diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..3550a30 --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +use flake diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md new file mode 100644 index 0000000..9590be1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -0,0 +1,30 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps / command to reproduce the behavior: +``` +$ crunchy ... +``` + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Client (please complete the following information):** + - OS: [e.g. Windows] + - Version [e.g. 3.0.0-dev.8 (17233f2 2023-01-10)] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..59094e2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/workflow-resources/PKGBUILD.binary b/.github/workflow-resources/PKGBUILD.binary new file mode 100644 index 0000000..00fee47 --- /dev/null +++ b/.github/workflow-resources/PKGBUILD.binary @@ -0,0 +1,48 @@ +# Maintainer: ByteDream +pkgname=crunchy-cli-bin +pkgdesc="Command-line downloader for Crunchyroll" +arch=('x86_64' 'aarch64') +url="https://github.com/crunchy-labs/crunchy-cli" +license=('MIT') + +pkgver=$CI_PKG_VERSION +pkgrel=1 + +depends=('ffmpeg') +provides=('crunchy-cli') +conflicts=('crunchy-cli') +source_x86_64=( + "crunchy-cli::https://github.com/crunchy-labs/crunchy-cli/releases/download/v${pkgver}/crunchy-cli-v${pkgver}-linux-x86_64" + "manpages.zip::https://github.com/crunchy-labs/crunchy-cli/releases/download/v${pkgver}/crunchy-cli-v${pkgver}-manpages.zip" + "completions.zip::https://github.com/crunchy-labs/crunchy-cli/releases/download/v${pkgver}/crunchy-cli-v${pkgver}-completions.zip" + "LICENSE::https://raw.githubusercontent.com/crunchy-labs/crunchy-cli/v${pkgver}/LICENSE" +) +source_aarch64=( + "crunchy-cli::https://github.com/crunchy-labs/crunchy-cli/releases/download/v${pkgver}/crunchy-cli-v${pkgver}-linux-aarch64" + "manpages.zip::https://github.com/crunchy-labs/crunchy-cli/releases/download/v${pkgver}/crunchy-cli-v${pkgver}-manpages.zip" + "completions.zip::https://github.com/crunchy-labs/crunchy-cli/releases/download/v${pkgver}/crunchy-cli-v${pkgver}-completions.zip" + "LICENSE::https://raw.githubusercontent.com/crunchy-labs/crunchy-cli/v${pkgver}/LICENSE" +) +noextract=("manpages.zip" "completions.zip") +sha256sums_x86_64=('$CI_AMD_BINARY_SHA_SUM' '$CI_MANPAGES_SHA_SUM' '$CI_COMPLETIONS_SHA_SUM' '$CI_LICENSE_SHA_SUM') +sha256sums_aarch64=('$CI_ARM_BINARY_SHA_SUM' '$CI_MANPAGES_SHA_SUM' '$CI_COMPLETIONS_SHA_SUM' '$CI_LICENSE_SHA_SUM') + +package() { + cd "$srcdir" + + # all files in manpages.zip and completions.zip are stored in root of the archive, makepkg extracts them all to $srcdir + # which makes it pretty messy. so the extraction is done manually to keep the content of $srcdir structured + mkdir manpages completions + cd manpages + bsdtar -xf ../manpages.zip + cd ../completions + bsdtar -xf ../completions.zip + cd .. + + install -Dm755 crunchy-cli $pkgdir/usr/bin/crunchy-cli + install -Dm644 manpages/* -t $pkgdir/usr/share/man/man1 + install -Dm644 completions/crunchy-cli.bash $pkgdir/usr/share/bash-completion/completions/crunchy-cli + install -Dm644 completions/_crunchy-cli $pkgdir/usr/share/zsh/site-functions/_crunchy-cli + install -Dm644 completions/crunchy-cli.fish $pkgdir/usr/share/fish/vendor_completions.d/crunchy-cli.fish + install -Dm644 LICENSE $pkgdir/usr/share/licenses/crunchy-cli/LICENSE +} diff --git a/.github/workflow-resources/PKGBUILD.source b/.github/workflow-resources/PKGBUILD.source new file mode 100644 index 0000000..4b14f5b --- /dev/null +++ b/.github/workflow-resources/PKGBUILD.source @@ -0,0 +1,46 @@ +# Maintainer: ByteDream +pkgname=crunchy-cli +pkgdesc="Command-line downloader for Crunchyroll" +arch=('x86_64' 'i686' 'arm' 'armv6h' 'armv7h' 'aarch64') +url="https://github.com/crunchy-labs/crunchy-cli" +license=('MIT') + +pkgver=$CI_PKG_VERSION +pkgrel=1 + +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 RUSTUP_TOOLCHAIN=stable + export CARGO_HOME="$srcdir/cargo-home" + + export CRUNCHY_CLI_GIT_HASH=$CI_GIT_HASH + cargo build --frozen --release +} + +package() { + cd "$srcdir/${pkgname}-$pkgver" + + install -Dm755 target/release/crunchy-cli $pkgdir/usr/bin/crunchy-cli + install -Dm644 target/release/manpages/* -t $pkgdir/usr/share/man/man1 + install -Dm644 target/release/completions/crunchy-cli.bash $pkgdir/usr/share/bash-completion/completions/crunchy-cli + install -Dm644 target/release/completions/_crunchy-cli $pkgdir/usr/share/zsh/site-functions/_crunchy-cli + install -Dm644 target/release/completions/crunchy-cli.fish $pkgdir/usr/share/fish/vendor_completions.d/crunchy-cli.fish + install -Dm644 LICENSE $pkgdir/usr/share/licenses/crunchy-cli/LICENSE +} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..9248ca5 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,145 @@ +name: build + +on: + push: + branches: + - '*' + pull_request: + workflow_dispatch: + +jobs: + build-linux: + runs-on: ubuntu-latest + strategy: + matrix: + include: + - arch: x86_64 + toolchain: x86_64-unknown-linux-musl + - arch: aarch64 + toolchain: aarch64-unknown-linux-musl + 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: ${{ matrix.toolchain }}-cargo-${{ hashFiles('**/Cargo.lock') }} + + - name: Setup Rust + uses: dtolnay/rust-toolchain@stable + with: + toolchain: stable + + - name: Install cross + run: cargo install --force cross + + - name: Build + run: cross build --locked --release --no-default-features --features openssl-tls-static --target ${{ matrix.toolchain }} + + - name: Upload binary artifact + 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 + 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 + 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: ${{ 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 + if: ${{ matrix.os != 'macos-13' }} # when using cache, the 'Setup Rust' step fails for macos 13 + uses: actions/cache@v4 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: x86_64-apple-darwin-cargo-${{ hashFiles('**/Cargo.lock') }} + + - name: Setup Rust + uses: dtolnay/rust-toolchain@stable + with: + toolchain: stable + + - name: Build + run: cargo build --locked --release --target ${{ matrix.toolchain }} + + - name: Upload binary artifact + uses: actions/upload-artifact@v4 + with: + name: crunchy-cli-darwin-${{ matrix.arch }} + path: ./target/${{ matrix.toolchain }}/release/crunchy-cli + if-no-files-found: error + + build-windows: + runs-on: windows-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-pc-windows-gnu-cargo-${{ hashFiles('**/Cargo.lock') }} + + - name: Install system dependencies + uses: msys2/setup-msys2@v2 + with: + update: true + install: mingw-w64-x86_64-rust base-devel + + - name: Build + shell: msys2 {0} + run: cargo build --locked --release --target x86_64-pc-windows-gnu + + - name: Upload binary artifact + uses: actions/upload-artifact@v4 + with: + name: crunchy-cli-windows-x86_64 + path: ./target/x86_64-pc-windows-gnu/release/crunchy-cli.exe + if-no-files-found: error 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 new file mode 100644 index 0000000..8f178ce --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,74 @@ +name: publish + +on: + push: + tags: + - v* + +jobs: + publish-aur: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Get version + run: echo "RELEASE_VERSION=$(echo ${{ github.ref_name }} | cut -c 2-)" >> $GITHUB_ENV + + - name: Generate crunchy-cli sha sum + run: | + 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 }} + 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 + with: + pkgname: crunchy-cli + pkgbuild: ./PKGBUILD + commit_username: release-action + commit_email: ${{ secrets.AUR_EMAIL }} + ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }} + commit_message: Update to version ${{ env.RELEASE_VERSION }} + + - name: Generate crunchy-cli-bin sha sums + run: | + curl -LO https://github.com/crunchy-labs/crunchy-cli/releases/download/${{ github.ref_name }}/crunchy-cli-${{ github.ref_name }}-linux-x86_64 + curl -LO https://github.com/crunchy-labs/crunchy-cli/releases/download/${{ github.ref_name }}/crunchy-cli-${{ github.ref_name }}-linux-aarch64 + curl -LO https://github.com/crunchy-labs/crunchy-cli/releases/download/${{ github.ref_name }}/crunchy-cli-${{ github.ref_name }}-completions.zip + curl -LO https://github.com/crunchy-labs/crunchy-cli/releases/download/${{ github.ref_name }}/crunchy-cli-${{ github.ref_name }}-manpages.zip + curl -LO https://raw.githubusercontent.com/crunchy-labs/crunchy-cli/${{ github.ref_name }}/LICENSE + echo "CRUNCHY_CLI_BIN_x86_64_SHA256=$(sha256sum crunchy-cli-${{ github.ref_name }}-linux-x86_64 | cut -f 1 -d ' ')" >> $GITHUB_ENV + echo "CRUNCHY_CLI_BIN_aarch64_SHA256=$(sha256sum crunchy-cli-${{ github.ref_name }}-linux-aarch64 | cut -f 1 -d ' ')" >> $GITHUB_ENV + echo "CRUNCHY_CLI_BIN_COMPLETIONS_SHA256=$(sha256sum crunchy-cli-${{ github.ref_name }}-completions.zip | cut -f 1 -d ' ')" >> $GITHUB_ENV + echo "CRUNCHY_CLI_BIN_MANPAGES_SHA256=$(sha256sum crunchy-cli-${{ github.ref_name }}-manpages.zip | cut -f 1 -d ' ')" >> $GITHUB_ENV + echo "CRUNCHY_CLI_BIN_LICENSE_SHA256=$(sha256sum LICENSE | cut -f 1 -d ' ')" >> $GITHUB_ENV + + - name: Generate crunchy-cli-bin PKGBUILD + env: + CI_PKG_VERSION: ${{ env.RELEASE_VERSION }} + CI_AMD_BINARY_SHA_SUM: ${{ env.CRUNCHY_CLI_BIN_x86_64_SHA256 }} + CI_ARM_BINARY_SHA_SUM: ${{ env.CRUNCHY_CLI_BIN_aarch64_SHA256 }} + 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/workflow-resources/PKGBUILD.binary > PKGBUILD + + - name: Publish crunchy-cli-bin to AUR + uses: KSXGitHub/github-actions-deploy-aur@v2.7.0 + with: + pkgname: crunchy-cli-bin + pkgbuild: ./PKGBUILD + commit_username: release-action + commit_email: ${{ secrets.AUR_EMAIL }} + ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }} + commit_message: Update to version ${{ env.RELEASE_VERSION }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..76cbb0a --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# Rust +/target + +# Editor +/.idea +/.vscode + +# Nix +/result +/.direnv diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..d01a80c --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2506 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "addr2line" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "0.6.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b" + +[[package]] +name = "anstyle-parse" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64c907d4e79225ac72e2a354c9ce84d50ebb4586dee56c82b3ee73004f537f5" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" +dependencies = [ + "anstyle", + "windows-sys 0.52.0", +] + +[[package]] +name = "anyhow" +version = "1.0.86" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" + +[[package]] +name = "async-speed-limit" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97d287ccbfb44ae20287d2f9c72ad9e560d50810883870697db5b320c541f183" +dependencies = [ + "futures-core", + "futures-io", + "futures-timer", + "pin-project-lite", +] + +[[package]] +name = "async-trait" +version = "0.1.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" + +[[package]] +name = "backtrace" +version = "0.3.71" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +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" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba368df5de76a5bea49aaf0cf1b39ccfbbef176924d1ba5db3e4135216cbe3c7" +dependencies = [ + "base64 0.21.7", + "serde", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" + +[[package]] +name = "bumpalo" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" + +[[package]] +name = "bytes" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" + +[[package]] +name = "cc" +version = "1.0.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41c270e7540d725e65ac7f1b212ac8ce349719624d7bcff99f8e2e488e8cf03f" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +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", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-targets 0.52.5", +] + +[[package]] +name = "clap" +version = "4.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_complete" +version = "4.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd79504325bf38b10165b02e89b4347300f855f273c4cb30c4a3209e6583275e" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" + +[[package]] +name = "clap_mangen" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1dd95b5ebb5c1c54581dd6346f3ed6a79a3eef95dd372fc2ac13d535535300e" +dependencies = [ + "clap", + "roff", +] + +[[package]] +name = "colorchoice" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" + +[[package]] +name = "console" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb" +dependencies = [ + "encode_unicode", + "lazy_static", + "libc", + "unicode-width", + "windows-sys 0.52.0", +] + +[[package]] +name = "cookie" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7efb37c3e1ccb1ff97164ad95ac1606e8ccd35b3fa0a7d99a304c7f4a428cc24" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "387461abbc748185c3a6e1673d826918b450b87ff22639429c694619a83b6cf6" +dependencies = [ + "cookie", + "idna 0.3.0", + "log", + "publicsuffix", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" + +[[package]] +name = "crunchy-cli" +version = "3.6.7" +dependencies = [ + "chrono", + "clap", + "clap_complete", + "clap_mangen", + "crunchy-cli-core", + "native-tls", + "tokio", +] + +[[package]] +name = "crunchy-cli-core" +version = "3.6.7" +dependencies = [ + "anyhow", + "async-speed-limit", + "chrono", + "clap", + "crunchyroll-rs", + "ctrlc", + "derive_setters", + "dialoguer", + "dirs", + "fs2", + "futures-util", + "http", + "indicatif", + "lazy_static", + "log", + "nix", + "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", +] + +[[package]] +name = "crunchyroll-rs" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6e38c223aecf65c9c9bec50764beea5dc70b6c97cd7f767bf6860f2fc8e0a07" +dependencies = [ + "async-trait", + "chrono", + "crunchyroll-rs-internal", + "dash-mpd", + "futures-util", + "jsonwebtoken", + "lazy_static", + "regex", + "reqwest", + "rustls", + "serde", + "serde_json", + "serde_urlencoded", + "smart-default", + "tokio", + "tower-service", + "uuid", + "webpki-roots", +] + +[[package]] +name = "crunchyroll-rs-internal" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144a38040a21aaa456741a9f6749354527bb68ad3bb14210e0bbc40fbd95186c" +dependencies = [ + "darling", + "quote", + "syn", +] + +[[package]] +name = "ctrlc" +version = "3.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "672465ae37dc1bc6380a6547a8883d5dd397b0f1faaad4f265726cc7042a5345" +dependencies = [ + "nix", + "windows-sys 0.52.0", +] + +[[package]] +name = "darling" +version = "0.20.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83b2eb4d90d12bdda5ed17de686c2acb4c57914f8f921b8da7e112b5a36f3fe1" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622687fe0bac72a04e5599029151f5796111b90f1baaa9b544d807a5e31cd120" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn", +] + +[[package]] +name = "darling_macro" +version = "0.20.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "733cabb43482b1a1b53eee8583c2b9e8684d592215ea83efd305dd31bc2f0178" +dependencies = [ + "darling_core", + "quote", + "syn", +] + +[[package]] +name = "dash-mpd" +version = "0.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4618a5e165bf47b084963611bcf1d568c681f52d8a237e8862a0cd8c546ba255" +dependencies = [ + "base64 0.22.1", + "base64-serde", + "bytes", + "chrono", + "fs-err", + "iso8601", + "lazy_static", + "num-traits", + "quick-xml", + "regex", + "serde", + "serde_path_to_error", + "serde_with", + "thiserror", + "tracing", + "url", + "xattr", +] + +[[package]] +name = "deranged" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", + "serde", +] + +[[package]] +name = "derive_setters" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e8ef033054e131169b8f0f9a7af8f5533a9436fadf3c500ed547f730f07090d" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "dialoguer" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "658bce805d770f407bc62102fca7c2c64ceef2fbcb2b8bd19d2765ce093980de" +dependencies = [ + "console", + "shell-words", + "thiserror", +] + +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.48.0", +] + +[[package]] +name = "either" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b" + +[[package]] +name = "encode_unicode" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" + +[[package]] +name = "encoding_rs" +version = "0.8.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "errno" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "fastrand" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs-err" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a41f105fe1d5b6b34b2055e3dc59bb79b46b48b2040b9e6c7b4b5de097aa41" +dependencies = [ + "autocfg", +] + +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "futures-channel" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" + +[[package]] +name = "futures-io" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" + +[[package]] +name = "futures-macro" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" + +[[package]] +name = "futures-task" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" + +[[package]] +name = "futures-timer" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" + +[[package]] +name = "futures-util" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "gimli" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" + +[[package]] +name = "h2" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa82e28a107a8cc405f0839610bdc9b15f1e25ec7d696aa5cf173edbcb1486ab" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap 2.2.6", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +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", +] + +[[package]] +name = "httparse" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" + +[[package]] +name = "hyper" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe575dd17d0862a9a33781c8c4696a55c320909004a67a00fb286ba8b1bc496d" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0bea761b46ae2b24eb4aef630d8d1c398157b6fc29e6350ecf090a0b70c952c" +dependencies = [ + "futures-util", + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +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.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "idna" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" +dependencies = [ + "equivalent", + "hashbrown 0.14.5", + "serde", +] + +[[package]] +name = "indicatif" +version = "0.17.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "763a5a8f45087d6bcea4222e7b72c291a054edf80e4ef6efd2a4979878c7bea3" +dependencies = [ + "console", + "instant", + "number_prefix", + "portable-atomic", + "unicode-width", +] + +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "ipnet" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924e5d73ea28f59011fec52a0d12185d496a9b075d360657aed2a5707f701153" +dependencies = [ + "nom", +] + +[[package]] +name = "itoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" + +[[package]] +name = "js-sys" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.155" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" + +[[package]] +name = "libredox" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +dependencies = [ + "bitflags 2.5.0", + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" + +[[package]] +name = "log" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" + +[[package]] +name = "memchr" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" + +[[package]] +name = "mime" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87dfd01fe195c66b572b37921ad8803d010623c0aca821bea2302239d155cdae" +dependencies = [ + "adler", +] + +[[package]] +name = "mio" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.48.0", +] + +[[package]] +name = "native-tls" +version = "0.2.12" +source = "git+https://github.com/crunchy-labs/rust-not-so-native-tls.git?rev=c7ac566#c7ac566559d441bbc3e5e5bd04fb7162c38d88b0" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "nix" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" +dependencies = [ + "bitflags 2.5.0", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +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", +] + +[[package]] +name = "num_cpus" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "number_prefix" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" + +[[package]] +name = "object" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" + +[[package]] +name = "openssl" +version = "0.10.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" +dependencies = [ + "bitflags 2.5.0", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "openssl-src" +version = "300.3.0+3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eba8804a1c5765b18c4b3f907e6897ebabeedebc9830e1a0046c4a4cf44663e1" +dependencies = [ + "cc", +] + +[[package]] +name = "openssl-sys" +version = "0.9.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2" +dependencies = [ + "cc", + "libc", + "openssl-src", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "percent-encoding" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" + +[[package]] +name = "pin-project" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" + +[[package]] +name = "portable-atomic" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7170ef9988bc169ba16dd36a7fa041e5c4cbeb6a35b76d4c03daded371eae7c0" + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "primal-check" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df7f93fd637f083201473dab4fee2db4c429d32e55e3299980ab3957ab916a0" +dependencies = [ + "num-integer", +] + +[[package]] +name = "proc-macro2" +version = "1.0.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b33eb56c327dec362a9e55b3ad14f9d2f0904fb5a5b03b513ab5465399e9f43" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "psl-types" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" + +[[package]] +name = "publicsuffix" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96a8c1bda5ae1af7f99a2962e49df150414a43d62404644d98dd5c3a93d07457" +dependencies = [ + "idna 0.3.0", + "psl-types", +] + +[[package]] +name = "quick-xml" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1004a344b30a54e2ee58d66a71b32d2db2feb0a31f9a2d302bf0536f15de2a33" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "quote" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "realfft" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "953d9f7e5cdd80963547b456251296efc2626ed4e3cbf36c869d9564e0220571" +dependencies = [ + "rustfft", +] + +[[package]] +name = "redox_users" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd283d9651eeda4b2a83a43c1c91b266c40fd76ecd39a50a8c630ae69dc72891" +dependencies = [ + "getrandom", + "libredox", + "thiserror", +] + +[[package]] +name = "regex" +version = "1.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" + +[[package]] +name = "reqwest" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "566cafdd92868e0939d3fb961bd0dc25fcfaaed179291093b3d43e6b3150ea10" +dependencies = [ + "base64 0.22.1", + "bytes", + "cookie", + "cookie_store", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "ipnet", + "js-sys", + "log", + "mime", + "mime_guess", + "native-tls", + "once_cell", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pemfile", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "system-configuration", + "tokio", + "tokio-native-tls", + "tokio-rustls", + "tokio-socks", + "tokio-util", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", + "winreg", +] + +[[package]] +name = "ring" +version = "0.17.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "spin", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "roff" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b833d8d034ea094b1ea68aa6d5c740e0d04bad9d16568d08ba6f76823a114316" + +[[package]] +name = "rsubs-lib" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +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.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" +dependencies = [ + "bitflags 2.5.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" +dependencies = [ + "log", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fb85efa936c42c6d5fc28d2629bb51e4b2f4b8a5211e297d599cc5a093792" +dependencies = [ + "openssl-probe", + "rustls-pemfile", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pemfile" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" +dependencies = [ + "base64 0.22.1", + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d" + +[[package]] +name = "rustls-webpki" +version = "0.102.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff448f7e92e913c4b7d4c6d8e4540a1724b319b4152b8aef6d4cf8339712b33e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rusty-chromaprint" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1755646867c36ecb391776deaa0b557a76d3badf20c142de7282630c34b20440" +dependencies = [ + "rubato", + "rustfft", +] + +[[package]] +name = "ryu" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" + +[[package]] +name = "schannel" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "security-framework" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c627723fd09706bacdb5cf41499e95098555af3c3c29d014dc3c458ef6be11c0" +dependencies = [ + "bitflags 2.5.0", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "317936bbbd05227752583946b9e66d7ce3b489f84e11a94a510b4437fef407d7" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.202" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "226b61a0d411b2ba5ff6d7f73a476ac4f8bb900373459cd00fab8512828ba395" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.202" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6048858004bcff69094cd972ed40a32500f153bd3be9f716b2eed2e8217c4838" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af99884400da37c88f5e9146b7f1fd0fbcae8f6eec4e9da38b67d05486f814a6" +dependencies = [ + "itoa", + "serde", +] + +[[package]] +name = "serde_plain" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ad483d2ab0149d5a5ebcd9972a3852711e0153d863bf5a5d0391d28883c4a20" +dependencies = [ + "base64 0.22.1", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.2.6", + "serde", + "serde_derive", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65569b702f41443e8bc8bbb1c5779bd0450bbe723b56198980e80ec45780bce2" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "shell-words" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde" + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "slab" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eb01866308440fc64d6c44d9e86c5cc17adfe33c4d6eed55da9145044d0ffc1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "socket2" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + +[[package]] +name = "strsim" +version = "0.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.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e801cf239ecd6ccd71f03d270d67dd53d13e90aab208bf4b8fe4ad957ea949b0" +dependencies = [ + "libc", +] + +[[package]] +name = "system-configuration" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tempfile" +version = "3.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" +dependencies = [ + "cfg-if", + "fastrand", + "rustix", + "windows-sys 0.52.0", +] + +[[package]] +name = "thiserror" +version = "1.0.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "time" +version = "0.3.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" + +[[package]] +name = "time-macros" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinyvec" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a" +dependencies = [ + "backtrace", + "bytes", + "libc", + "mio", + "num_cpus", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.48.0", +] + +[[package]] +name = "tokio-macros" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" +dependencies = [ + "rustls", + "rustls-pki-types", + "tokio", +] + +[[package]] +name = "tokio-socks" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51165dfa029d2a65969413a6cc96f354b86b464498702f174a4efa13608fd8c0" +dependencies = [ + "either", + "futures-util", + "thiserror", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" + +[[package]] +name = "tracing" +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", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicase" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicode-bidi" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "unicode-normalization" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-width" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f5e5f3158ecfd4b8ff6fe086db7c8467a2dfdac97fe420f2b7c4aa97af66d6" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" +dependencies = [ + "form_urlencoded", + "idna 0.5.0", + "percent-encoding", +] + +[[package]] +name = "utf8parse" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" + +[[package]] +name = "wasm-streams" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b65dc4c90b63b118468cf747d8bf3566c1913ef60be765b5730ead9e0a3ba129" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3de34ae270483955a94f4b21bdaaeb83d508bb84a01435f393818edb0012009" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets 0.52.5", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.5", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" +dependencies = [ + "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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" + +[[package]] +name = "winreg" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5" +dependencies = [ + "cfg-if", + "windows-sys 0.48.0", +] + +[[package]] +name = "xattr" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +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 new file mode 100644 index 0000000..c1e28bb --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "crunchy-cli" +authors = ["Crunchy Labs Maintainers"] +version = "3.6.7" +edition = "2021" +license = "MIT" + +[features] +default = ["native-tls"] + +rustls-tls = ["crunchy-cli-core/rustls-tls"] +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"] + +[dependencies] +tokio = { version = "1.38", features = ["macros", "rt-multi-thread", "time"], default-features = false } + +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.5", features = ["string"] } +clap_complete = "4.5" +clap_mangen = "0.2" + +crunchy-cli-core = { path = "./crunchy-cli-core" } + +[workspace] +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 = "c7ac566" } + +[profile.release] +strip = true +opt-level = "z" +lto = true diff --git a/LICENSE b/LICENSE index 36688ae..512eb1b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,61 +1,25 @@ -Copyright © 2007 Free Software Foundation, Inc. +Copyright (c) 2023-NOW Crunchy Labs Team -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: -This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. -0. Additional Definitions. +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. -As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License. - -“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. - -An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. - -A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”. - -The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. - -The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. -1. Exception to Section 3 of the GNU GPL. - -You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. -2. Conveying Modified Versions. - -If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: - - a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or - b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. - -3. Object Code Incorporating Material from Library Header Files. - -The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. - b) Accompany the object code with a copy of the GNU GPL and this license document. - -4. Combined Works. - -You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: - - a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. - b) Accompany the Combined Work with a copy of the GNU GPL and this license document. - c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. - d) Do one of the following: - 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. - 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. - e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) - -5. Combined Libraries. - -You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. - b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. - -6. Revised Versions of the GNU Lesser General Public License. - -The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. - -If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/Makefile b/Makefile deleted file mode 100644 index 2610180..0000000 --- a/Makefile +++ /dev/null @@ -1,17 +0,0 @@ -VERSION=1.0.1 -BINARY_NAME=crunchy -VERSION_BINARY_NAME=$(BINARY_NAME)-v$(VERSION) - -build: - cd cmd/crunchyroll-go && go build -o $(BINARY_NAME) - mv cmd/crunchyroll-go/$(BINARY_NAME) . - -test: - go test -v . - -release: - cd cmd/crunchyroll-go && GOOS=linux GOARCH=amd64 go build -o $(VERSION_BINARY_NAME)_linux - cd cmd/crunchyroll-go && GOOS=windows GOARCH=amd64 go build -o $(VERSION_BINARY_NAME)_windows.exe - cd cmd/crunchyroll-go && GOOS=darwin GOARCH=amd64 go build -o $(VERSION_BINARY_NAME)_darwin - - mv cmd/crunchyroll-go/$(VERSION_BINARY_NAME)_* . diff --git a/README.md b/README.md index 4769bf5..1ae2645 100644 --- a/README.md +++ b/README.md @@ -1,331 +1,734 @@ -# crunchyroll-go +# This project has been sunset as Crunchyroll moved to a DRM-only system. See [#362](https://github.com/crunchy-labs/crunchy-cli/issues/362). -A [Go](https://golang.org) library & cli for the undocumented [crunchyroll](https://www.crunchyroll.com) api. +# crunchy-cli -**You surely need a crunchyroll premium account to get full (api) access.** +👇 A Command-line downloader for [Crunchyroll](https://www.crunchyroll.com).

- - Code size + + Code size - - License + + Download Badge - - Go version + + License - - Release + + Release + + + Discord + + + Build

- CLI 🖥️ + Usage 🖥️ • - Library 📚 - • - Credits 🙏 + Disclaimer 📜License ⚖

-## 🖥️ CLI +> We are in no way affiliated with, maintained, authorized, sponsored, or officially associated with Crunchyroll LLC or any of its subsidiaries or affiliates. +> The official Crunchyroll website can be found at [www.crunchyroll.com](https://www.crunchyroll.com/). -#### ✨ Features -- Download single videos and entire series from [crunchyroll](https://www.crunchyroll.com) +## ✨ Features -#### Get the executable -- 📥 Download the latest binaries [here](https://github.com/ByteDream/crunchyroll-go/releases/latest) or get it from below - - [Linux (x64)](https://github.com/ByteDream/crunchyroll-go/releases/download/v1.0.1/crunchy-v1.0.1_linux) - - [Windows (x64)](https://github.com/ByteDream/crunchyroll-go/releases/download/v1.0.1/crunchy-v1.0.1_windows.exe) - - [MacOS (x64)](https://github.com/ByteDream/crunchyroll-go/releases/download/v1.0.1/crunchy-v1.0.1_darwin) -- 🛠 Build it yourself - - use `make` (requires `go` to be installed) - ``` - $ git clone https://github.com/ByteDream/crunchyroll-go - $ cd crunchyroll-go - $ make - ``` - - use `go` - ``` - $ git clone https://github.com/ByteDream/crunchyroll-go - $ cd crunchyroll-go/cmd/crunchyroll-go - $ go build -o crunchy +- Download single videos and entire series from [Crunchyroll](https://www.crunchyroll.com). +- Archive episodes or seasons in an `.mkv` file with multiple subtitles and audios. +- Specify a range of episodes to download from an anime. +- Search through the Crunchyroll collection and return metadata (title, duration, direct stream link, ...) of all media types. + +## 💾 Get the executable + +### 📥 Download the latest binaries + +Check out the [releases](https://github.com/crunchy-labs/crunchy-cli/releases) tab and get the binary from the latest (pre-)release. + +### 📦 Get it via a package manager + +- [AUR](https://aur.archlinux.org/) + + If you're using Arch or an Arch based Linux distribution you are able to install our [AUR](https://aur.archlinux.org/) package. + You need an [AUR helper](https://wiki.archlinux.org/title/AUR_helpers) like [yay](https://github.com/Jguer/yay) to install it. + + ```shell + # this package builds crunchy-cli manually (recommended) + $ yay -S crunchy-cli + # this package installs the latest pre-compiled release binary + $ yay -S crunchy-cli-bin ``` -### 📝 Examples +- [Scoop](https://scoop.sh/) -#### Login -Before you can do something, you have to login first. + For Windows users, we support the [scoop](https://scoop.sh/#/) command-line installer. -This can be performed via crunchyroll account email and password -``` -$ crunchy login user@example.com password -``` - -or via session id -``` -$ crunchy login --session-id 8e9gs135defhga790dvrf2i0eris8gts -``` - -#### Download - -**With the cli you can download single videos or entire series.** - -By default the cli tries to download the episode with your system language as audio. -If no streams with your system language are available, the video will be downloaded with japanese audio and hardsubbed subtitles in your system language. -**If your system language is not supported, an error message will be displayed and en-US (american english) will be chosen as language.** - -``` -$ crunchy download https://www.crunchyroll.com/darling-in-the-franxx/episode-1-alone-and-lonesome-759575 -``` - -With `-r best` the video(s) will have the best available resolution (mostly 1920x1080 / Full HD). - -``` -$ crunchy download -r best https://www.crunchyroll.com/darling-in-the-franxx/episode-1-alone-and-lonesome-759575 -``` - -The file is by default saved as a `.ts` (mpeg transport stream) file. -`.ts` files may can't be played or are looking very weird (it depends on the video player you are using). -With the `-o` flag, you can change the name (and file ending) of the output file. -So if you want to save it as, for example, `mp4` file, just name it `whatever.mp4`. -**You need [ffmpeg](https://ffmpeg.org) to store the video in other file formats.** - -``` -$ crunchy download -o "daaaaaaaaaaaaaaaarling.ts" https://www.crunchyroll.com/darling-in-the-franxx/episode-1-alone-and-lonesome-759575 -``` - -With the `--audio` flag you can specify which audio the video should have and with `--subtitle` which subtitle it should have. -Type `crunchy help download` to see all available locales. - -``` -$ crunchy download --audio ja-JP --subtitle de-DE https://www.crunchyroll.com/darling-in-the-franxx -``` - -##### Flags -- `--audio` » forces audio of the video(s) -- `--subtitle` » forces subtitle of the video(s) -- `--no-hardsub` » forces that the subtitles are stored as a separate file and are not directly embedded into the video - -- `-d`, `--directory` » directory to download the video(s) to -- `-o`, `--output` » name of the output file - -- `-r`, `--resolution` » the resolution of the video(s). `best` for best resolution, `worst` for worst - -- `--alternative-progress` » shows an alternative, not so user-friendly progress instead of the progress bar - -#### Help -- General help - ``` - $ crunchy help - ``` -- Login help - ``` - $ crunchy help login - ``` -- Download help - ``` - $ crunchy help download + ```shell + $ scoop bucket add extras + $ scoop install extras/crunchy-cli ``` -#### Global flags -These flags you can use across every sub-command +- [Homebrew](https://brew.sh/) -- `-q`, `--quiet` » disables all output -- `-v`, `--verbote` » shows additional debug output -- `--color` » adds color to the output (works only on not windows systems) + For macOS/linux users, we support the [brew](https://brew.sh/#/) command-line installer. Packages are compiled by the [homebrew project](https://formulae.brew.sh/formula/crunchy-cli), and will also install the `openssl@3` and `ffmpeg` dependencies. -- `-p`, `--proxy` » use a proxy to hide your ip / redirect your traffic + ```shell + $ brew install crunchy-cli + ``` -- `-l`, `--locale` » the language to display video specific things like the title. default is your system language + Supported archs: `x86_64_linux`, `arm64_monterey`, `sonoma`, `ventura` -## 📚 Library -Download the library via `go get` +- [Nix](https://nixos.org/) -``` -$ go get github.com/ByteDream/crunchyroll-go + This requires [nix](https://nixos.org) and you'll probably need `--extra-experimental-features "nix-command flakes"`, depending on your configurations. + + ```shell + $ nix github:crunchy-labs/crunchy-cli + ``` + +### 🛠 Build it yourself + +Since we do not support every platform and architecture you may have to build the project yourself. +This requires [git](https://git-scm.com/) and [Cargo](https://doc.rust-lang.org/cargo). + +```shell +$ git clone https://github.com/crunchy-labs/crunchy-cli +$ cd crunchy-cli +# either just build it (will be available in ./target/release/crunchy-cli)... +$ cargo build --release +# ... or install it globally +$ cargo install --force --path . ``` -### 📝 Examples -```go -func main() { - // login with credentials - crunchy, err := crunchyroll.LoginWithCredentials("user@example.com", "password", crunchyroll.US, http.DefaultClient) - if err != nil { - panic(err) - } +## 🖥️ Usage - // finds a series or movie by a crunchyroll link - video, err := crunchy.FindVideo("https://www.crunchyroll.com/darling-in-the-franxx") - if err != nil { - panic(err) - } +> All shown commands are examples 🧑🏼‍🍳 - series := video.(*crunchyroll.Series) - seasons, err := series.Seasons() - if err != nil { - panic(err) - } - fmt.Printf("Found %d seasons for series %s\n", len(seasons), series.Title) +### Global Flags - // search `Darling` and return 20 results - series, movies, err := crunchy.Search("Darling", 20) - if err != nil { - panic(err) - } - fmt.Printf("Found %d series and %d movies for query `Darling`\n", len(series), len(movies)) -} +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 + + ```shell + $ crunchy-cli --credentials "email:password" + ``` + +- Stay Anonymous + + Login without an account (you won't be able to access premium content): + + ```shell + $ crunchy-cli --anonymous + ``` + +### Global settings + +You can set specific settings which will be + +- Verbose output + + If you want to include debug information in the output, use the `-v` / `--verbose` flag to show it. + + ```shell + $ crunchy-cli -v + ``` + + This flag can't be used in combination with `-q` / `--quiet`. + +- 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). + + ```shell + $ crunchy-cli -q + ``` + + 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. + + ```shell + $ crunchy-cli --lang de-DE + ``` + +- 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. + As the *experimental* in `--experimental-fixes` states, these fixes may or may not break other functionality. + + ```shell + $ crunchy-cli --experimental-fixes + ``` + + 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 + + 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 + ``` + + 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 + + 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. + + ```shell + $ crunchy-cli --user-agent "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)" + ``` + + Default is the user agent, defined in the underlying [library](https://github.com/crunchy-labs/crunchyroll-rs). + +- 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). + + ```shell + $ crunchy-cli --speed-limit 10MB + ``` + +### Login + +The `login` command can store your session, so you don't have to authenticate every time you execute a command. + +```shell +# 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" ``` -```go -func main() { - crunchy, err := crunchyroll.LoginWithSessionID("8e9gs135defhga790dvrf2i0eris8gts", crunchyroll.US, http.DefaultClient) - if err != nil { - panic(err) - } +With the session stored, you do not need to pass `--credentials` / `--anonymous` anymore when you want to execute a command. - // returns an episode slice with all episodes which are matching the given url. - // the episodes in the returning slice differs from the underlying streams, but are all pointing to the first ditf episode - episodes, err := crunchy.FindEpisode("https://www.crunchyroll.com/darling-in-the-franxx/episode-1-alone-and-lonesome-759575") - if err != nil { - panic(err) - } - fmt.Printf("Found %d episodes\n", len(episodes)) -} +### Download + +The `download` command lets you download episodes with a specific audio language and optional subtitles. + +**Supported urls** + +- Single episode (with [episode filtering](#episode-filtering)) + ```shell + $ crunchy-cli download https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + ``` +- Series (with [episode filtering](#episode-filtering)) + ```shell + $ crunchy-cli download https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + +**Options** + +- 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. + + ```shell + $ crunchy-cli download -a de-DE https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + Default is your system locale. If not supported by Crunchyroll, `en-US` (American English) is the default. + +- 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. + + ```shell + $ crunchy-cli download -s de-DE https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + Default is none. + +- Output template + + Define an output template by using the `-o` / `--output` flag. + + ```shell + $ crunchy-cli download -o "ditf.mp4" https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + ``` + + Default is `{title}.mp4`. See the [Template Options section](#output-template-options) below for more options. + +- 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 "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. + +- 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. + + ```shell + $ crunchy-cli download -r worst https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + ``` + + Default is `best`. + +- 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 download --ffmpeg-preset av1-lossless https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + ``` + +- 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`. + + ```shell + $ crunchy-cli download --ffmpeg-threads 4 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + ``` + +- 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. + + ```shell + $ crunchy-cli download --skip-existing 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. + + ```shell + $ crunchy-cli download --skip-specials https://www.crunchyroll.com/series/GYZJ43JMR/that-time-i-got-reincarnated-as-a-slime[S2] + ``` + +- 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. + + ```shell + $ crunchy-cli download --yes https://www.crunchyroll.com/series/GR49G9VP6/sword-art-online + ``` + + If you've passed the `-q` / `--quiet` [global flag](#global-settings), this flag is automatically set. + +- 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. + + ```shell + $ crunchy-cli download --force-hardsub -s en-US https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + ``` + +- 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. + + ```shell + $ crunchy-cli download -t 1 https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + The default thread count is the count of cpu threads your pc has. + +### Archive + +The `archive` command lets you download episodes with multiple audios and subtitles and merges it into a `.mkv` file. + +**Supported urls** + +- Single episode (with [episode filtering](#episode-filtering)) + ```shell + $ crunchy-cli archive https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + ``` +- Series (with [episode filtering](#episode-filtering)) + ```shell + $ crunchy-cli archive https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + +**Options** + +- Audio languages + + Set the audio language with the `-a` / `--audio` flag. Can be used multiple times. + + ```shell + $ crunchy-cli archive -a ja-JP -a de-DE https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + Default is your system locale (if not supported by Crunchyroll, `en-US` (American English) and `ja-JP` (Japanese) are used). + +- Subtitle languages + + Besides the audio, you can specify the subtitle language by using the `-s` / `--subtitle` flag. + + ```shell + $ crunchy-cli archive -s de-DE https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + Default is `all` subtitles. + +- 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. + + ```shell + $ crunchy-cli archive -o "{title}.mkv" https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + Default is `{title}.mkv`. See the [Template Options section](#output-template-options) below for more options. + +- 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 "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. + +- 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. + + ```shell + $ crunchy-cli archive -r worst https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + Default is `best`. + +- Merge behavior + + Due to censorship or additional intros, some episodes have multiple lengths for different languages. + In the best case, when multiple audio & subtitle tracks are used, there is only one *video* track and all other languages can be stored as audio-only. + 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`; `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 + $ crunchy-cli archive -m audio https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + Default is `auto`. + +- 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`. + 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 archive --ffmpeg-preset av1-lossless https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + ``` + +- 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`. + + ```shell + $ crunchy-cli archive --ffmpeg-threads 4 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + ``` + +- Default subtitle + + `--default-subtitle` Set which subtitle language is to be flagged as **default** and **forced**. + + ```shell + $ crunchy-cli archive --default-subtitle en-US https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + Default is none. + +- 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. + + ```shell + $ crunchy-cli archive --include-fonts https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + +- 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. + + ```shell + $ crunchy-cli archive --skip-existing https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + +- 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. + + ```shell + $ crunchy-cli archive --skip-specials https://www.crunchyroll.com/series/GYZJ43JMR/that-time-i-got-reincarnated-as-a-slime[S2] + ``` + +- 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. + + ```shell + $ crunchy-cli archive --yes https://www.crunchyroll.com/series/GR49G9VP6/sword-art-online + ``` + + If you've passed the `-q` / `--quiet` [global flag](#global-settings), this flag is automatically set. + +- 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. + + ```shell + $ crunchy-cli archive -t 1 https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + The default thread count is the count of cpu threads your pc has. + +### 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)) + ```shell + $ crunchy-cli search https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome + ``` +- Series (with [episode filtering](#episode-filtering)) + ```shell + $ crunchy-cli search https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` +- Search input + ```shell + $ crunchy-cli search "darling in the franxx" + ``` + +**Options** + +- Audio + + Set the audio language to search via the `--audio` flag. Can be used multiple times. + + ```shell + $ crunchy-cli search --audio en-US https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + Default is your system locale. + +- 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. + `--search-series-limit` sets the limit of only series, `--search-movie-listing-limit` of only movie listings, `--search-episode-limit` of only episodes and `--search-music-limit` of only concerts and music videos. + + ```shell + $ crunchy-cli search --search-top-results-limit 10 "darling in the franxx" + # only return series which have 'darling' in it. do not return top results which might also be non-series items + $ crunchy-cli search --search-top-results-limit 0 --search-series-limit 10 "darling" + # this returns 2 top results, 3 movie listings, 5 episodes and 1 music item as result + $ crunchy-cli search --search-top-results-limit 2 --search-movie-listing-limit 3 --search-episode-limit 5 --search-music-limit 1 "test" + ``` + + Default is `5` for `--search-top-results-limit`, `0` for all others. + +- Output template + + The search command is designed to show only the specific information you want. + This is done with the `-o`/`--output` flag. + You can specify keywords in a specific pattern, and they will get replaced in the output text. + The required pattern for this begins with `{{`, then the keyword, and closes with `}}` (e.g. `{{episode.title}}`). + For example, if you want to get the title of an episode, you can use `Title: {{episode.title}}` and `{{episode.title}}` will be replaced with the episode title. + You can see all supported keywords with `crunchy-cli search --help`. + + ```shell + $ crunchy-cli search -o "{{series.title}}" https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx + ``` + + Default is `S{{season.number}}E{{episode.number}} - {{episode.title}}`. + +--- + +#### Output Template Options + +You can use various template options to change how the filename is processed. The following tags are available: + +- `{title}` → Title of the video +- `{series_name}` → Name of the series +- `{season_name}` → Name of the season +- `{audio}` → Audio language of the video +- `{width}` → Width of the video +- `{height}` → Height of the video +- `{season_number}` → Number of the season +- `{episode_number}` → Number of the episode +- `{relative_episode_number}` → Number of the episode relative to its season +- `{sequence_number}` → Like `{episode_number}` but without possible non-number characters +- `{relative_sequence_number}` → Like `{relative_episode_number}` but with support for episode 0's and .5's +- `{release_year}` → Release year of the video +- `{release_month}` → Release month of the video +- `{release_day} ` → Release day of the video +- `{series_id}` → ID of the series +- `{season_id}` → ID of the season +- `{episode_id}` → ID of the episode + +Example: + +```shell +$ crunchy-cli archive -o "[S{season_number}E{episode_number}] {title}.mkv" https://www.crunchyroll.com/series/G8DHV7W21/dragon-ball +# Output file: '[S01E01] Secret of the Dragon Ball.mkv' ``` -

Structure

+#### Episode filtering -Because of the apis structure, it can lead very fast much redundant code for simple tasks, like getting all episodes -with japanese audio and german subtitle. For this case and some other, the api has a utility called `Structure` in its utils. +Filters patterns can be used to download a specific range of episodes from a single series. -```go -func main() { - crunchy, err := crunchyroll.LoginWithCredentials("user@example.com", "password", crunchyroll.US, http.DefaultClient) - if err != nil { - panic(err) - } +A filter pattern may consist of either a season, an episode, or a combination of the two. +When used in combination, seasons `S` must be defined before episodes `E`. - // search `Darling` and return 20 results (series and movies) or less - series, movies, err := crunchy.Search("Darling", 20) - if err != nil { - panic(err) - } - fmt.Printf("Found %d series and %d movies for search query `Darling`\n", len(series), len(movies)) +There are many possible patterns, for example: - seasons, err := series[0].Seasons() - if err != nil { - panic(err) - } +- `...[E5]` - Download the fifth episode. +- `...[S1]` - Download the whole first season. +- `...[-S2]` - Download the first two seasons. +- `...[S3E4-]` - Download everything from season three, episode four, onwards. +- `...[S1E4-S3]` - Download season one, starting at episode four, then download season two and three. +- `...[S3,S5]` - Download season three and five. +- `...[S1-S3,S4E2-S4E6]` - Download season one to three, then episodes two to six from season four. - // in the crunchyroll.utils package, you find some structs which can be used to simplify tasks. - // you can recursively search all underlying content - seriesStructure := utils.NewSeasonStructure(seasons) +In practice, it would look like this: - // this returns every format of all the above given seasons - formats, err := seriesStructure.Formats() - if err != nil { - panic(err) - } - fmt.Printf("Found %d formats\n", len(formats)) - - filteredFormats, err := seriesStructure.FilterFormatsByLocales(crunchyroll.JP, crunchyroll.DE, true) - if err != nil { - panic(err) - } - fmt.Printf("Found %d formats with japanese audio and hardsubbed german subtitles\n", len(filteredFormats)) - - // reverse sorts the formats after their resolution by calling a sort type which is also defined in the api utils - // and stores the format with the highest resolution in a variable - sort.Sort(sort.Reverse(utils.FormatsByResolution(filteredFormats))) - format := formats[0] - // get the episode from which the format is a child - episode, err := seriesStructure.FilterEpisodeByFormat(format) - if err != nil { - panic(err) - } - - file, err := os.Create(fmt.Sprintf("%s.ts", episode.Title)) - if err != nil { - panic(err) - } - - // download the format to the file - if err := format.Download(file, nil); err != nil { - panic(err) - } - fmt.Printf("Downloaded %s with %s resolution and %.2f fps as %s\n", episode.Title, format.Video.Resolution, format.Video.FPS, file.Name()) - - // for more useful structure function just let your IDE's autocomplete make its thing -} +``` +https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx[E1-E5] ``` -As you can see in the example above, most of the `crunchyroll.utils` Structure functions are returning errors. There is -a build-in functionality with are avoiding causing the most errors and let you safely ignore them as well. -**Note that errors still can appear** +# 📜 Disclaimer -```go -func main() { - crunchy, err := crunchyroll.LoginWithCredentials("user@example.com", "password", crunchyroll.US, http.DefaultClient) - if err != nil { - panic(err) - } +This tool is meant for private use only. +You need a [Crunchyroll Premium](https://www.crunchyroll.com/welcome#plans) subscription to access premium content. - foundEpisodes, err := crunchy.FindEpisode("https://www.crunchyroll.com/darling-in-the-franxx/episode-1-alone-and-lonesome-759575") - if err != nil { - panic(err) - } - episodeStructure := utils.NewEpisodeStructure(foundEpisodes) - - // this function recursively calls all api endpoints, receives everything and stores it in memory, - // so that after executing this, no more request to the crunchyroll server has to be made. - // note that it could cause much network load while running this method. - // - // you should check the InitAllState before, because InitAll could have been already called or - // another function has the initialization as side effect and re-initializing everything - // will change every pointer in the struct which can cause massive problems afterwards. - if !episodeStructure.InitAllState() { - if err := episodeStructure.InitAll(); err != nil { - panic(err) - } - } - - formats, _ := episodeStructure.Formats() - streams, _ := episodeStructure.Streams() - episodes, _ := episodeStructure.Episodes() - fmt.Printf("Initialized %d formats, %d streams and %d episodes\n", len(formats), len(streams), len(episodes)) -} -``` - -### Tests -You can also run test to see if the api works correctly. -Before doing this, make sure to either set your crunchyroll email and password or sessions as environment variable. -The email variable has to be named `EMAIL` and the password variable `PASSWORD`. If you want to use your session id, the variable must be named `SESSION_ID`. - -You can run the test via `make` -``` -$ make test -``` - -or via `go` directly -``` -$ go test . -``` - -# 🙏 Credits - -### [Kamyroll-Python](https://github.com/hyugogirubato/Kamyroll-Python) -- Extracted all api endpoints and the login process from this - -### [m3u8](https://github.com/oopsguy/m3u8) -- Decrypting mpeg stream files - -### All libraries -- [m3u8](https://github.com/grafov/m3u8) (not the m3u8 library from above) » mpeg stream info library -- [cobra](https://github.com/spf13/cobra) » cli library +**You are entirely responsible for what happens when you use crunchy-cli.** # ⚖ License -This project is licensed under the GNU Lesser General Public License v3.0 (LGPL-3.0) - see the [LICENSE](LICENSE) file -for more details. +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for more details. diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..313cb6d --- /dev/null +++ b/build.rs @@ -0,0 +1,122 @@ +use clap::{Command, CommandFactory}; +use clap_complete::shells; +use std::path::{Path, PathBuf}; + +fn main() -> std::io::Result<()> { + let rustls_tls = cfg!(feature = "rustls-tls"); + let native_tls = cfg!(feature = "native-tls"); + let openssl_tls = cfg!(any(feature = "openssl-tls", feature = "openssl-tls-static")); + + if rustls_tls as u8 + native_tls as u8 + openssl_tls as u8 > 1 { + let active_tls_backend = if openssl_tls { + "openssl" + } else if native_tls { + "native tls" + } else { + "rustls" + }; + + 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) + } + + // 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 + // its nested in sub directories and is difficult to find (at least more difficult than in the + // build root) + let unconventional_out_dir = + std::path::PathBuf::from(std::env::var_os("OUT_DIR").ok_or(std::io::ErrorKind::NotFound)?) + .parent() + .unwrap() + .parent() + .unwrap() + .parent() + .unwrap() + .to_path_buf(); + + let completions_dir = exist_or_create_dir(unconventional_out_dir.join("completions"))?; + let manpage_dir = exist_or_create_dir(unconventional_out_dir.join("manpages"))?; + + generate_completions(completions_dir)?; + generate_manpages(manpage_dir)?; + + Ok(()) +} + +fn exist_or_create_dir(path: PathBuf) -> std::io::Result { + if !path.exists() { + std::fs::create_dir(path.clone())? + } + Ok(path) +} + +fn generate_completions(out_dir: PathBuf) -> std::io::Result<()> { + let mut command: Command = crunchy_cli_core::Cli::command(); + + clap_complete::generate_to( + shells::Bash, + &mut command.clone(), + "crunchy-cli", + out_dir.clone(), + )?; + clap_complete::generate_to( + shells::Elvish, + &mut command.clone(), + "crunchy-cli", + out_dir.clone(), + )?; + println!( + "{}", + clap_complete::generate_to( + shells::Fish, + &mut command.clone(), + "crunchy-cli", + out_dir.clone(), + )? + .to_string_lossy() + ); + clap_complete::generate_to( + shells::PowerShell, + &mut command.clone(), + "crunchy-cli", + out_dir.clone(), + )?; + clap_complete::generate_to(shells::Zsh, &mut command, "crunchy-cli", out_dir)?; + + Ok(()) +} + +fn generate_manpages(out_dir: PathBuf) -> std::io::Result<()> { + fn generate_command_manpage( + mut command: Command, + base_path: &Path, + sub_name: &str, + ) -> std::io::Result<()> { + let (file_name, title) = if sub_name.is_empty() { + command = command.name("crunchy-cli"); + ("crunchy-cli.1".to_string(), "crunchy-cli".to_string()) + } else { + command = command.name(format!("crunchy-cli {}", sub_name)); + ( + format!("crunchy-cli-{}.1", sub_name), + format!("crunchy-cli-{}", sub_name), + ) + }; + + let mut command_buf = vec![]; + let man = clap_mangen::Man::new(command) + .title(title) + .date(chrono::Utc::now().format("%b %d, %Y").to_string()); + man.render(&mut command_buf)?; + + std::fs::write(base_path.join(file_name), command_buf) + } + + generate_command_manpage(crunchy_cli_core::Cli::command(), &out_dir, "")?; + generate_command_manpage(crunchy_cli_core::Archive::command(), &out_dir, "archive")?; + generate_command_manpage(crunchy_cli_core::Download::command(), &out_dir, "download")?; + generate_command_manpage(crunchy_cli_core::Login::command(), &out_dir, "login")?; + generate_command_manpage(crunchy_cli_core::Search::command(), &out_dir, "search")?; + + Ok(()) +} diff --git a/cmd/crunchyroll-go/cmd/download.go b/cmd/crunchyroll-go/cmd/download.go deleted file mode 100644 index bcdb4d8..0000000 --- a/cmd/crunchyroll-go/cmd/download.go +++ /dev/null @@ -1,574 +0,0 @@ -package cmd - -import ( - "bytes" - "encoding/json" - "fmt" - "github.com/ByteDream/crunchyroll-go" - "github.com/ByteDream/crunchyroll-go/utils" - "github.com/grafov/m3u8" - "github.com/spf13/cobra" - "os" - "os/exec" - "os/signal" - "path" - "path/filepath" - "sort" - "strconv" - "strings" - "syscall" - "text/template" -) - -// sigusr1 is actually syscall.SIGUSR1, but because has no signal (or very less) it has to be defined manually -var sigusr1 = syscall.Signal(0xa) - -var ( - audioFlag string - subtitleFlag string - noHardsubFlag bool - - directoryFlag string - outputFlag string - - resolutionFlag string - - alternativeProgressFlag bool -) - -var cleanup [2]string - -var getCmd = &cobra.Command{ - Use: "download", - Short: "Download a video", - Args: cobra.MinimumNArgs(1), - - Run: func(cmd *cobra.Command, args []string) { - loadCrunchy() - download(args) - }, -} - -func init() { - rootCmd.AddCommand(getCmd) - getCmd.Flags().StringVar(&audioFlag, "audio", "", "The locale of the audio. Available locales: "+strings.Join(allLocalesAsStrings(), ", ")) - getCmd.Flags().StringVar(&subtitleFlag, "subtitle", "", "The locale of the subtitle. Available locales: "+strings.Join(allLocalesAsStrings(), ", ")) - getCmd.Flags().BoolVar(&noHardsubFlag, "no-hardsub", false, "Same as `--sub`, but the subtitles are not stored in the video itself, but in a separate file") - - cwd, _ := os.Getwd() - getCmd.Flags().StringVarP(&directoryFlag, "directory", "d", cwd, "The directory to download the file to") - getCmd.Flags().StringVarP(&outputFlag, "output", "o", "{{.Title}}.ts", "Name of the output file\n"+ - "If you use the following things in the name, the will get replaced"+ - "\t{{.Title}} » Title of the video\n"+ - "\t{{.Resolution}} » Resolution of the video\n"+ - "\t{{.FPS}} » Frame Rate of the video\n"+ - "\t{{.Audio}} » Audio locale of the video\n"+ - "\t{{.Subtitle}} » Subtitle locale of the video\n") - - getCmd.Flags().StringVarP(&resolutionFlag, "resolution", "r", "best", "res") - - getCmd.Flags().BoolVar(&alternativeProgressFlag, "alternative-progress", false, "Shows an alternative, not so user-friendly progress instead of the progress bar") -} - -type information struct { - Title string `json:"title"` - OriginalURL string `json:"original_url"` - DownloadURL string `json:"download_url"` - Resolution string `json:"resolution"` - FPS float64 `json:"fps"` - Audio crunchyroll.LOCALE `json:"audio"` - Subtitle crunchyroll.LOCALE `json:"subtitle"` - Hardsub bool `json:"hardsub"` -} - -func download(urls []string) { - if path.Ext(outputFlag) != ".ts" && !hasFFmpeg() { - out.Fatalf("The file ending for the output file (%s) is not `.ts`. "+ - "Install ffmpeg (https://ffmpeg.org/download.html) use other media file endings (e.g. `.mp4`)\n", outputFlag) - } - - var allFormats []*crunchyroll.Format - var allTitles []string - var allURLs []string - - for i, url := range urls { - var failed bool - - out.StartProgressf("Parsing url %d", i+1) - if video, err1 := crunchy.FindVideo(url); err1 == nil { - out.Debugf("Pre-parsed url %d as video\n", i+1) - if formats, titles := parseVideo(video, url); formats != nil { - allFormats = append(allFormats, formats...) - allTitles = append(allTitles, titles...) - for range formats { - allURLs = append(allURLs, url) - } - } else { - failed = true - } - } else if episodes, err2 := crunchy.FindEpisode(url); err2 == nil { - out.Debugf("Parsed url %d as episode\n", i+1) - out.Debugf("Found %d episode types\n", len(episodes)) - if format, title := parseEpisodes(episodes, url); format != nil { - allFormats = append(allFormats, format) - allTitles = append(allTitles, title) - allURLs = append(allURLs, url) - } else { - failed = true - } - } else { - out.EndProgressf(false, "Could not parse url %d, skipping\n", i+1) - out.Debugf("Parse error 1: %s\n", err1) - out.Debugf("Parse error 2: %s\n", err2) - continue - } - - if !failed { - out.EndProgressf(true, "Parsed url %d successful\n", i+1) - } else { - out.EndProgressf(false, "Failed to parse url %d (the url is valid but some kind of error which is surely shown caused the failure)", i+1) - } - } - out.Debugf("%d of %d urls could be parsed\n", len(allURLs), len(urls)) - - out.Empty() - if len(allFormats) == 0 { - out.Fatalf("Nothing to download, aborting\n") - } - out.Infof("Downloads:") - for i, format := range allFormats { - video := format.Video - out.Infof("\t%d. %s » %spx, %.2f FPS, %s audio\n", i+1, allTitles[i], video.Resolution, video.FrameRate, utils.LocaleLanguage(format.AudioLocale)) - } - var tmpl *template.Template - var err error - tmpl, err = template.New("").Parse(outputFlag) - if err == nil { - var buff bytes.Buffer - if err := tmpl.Execute(&buff, allFormats[0].Video); err == nil { - if buff.String() == outputFlag { - tmpl = nil - } - } - } - - if fileInfo, stat := os.Stat(directoryFlag); err == nil { - if !fileInfo.IsDir() { - out.Fatalf("%s (given from the `-d`/`--directory` flag) is not a directory\n", directoryFlag) - } - } else if os.IsNotExist(stat) { - if err := os.MkdirAll(directoryFlag, 0777); err != nil { - out.Fatalf("Failed to create directory which was given from the `-d`/`--directory` flag: %s\n", err) - } - } else { - out.Fatalf("Failed to get information for via `-d`/`--directory` flag the given file / directory: %s", err) - } - - var success int - for i, format := range allFormats { - var subtitle crunchyroll.LOCALE - if subtitleFlag != "" { - subtitle = localeToLOCALE(subtitleFlag) - } - info := information{ - Title: allTitles[i], - OriginalURL: allURLs[i], - DownloadURL: format.Video.URI, - Resolution: format.Video.Resolution, - FPS: format.Video.FrameRate, - Audio: format.AudioLocale, - Subtitle: subtitle, - } - - if verboseFlag { - fmtOptionsBytes, err := json.Marshal(info) - if err != nil { - fmtOptionsBytes = make([]byte, 0) - } - out.Debugf("Information (json): %s", string(fmtOptionsBytes)) - } - - var baseFilename string - if tmpl != nil { - var buff bytes.Buffer - if err := tmpl.Execute(&buff, info); err == nil { - baseFilename = buff.String() - } else { - out.Fatalf("Could not convert filename (%s), aborting\n", err) - } - } else { - baseFilename = outputFlag - } - - out.Empty() - if downloadFormat(format, directoryFlag, baseFilename, info) { - success++ - } - } - - out.Empty() - out.Infof("Downloaded %d out of %d videos successful\n", success, len(allFormats)) -} - -func parseVideo(video crunchyroll.Video, url string) (parsedFormats []*crunchyroll.Format, titles []string) { - var rootTitle string - var orderedFormats [][]*crunchyroll.Format - var videoStructure utils.VideoStructure - - switch video.(type) { - case *crunchyroll.Series: - out.Debugf("Parsed url as series\n") - series := video.(*crunchyroll.Series) - seasons, err := series.Seasons() - if err != nil { - out.Errf("Could not get any season of %s (%s): %s. Aborting\n", series.Title, url, err.Error()) - return - } - out.Debugf("Found %d seasons\n", len(seasons)) - seasonsStructure := utils.NewSeasonStructure(seasons) - if err := seasonsStructure.InitAll(); err != nil { - out.Errf("Failed to initialize %s (%s): %s. Aborting\n", series.Title, url, err.Error()) - return - } - out.Debugf("Initialized %s\n", series.Title) - - rootTitle = series.Title - orderedFormats, _ = seasonsStructure.OrderFormatsByEpisodeNumber() - videoStructure = seasonsStructure.EpisodeStructure - case *crunchyroll.Movie: - out.Debugf("Parsed url as movie\n") - movie := video.(*crunchyroll.Movie) - movieListings, err := movie.MovieListing() - if err != nil { - out.Errf("Failed to get movie of %s (%s)\n", movie.Title, url) - return - } - out.Debugf("Parsed %d movie listenings\n", len(movieListings)) - movieListingStructure := utils.NewMovieListingStructure(movieListings) - if err := movieListingStructure.InitAll(); err != nil { - out.Errf("Failed to initialize %s (%s): %s. Aborting\n", movie.Title, url, err.Error()) - return - } - - rootTitle = movie.Title - unorderedFormats, _ := movieListingStructure.Formats() - orderedFormats = append(orderedFormats, unorderedFormats) - videoStructure = movieListingStructure - } - - // out.Debugf("Found %d formats\n", len(unorderedFormats)) - out.Debugf("Found %d different episodes\n", len(orderedFormats)) - - for j, formats := range orderedFormats { - if format := findFormat(formats); format != nil { - var title string - switch videoStructure.(type) { - case *utils.EpisodeStructure: - episode, _ := videoStructure.(*utils.EpisodeStructure).GetEpisodeByFormat(format) - title = episode.Title - case *utils.MovieListingStructure: - movieListing, _ := videoStructure.(*utils.MovieListingStructure).GetMovieListingByFormat(format) - title = movieListing.Title - } - - parsedFormats = append(parsedFormats, format) - titles = append(titles, title) - out.Debugf("Successful parsed format %d for %s\n", j+1, rootTitle) - } - } - - return -} - -func parseEpisodes(episodes []*crunchyroll.Episode, url string) (*crunchyroll.Format, string) { - episodeStructure := utils.NewEpisodeStructure(episodes) - if err := episodeStructure.InitAll(); err != nil { - out.EndProgressf(false, "Failed to initialize %s (%s): %s, skipping\n", episodes[0].Title, url, err) - return nil, "" - } - - formats, _ := episodeStructure.Formats() - out.Debugf("Found %d formats\n", len(formats)) - if format := findFormat(formats); format != nil { - episode, _ := episodeStructure.GetEpisodeByFormat(format) - return format, episode.Title - } - return nil, "" -} - -func findFormat(formats []*crunchyroll.Format) (format *crunchyroll.Format) { - formatStructure := utils.NewFormatStructure(formats) - var audioLocale, subtitleLocale crunchyroll.LOCALE - - if audioFlag != "" { - audioLocale = localeToLOCALE(audioFlag) - } else { - audioLocale = localeToLOCALE(systemLocale()) - } - if subtitleFlag != "" { - subtitleLocale = localeToLOCALE(subtitleFlag) - } - - if audioFlag == "" { - var dubOk bool - availableDub, _, _, _ := formatStructure.AvailableLocales(true) - for _, dub := range availableDub { - if dub == audioLocale { - dubOk = true - break - } - } - if !dubOk { - if audioFlag != systemLocale() { - out.EndProgressf(false, "No stream with audio locale `%s` is available, skipping\n", audioLocale) - return nil - } - out.Errf("No stream with default audio locale `%s` is available, using hardsubbed %s with subtitle locale %s\n", audioLocale, crunchyroll.JP, systemLocale()) - audioLocale = crunchyroll.JP - if subtitleFlag == "" { - subtitleLocale = localeToLOCALE(systemLocale()) - } - } - } - - var dubOk, subOk bool - availableDub, availableSub, _, _ := formatStructure.AvailableLocales(true) - for _, dub := range availableDub { - if dub == audioLocale { - dubOk = true - break - } - } - if !dubOk { - if audioFlag == "" { - audioLocale = crunchyroll.JP - if subtitleFlag == "" { - subtitleLocale = localeToLOCALE(systemLocale()) - out.Errf("No stream with default audio locale `%s` is available, using hardsubbed %s with subtitle locale %s\n", audioLocale, crunchyroll.JP, subtitleLocale) - } - } - for _, dub := range availableDub { - if dub == audioLocale { - dubOk = true - break - } - } - } - if subtitleLocale != "" { - for _, sub := range availableSub { - if sub == subtitleLocale { - subOk = true - break - } - } - } else { - subOk = true - } - - if !dubOk { - out.Errf("Could not find any video with `%s` audio locale\n", audioLocale) - } - if !subOk { - out.Errf("Could not find any video with `%s` subtitle locale\n", subtitleLocale) - } - if !dubOk || !subOk { - return nil - } - - formats, err := formatStructure.FilterFormatsByLocales(audioLocale, subtitleLocale, !noHardsubFlag) - if err != nil { - out.Errln("Failed to get matching format. Try to change the `--audio` or `--subtitle` flag") - return - } - - if resolutionFlag == "best" || resolutionFlag == "" { - sort.Sort(sort.Reverse(utils.FormatsByResolution(formats))) - format = formats[0] - } else if resolutionFlag == "worst" { - sort.Sort(utils.FormatsByResolution(formats)) - format = formats[0] - } else { - for _, f := range formats { - if f.Video.Resolution == resolutionFlag { - format = f - break - } - } - } - subtitleFlag = string(subtitleLocale) - return -} - -func downloadFormat(format *crunchyroll.Format, dir, fname string, info information) bool { - filename := freeFileName(filepath.Join(dir, fname)) - ext := path.Ext(filename) - out.Debugf("Download filename: %s\n", filename) - if filename != filepath.Join(dir, fname) { - out.Errf("The file %s already exist, renaming the download file to %s\n", filepath.Join(dir, fname), filename) - } - if ext != ".ts" { - if !hasFFmpeg() { - out.Fatalf("The file ending for the output file (%s) is not `.ts`. "+ - "Install ffmpeg (https://ffmpeg.org/download.html) use other media file endings (e.g. `.mp4`)\n", filename) - } - out.Debugf("File will be converted via ffmpeg") - } - var subtitleFilename string - if noHardsubFlag { - subtitle, ok := utils.SubtitleByLocale(format, info.Subtitle) - if !ok { - out.Errf("Failed to get %s subtitles\n", info.Subtitle) - return false - } - subtitleFilename = freeFileName(filepath.Join(dir, fmt.Sprintf("%s.%s", strings.TrimRight(path.Base(filename), ext), subtitle.Format))) - out.Debugf("Subtitles will be saved as `%s`\n", subtitleFilename) - } - - out.Infof("Downloading `%s` (%s) as `%s`\n", info.Title, info.OriginalURL, filename) - out.Infof("Audio: %s\n", info.Audio) - out.Infof("Subtitle: %s\n", info.Subtitle) - out.Infof("Hardsub: %v\n", format.Hardsub != "") - out.Infof("Resolution: %s\n", info.Resolution) - out.Infof("FPS: %.2f\n", info.FPS) - - var err error - if ext == ".ts" { - file, err := os.Create(filename) - defer file.Close() - if err != nil { - out.Errf("Could not create file `%s` to download episode `%s` (%s): %s, skipping\n", filename, info.Title, info.OriginalURL, err) - return false - } - cleanup[0] = filename - - // removes all files in case of an unexpected exit - sigs := make(chan os.Signal) - signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, sigusr1) - go func() { - sig := <-sigs - os.RemoveAll(cleanup[1]) - switch sig { - case os.Interrupt, syscall.SIGTERM: - os.Remove(cleanup[0]) - os.Exit(1) - } - }() - - err = format.Download(file, downloadProgress) - // newline to avoid weird output - fmt.Println() - - // make the goroutine stop - sigs <- sigusr1 - } else { - tempDir, err := os.MkdirTemp("", "crunchy_") - if err != nil { - out.Errln("Failed to create temp download dir. Skipping") - return false - } - sigs := make(chan os.Signal, 1) - signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, sigusr1) - go func() { - sig := <-sigs - os.RemoveAll(tempDir) - switch sig { - case os.Interrupt, syscall.SIGTERM: - os.Exit(1) - } - }() - - var segmentCount int - err = format.DownloadSegments(tempDir, 4, func(segment *m3u8.MediaSegment, current, total int, file *os.File, err error) error { - segmentCount++ - return downloadProgress(segment, current, total, file, err) - }) - // newline to avoid weird output - fmt.Println() - - f, _ := os.CreateTemp("", "*.txt") - for i := 0; i < segmentCount; i++ { - fmt.Fprintf(f, "file '%s.ts'\n", filepath.Join(tempDir, strconv.Itoa(i))) - } - defer os.Remove(f.Name()) - f.Close() - - cmd := exec.Command("ffmpeg", - "-f", "concat", - "-safe", "0", - "-i", f.Name(), - "-c", "copy", - filename) - err = cmd.Run() - - sigs <- sigusr1 - } - if err != nil { - out.Errln("Failed to download video, skipping") - } else { - if info.Subtitle == "" { - out.Infof("Downloaded `%s` as `%s` with %s audio locale\n", info.Title, filename, strings.ToLower(utils.LocaleLanguage(info.Audio))) - } else { - out.Infof("Downloaded `%s` as `%s` with %s audio locale and %s subtitle locale\n", info.Title, filename, strings.ToLower(utils.LocaleLanguage(info.Audio)), strings.ToLower(utils.LocaleLanguage(info.Subtitle))) - if subtitleFilename != "" { - file, err := os.Create(subtitleFilename) - if err != nil { - out.Errf("Failed to download subtitles: %s\n", err) - return false - } else { - subtitle, ok := utils.SubtitleByLocale(format, info.Subtitle) - if !ok { - out.Errf("Failed to get %s subtitles\n", info.Subtitle) - return false - } - if err := subtitle.Download(file); err != nil { - out.Errf("Failed to download subtitles: %s\n", err) - return false - } - out.Infof("Downloaded `%s` subtitles to `%s`\n", info.Subtitle, subtitleFilename) - } - } - } - } - - return true -} - -func downloadProgress(segment *m3u8.MediaSegment, current, total int, file *os.File, err error) error { - if cleanup[1] == "" && file != nil { - cleanup[1] = path.Dir(file.Name()) - } - - if !quietFlag { - percentage := float32(current) / float32(total) * 100 - if alternativeProgressFlag { - out.Infof("Downloading %d/%d (%.2f%%) » %s", current, total, percentage, segment.URI) - } else { - progressWidth := float32(terminalWidth() - (14 + len(out.InfoLog.Prefix())) - (len(fmt.Sprint(total)))*2) - - repeatCount := int(percentage / (float32(100) / progressWidth)) - // it can be lower than zero when the terminal is very tiny - if repeatCount < 0 { - repeatCount = 0 - } - - // alternative: - // progressPercentage := strings.Repeat("█", repeatCount) - progressPercentage := (strings.Repeat("=", repeatCount) + ">")[1:] - - fmt.Printf("\r%s[%-"+fmt.Sprint(progressWidth)+"s]%4d%% %8d/%d", out.InfoLog.Prefix(), progressPercentage, int(percentage), current, total) - } - } - return nil -} - -func freeFileName(filename string) string { - ext := path.Ext(filename) - base := strings.TrimRight(filename, ext) - for j := 0; ; j++ { - if _, stat := os.Stat(filename); stat != nil && !os.IsExist(stat) { - break - } - filename = fmt.Sprintf("%s (%d)%s", base, j, ext) - } - return filename -} diff --git a/cmd/crunchyroll-go/cmd/login.go b/cmd/crunchyroll-go/cmd/login.go deleted file mode 100644 index fb4b85c..0000000 --- a/cmd/crunchyroll-go/cmd/login.go +++ /dev/null @@ -1,50 +0,0 @@ -package cmd - -import ( - "github.com/ByteDream/crunchyroll-go" - "github.com/spf13/cobra" - "io/ioutil" -) - -var ( - sessionIDFlag bool -) - -var loginCmd = &cobra.Command{ - Use: "login", - Short: "Login to crunchyroll", - Args: cobra.RangeArgs(1, 2), - - RunE: func(cmd *cobra.Command, args []string) error { - if sessionIDFlag { - return loginSessionID(args[0], false) - } else { - return loginCredentials(args[0], args[1]) - } - }, -} - -func init() { - rootCmd.AddCommand(loginCmd) - loginCmd.Flags().BoolVar(&sessionIDFlag, "session-id", false, "session id") -} - -func loginCredentials(email, password string) error { - out.Debugln("Logging in via credentials") - session, err := crunchyroll.LoginWithCredentials(email, password, locale, client) - if err != nil { - return err - } - return loginSessionID(session.SessionID, true) -} - -func loginSessionID(sessionID string, alreadyChecked bool) error { - if !alreadyChecked { - out.Debugln("Logging in via session id") - if _, err := crunchyroll.LoginWithSessionID(sessionID, locale, client); err != nil { - return err - } - } - out.Infoln("Due to security reasons, you have to login again on the next reboot") - return ioutil.WriteFile(sessionIDPath, []byte(sessionID), 0777) -} diff --git a/cmd/crunchyroll-go/cmd/root.go b/cmd/crunchyroll-go/cmd/root.go deleted file mode 100644 index 94c72af..0000000 --- a/cmd/crunchyroll-go/cmd/root.go +++ /dev/null @@ -1,68 +0,0 @@ -package cmd - -import ( - "github.com/ByteDream/crunchyroll-go" - "github.com/spf13/cobra" - "net/http" - "os" - "runtime" - "runtime/debug" -) - -var ( - client *http.Client - locale crunchyroll.LOCALE - crunchy *crunchyroll.Crunchyroll - out = newLogger(false, true, true, colorFlag) - - quietFlag bool - verboseFlag bool - proxyFlag string - localeFlag string - colorFlag bool -) - -var rootCmd = &cobra.Command{ - Use: "crunchyroll", - Short: "Download crunchyroll videos with ease", - PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) { - if verboseFlag { - out = newLogger(true, true, true, colorFlag) - } else if quietFlag { - out = newLogger(false, false, false, false) - } - - out.DebugLog.Printf("Executing `%s` command with %d arg(s)\n", cmd.Name(), len(args)) - - locale = localeToLOCALE(localeFlag) - - client, err = createOrDefaultClient(proxyFlag) - return - }, -} - -func init() { - rootCmd.PersistentFlags().BoolVarP(&quietFlag, "quiet", "q", false, "Disable all output") - rootCmd.PersistentFlags().BoolVarP(&verboseFlag, "verbose", "v", false, "Adds debug messages to the normal output") - rootCmd.PersistentFlags().StringVarP(&proxyFlag, "proxy", "p", "", "Proxy to use") - rootCmd.PersistentFlags().StringVarP(&localeFlag, "locale", "l", systemLocale(), "The locale to use") - rootCmd.PersistentFlags().BoolVar(&colorFlag, "color", false, "Colored output. Only available on not windows systems") -} - -func Execute() { - rootCmd.CompletionOptions.DisableDefaultCmd = true - defer func() { - if r := recover(); r != nil { - out.Errln(r) - // change color to red - if colorFlag && runtime.GOOS != "windows" { - out.ErrLog.SetOutput(&loggerWriter{original: out.ErrLog.Writer(), color: "\033[31m"}) - } - out.Debugln(string(debug.Stack())) - os.Exit(2) - } - }() - if err := rootCmd.Execute(); err != nil { - out.Fatalln(err) - } -} diff --git a/cmd/crunchyroll-go/cmd/utils.go b/cmd/crunchyroll-go/cmd/utils.go deleted file mode 100644 index 2afe2f8..0000000 --- a/cmd/crunchyroll-go/cmd/utils.go +++ /dev/null @@ -1,310 +0,0 @@ -package cmd - -import ( - "fmt" - "github.com/ByteDream/crunchyroll-go" - "github.com/ByteDream/crunchyroll-go/utils" - "io" - "io/ioutil" - "log" - "net/http" - "net/url" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" - "time" -) - -var sessionIDPath = filepath.Join(os.TempDir(), ".crunchy") - -type progress struct { - status bool - message string -} - -type logger struct { - DebugLog *log.Logger - InfoLog *log.Logger - ErrLog *log.Logger - - devView bool - - progressWG sync.Mutex - progress chan progress -} - -func newLogger(debug, info, err bool, color bool) *logger { - debugLog, infoLog, errLog := log.New(io.Discard, "=> ", 0), log.New(io.Discard, "=> ", 0), log.New(io.Discard, "=> ", 0) - - debugColor, infoColor, errColor := "", "", "" - if color && runtime.GOOS != "windows" { - debugColor, infoColor, errColor = "\033[95m", "\033[96m", "\033[31m" - } - - if debug { - debugLog.SetOutput(&loggerWriter{original: os.Stdout, color: debugColor}) - } - if info { - infoLog.SetOutput(&loggerWriter{original: os.Stdout, color: infoColor}) - } - if err { - errLog.SetOutput(&loggerWriter{original: os.Stdout, color: errColor}) - } - - if debug { - debugLog = log.New(debugLog.Writer(), "[debug] ", 0) - infoLog = log.New(infoLog.Writer(), "[info] ", 0) - errLog = log.New(errLog.Writer(), "[err] ", 0) - } - - return &logger{ - DebugLog: debugLog, - InfoLog: infoLog, - ErrLog: errLog, - - devView: debug, - } -} - -func (l *logger) Empty() { - if !l.devView && l.InfoLog.Writer() != io.Discard { - fmt.Println() - } -} - -func (l *logger) StartProgress(message string) { - if l.devView { - l.InfoLog.Println(message) - return - } - l.progress = make(chan progress) - - go func() { - states := []string{"-", "\\", "|", "/"} - for i := 0; ; i++ { - l.progressWG.Lock() - select { - case p := <-l.progress: - // clearing the last line - fmt.Printf("\r%s\r", strings.Repeat(" ", len(l.InfoLog.Prefix())+len(message)+2)) - if p.status { - successTag := "✔" - if runtime.GOOS == "windows" { - successTag = "~" - } - l.InfoLog.Printf("%s %s", successTag, p.message) - } else { - errorTag := "✘" - if runtime.GOOS == "windows" { - errorTag = "!" - } - l.ErrLog.Printf("%s %s", errorTag, p.message) - } - l.progress = nil - l.progressWG.Unlock() - return - default: - if i%10 == 0 { - fmt.Printf("\r%s%s %s", l.InfoLog.Prefix(), states[i/10%4], message) - } - time.Sleep(35 * time.Millisecond) - l.progressWG.Unlock() - } - } - }() -} - -func (l *logger) StartProgressf(message string, a ...interface{}) { - l.StartProgress(fmt.Sprintf(message, a...)) -} - -func (l *logger) EndProgress(successful bool, message string) { - if l.devView { - if successful { - l.InfoLog.Print(message) - } else { - l.ErrLog.Print(message) - } - return - } - - l.progress <- progress{ - status: successful, - message: message, - } -} - -func (l *logger) EndProgressf(successful bool, message string, a ...interface{}) { - l.EndProgress(successful, fmt.Sprintf(message, a...)) -} - -func (l *logger) Debugln(v ...interface{}) { - l.print(0, v...) -} - -func (l *logger) Debugf(message string, a ...interface{}) { - l.print(0, fmt.Sprintf(message, a...)) -} - -func (l *logger) Infoln(v ...interface{}) { - l.print(1, v...) -} - -func (l *logger) Infof(message string, a ...interface{}) { - l.print(1, fmt.Sprintf(message, a...)) -} - -func (l *logger) Errln(v ...interface{}) { - l.print(2, v...) -} - -func (l *logger) Errf(message string, a ...interface{}) { - l.print(2, fmt.Sprintf(message, a...)) -} - -func (l *logger) Fatalln(v ...interface{}) { - l.print(2, v...) - os.Exit(1) -} - -func (l *logger) Fatalf(message string, a ...interface{}) { - l.print(2, fmt.Sprintf(message, a...)) - os.Exit(1) -} - -func (l *logger) print(level int, v ...interface{}) { - if l.progress != nil { - l.progressWG.Lock() - defer l.progressWG.Unlock() - fmt.Print("\r") - } - - switch level { - case 0: - l.DebugLog.Print(v...) - case 1: - l.InfoLog.Print(v...) - case 2: - l.ErrLog.Print(v...) - } -} - -type loggerWriter struct { - io.Writer - - original io.Writer - color string -} - -func (lw *loggerWriter) Write(p []byte) (n int, err error) { - if lw.color != "" { - p = append([]byte(lw.color), p...) - p = append(p, []byte("\033[0m")...) - } - return lw.original.Write(p) -} - -// systemLocale receives the system locale -// https://stackoverflow.com/questions/51829386/golang-get-system-language/51831590#51831590 -func systemLocale() string { - if runtime.GOOS != "windows" { - if lang, ok := os.LookupEnv("LANG"); ok { - return strings.ReplaceAll(strings.Split(lang, ".")[0], "_", "-") - } - } else { - cmd := exec.Command("powershell", "Get-Culture | select -exp Name") - if output, err := cmd.Output(); err != nil { - return strings.Trim(string(output), "\r\n") - } - } - return "en-US" -} - -func localeToLOCALE(locale string) crunchyroll.LOCALE { - if l := crunchyroll.LOCALE(locale); utils.ValidateLocale(l) { - return l - } else { - out.Errf("%s is not a supported locale, using %s as fallback\n", locale, crunchyroll.US) - return crunchyroll.US - } -} - -func allLocalesAsStrings() (locales []string) { - for _, locale := range utils.AllLocales { - locales = append(locales, string(locale)) - } - return -} - -func createOrDefaultClient(proxy string) (*http.Client, error) { - if proxy == "" { - return http.DefaultClient, nil - } else { - out.Infof("Using custom proxy %s\n", proxy) - proxyURL, err := url.Parse(proxy) - if err != nil { - return nil, err - } - client := &http.Client{ - Transport: &http.Transport{ - DisableCompression: true, - Proxy: http.ProxyURL(proxyURL), - }, - Timeout: 30 * time.Second, - } - return client, nil - } -} - -func loadSessionID() (string, error) { - if _, stat := os.Stat(sessionIDPath); os.IsNotExist(stat) { - out.Fatalf("To use this command, login first. Type `%s login -h` to get help\n", os.Args[0]) - } - body, err := ioutil.ReadFile(sessionIDPath) - if err != nil { - return "", err - } - return strings.ReplaceAll(string(body), "\n", ""), nil -} - -func loadCrunchy() { - out.StartProgress("Logging in") - sessionID, err := loadSessionID() - if err == nil { - if crunchy, err = crunchyroll.LoginWithSessionID(sessionID, locale, client); err != nil { - out.EndProgress(false, err.Error()) - os.Exit(1) - } - } else { - out.EndProgress(false, err.Error()) - os.Exit(1) - } - out.EndProgress(true, "Logged in") - out.Debugf("Logged in with session id %s\n", sessionID) -} - -func hasFFmpeg() bool { - cmd := exec.Command("ffmpeg", "-h") - return cmd.Run() == nil -} - -func terminalWidth() int { - if runtime.GOOS != "windows" { - cmd := exec.Command("stty", "size") - cmd.Stdin = os.Stdin - out, err := cmd.Output() - if err != nil { - return 60 - } - width, err := strconv.Atoi(strings.Split(strings.ReplaceAll(string(out), "\n", ""), " ")[1]) - if err != nil { - return 60 - } - return width - } - return 60 -} diff --git a/cmd/crunchyroll-go/main.go b/cmd/crunchyroll-go/main.go deleted file mode 100644 index 0b13e39..0000000 --- a/cmd/crunchyroll-go/main.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -// the cli will be redesigned soon - -import ( - "github.com/ByteDream/crunchyroll-go/cmd/crunchyroll-go/cmd" -) - -func main() { - cmd.Execute() -} diff --git a/crunchy-cli-core/Cargo.toml b/crunchy-cli-core/Cargo.toml new file mode 100644 index 0000000..399053f --- /dev/null +++ b/crunchy-cli-core/Cargo.toml @@ -0,0 +1,51 @@ +[package] +name = "crunchy-cli-core" +authors = ["Crunchy Labs Maintainers"] +version = "3.6.7" +edition = "2021" +license = "MIT" + +[features] +rustls-tls = ["reqwest/rustls-tls"] +native-tls = ["reqwest/native-tls", "reqwest/native-tls-alpn"] +openssl-tls = ["reqwest/native-tls", "reqwest/native-tls-alpn", "dep:rustls-native-certs"] +openssl-tls-static = ["reqwest/native-tls", "reqwest/native-tls-alpn", "reqwest/native-tls-vendored", "dep:rustls-native-certs"] + +[dependencies] +anyhow = "1.0" +async-speed-limit = "0.4" +clap = { version = "4.5", features = ["derive", "string"] } +chrono = "0.4" +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 = "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.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.3" +sys-locale = "0.3" +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.7", optional = true } + +[target.'cfg(not(target_os = "windows"))'.dependencies] +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 new file mode 100644 index 0000000..b36ec8e --- /dev/null +++ b/crunchy-cli-core/build.rs @@ -0,0 +1,34 @@ +fn main() -> std::io::Result<()> { + println!( + "cargo:rustc-env=GIT_HASH={}", + std::env::var("CRUNCHY_CLI_GIT_HASH") + .or::(Ok(get_short_commit_hash()?.unwrap_or_default()))? + ); + println!( + "cargo:rustc-env=BUILD_DATE={}", + chrono::Utc::now().format("%F") + ); + + Ok(()) +} + +fn get_short_commit_hash() -> std::io::Result> { + let git = std::process::Command::new("git") + .arg("rev-parse") + .arg("--short") + .arg("HEAD") + .output(); + + match git { + Ok(cmd) => Ok(Some( + String::from_utf8_lossy(cmd.stdout.as_slice()).to_string(), + )), + Err(e) => { + if e.kind() != std::io::ErrorKind::NotFound { + Err(e) + } else { + Ok(None) + } + } + } +} diff --git a/crunchy-cli-core/src/archive/command.rs b/crunchy-cli-core/src/archive/command.rs new file mode 100644 index 0000000..0d1b3a4 --- /dev/null +++ b/crunchy-cli-core/src/archive/command.rs @@ -0,0 +1,692 @@ +use crate::utils::context::Context; +use crate::utils::download::{ + DownloadBuilder, DownloadFormat, DownloadFormatMetadata, MergeBehavior, +}; +use crate::utils::ffmpeg::FFmpegPreset; +use crate::utils::filter::{Filter, FilterMediaScope}; +use crate::utils::format::{Format, SingleFormat}; +use crate::utils::locale::{all_locale_in_locales, resolve_locales, LanguageTagging}; +use crate::utils::log::progress; +use crate::utils::os::{free_file, has_ffmpeg, is_special_file}; +use crate::utils::parse::parse_url; +use crate::utils::video::stream_data_from_stream; +use crate::Execute; +use anyhow::bail; +use anyhow::Result; +use chrono::Duration; +use crunchyroll_rs::media::{Resolution, Subtitle}; +use crunchyroll_rs::Locale; +use log::{debug, warn}; +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")] +#[command(arg_required_else_help(true))] +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 {}\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: {}\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. \ + If you use one of the following pattern they will get replaced:\n \ + {title} → Title of the video\n \ + {series_name} → Name of the series\n \ + {season_name} → Name of the season\n \ + {audio} → Audio language of the video\n \ + {width} → Width of the video\n \ + {height} → Height of the video\n \ + {season_number} → Number of the season\n \ + {episode_number} → Number of the episode\n \ + {relative_episode_number} → Number of the episode relative to its season\n \ + {sequence_number} → Like '{episode_number}' but without possible non-number characters\n \ + {relative_sequence_number} → Like '{relative_episode_number}' but with support for episode 0's and .5's\n \ + {release_year} → Release year of the video\n \ + {release_month} → Release month of the video\n \ + {release_day} → Release day of the video\n \ + {series_id} → ID of the series\n \ + {season_id} → ID of the season\n \ + {episode_id} → ID of the episode")] + #[arg(short, long, default_value = "{title}.mkv")] + pub(crate) output: String, + #[arg(help = "Name of the output file if the episode is a special")] + #[arg(long_help = "Name of the output file if the episode is a special. \ + If not set, the '-o'/'--output' flag will be used as name template")] + #[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). \ + Specifying the exact pixels is not recommended, use one of the other options instead. \ + Crunchyroll let you choose the quality with pixel abbreviation on their clients, so you might be already familiar with the available options. \ + The available common-use words are 'best' (choose the best resolution available) and 'worst' (worst resolution available)")] + #[arg(short, long, default_value = "best")] + #[arg(value_parser = crate::utils::clap::clap_parse_resolution)] + pub(crate) resolution: Resolution, + + #[arg( + 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), '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 ")))] + #[arg(long_help = format!("Presets for converting the video to a specific coding format. \ + If you need more specific ffmpeg customizations you can pass ffmpeg output arguments instead of a preset as value. \ + Available presets: \n {}", FFmpegPreset::available_matches_human_readable().join("\n ")))] + #[arg(long)] + #[arg(value_parser = FFmpegPreset::parse)] + pub(crate) ffmpeg_preset: Option, + #[arg( + help = "The number of threads used by ffmpeg to generate the output file. Does not work with every codec/preset" + )] + #[arg( + long_help = "The number of threads used by ffmpeg to generate the output file. \ + Does not work with every codec/preset and is skipped entirely when specifying custom ffmpeg output arguments instead of a preset for `--ffmpeg-preset`. \ + By default, ffmpeg chooses the thread count which works best for the output codec" + )] + #[arg(long)] + pub(crate) ffmpeg_threads: Option, + + #[arg( + help = "Set which subtitle language should be set as default / auto shown when starting a video" + )] + #[arg(long)] + pub(crate) default_subtitle: Option, + #[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 = "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, + + #[arg(help = "Skip any interactive input")] + #[arg(short, long, default_value_t = false)] + pub(crate) yes: bool, + + #[arg(help = "The number of threads used to download")] + #[arg(short, long, default_value_t = num_cpus::get())] + pub(crate) threads: usize, + + #[arg(help = "Crunchyroll series url(s)")] + #[arg(required = true)] + pub(crate) urls: Vec, +} + +impl Execute for Archive { + fn pre_check(&mut self) -> Result<()> { + if !has_ffmpeg() { + bail!("FFmpeg is needed to run this command") + } else if PathBuf::from(&self.output) + .extension() + .unwrap_or_default() + .to_string_lossy() + != "mkv" + && !is_special_file(&self.output) + && self.output != "-" + { + bail!("File extension is not '.mkv'. Currently only matroska / '.mkv' files are supported") + } else if let Some(special_output) = &self.output_specials { + if PathBuf::from(special_output) + .extension() + .unwrap_or_default() + .to_string_lossy() + != "mkv" + && !is_special_file(special_output) + && special_output != "-" + { + bail!("File extension for special episodes is not '.mkv'. Currently only matroska / '.mkv' files are supported") + } + } + + if self.include_chapters + && !matches!(self.merge, MergeBehavior::Sync) + && !matches!(self.merge, MergeBehavior::Audio) + { + 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() { + let progress_handler = progress!("Parsing url {}", i + 1); + match parse_url(&ctx.crunchy, url.clone(), true).await { + Ok((media_collection, url_filter)) => { + progress_handler.stop(format!("Parsed url {}", i + 1)); + parsed_urls.push((media_collection, url_filter)) + } + Err(e) => bail!("url {} could not be parsed: {}", url, e), + }; + } + + for (i, (media_collection, url_filter)) in parsed_urls.into_iter().enumerate() { + let progress_handler = progress!("Fetching series details"); + 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)); + continue; + } + progress_handler.stop(format!("Loaded series information for url {}", i + 1)); + + single_format_collection.full_visual_output(); + + 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?; + + let mut downloader = download_builder.clone().build(); + for download_format in download_formats { + downloader.add_format(download_format) + } + + let formatted_path = if format.is_special() { + format.format_path( + 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(), + self.universal_output, + self.language_tagging.as_ref(), + ) + }; + let (mut path, changed) = free_file(formatted_path.clone()); + + if changed && self.skip_existing { + 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, _)| { + self.audio + .iter() + .position(|l| l == a) + .cmp(&self.audio.iter().position(|l| l == b)) + }); + for (_, subtitles) in format.locales.iter_mut() { + subtitles.sort_by(|a, b| { + self.subtitle + .iter() + .position(|l| l == a) + .cmp(&self.subtitle.iter().position(|l| l == b)) + }) + } + + format.visual_output(&path); + + downloader.download(&path).await? + } + } + + Ok(()) + } +} + +#[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, +) -> Result<(Vec, Format)> { + let mut format_pairs = vec![]; + let mut single_format_to_format_pairs = vec![]; + + for single_format in single_formats { + let stream = single_format.stream().await?; + let Some((video, audio, _)) = + stream_data_from_stream(&stream, &archive.resolution, None).await? + else { + if single_format.is_episode() { + bail!( + "Resolution ({}) is not available for episode {} ({}) of {} season {}", + archive.resolution, + single_format.episode_number, + single_format.title, + single_format.series_name, + single_format.season_number, + ) + } else { + bail!( + "Resolution ({}) is not available for {} ({})", + archive.resolution, + single_format.source_type(), + single_format.title + ) + } + }; + + let subtitles: Vec<(Subtitle, bool)> = archive + .subtitle + .iter() + .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)); + + stream.invalidate().await? + } + + let mut download_formats = vec![]; + + match archive.merge { + MergeBehavior::Video => { + for (single_format, video, audio, subtitles) in format_pairs { + download_formats.push(DownloadFormat { + video: (video, single_format.audio.clone()), + audios: vec![(audio, single_format.audio.clone())], + subtitles, + metadata: DownloadFormatMetadata { skip_events: None }, + }) + } + } + MergeBehavior::Audio => download_formats.push(DownloadFormat { + video: ( + format_pairs.first().unwrap().1.clone(), + format_pairs.first().unwrap().0.audio.clone(), + ), + audios: format_pairs + .iter() + .map(|(single_format, _, audio, _)| (audio.clone(), single_format.audio.clone())) + .collect(), + // mix all subtitles together and then reduce them via a map so that only one subtitle + // per language exists + subtitles: format_pairs + .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 | MergeBehavior::Sync => { + let mut d_formats: Vec<(Duration, DownloadFormat)> = vec![]; + + for (single_format, video, audio, subtitles) in format_pairs { + 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_iter() { + download_formats.push(d_format); + } + } + } + + Ok(( + download_formats, + 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/mod.rs b/crunchy-cli-core/src/archive/mod.rs new file mode 100644 index 0000000..670d0c2 --- /dev/null +++ b/crunchy-cli-core/src/archive/mod.rs @@ -0,0 +1,3 @@ +mod command; + +pub use command::Archive; diff --git a/crunchy-cli-core/src/download/command.rs b/crunchy-cli-core/src/download/command.rs new file mode 100644 index 0000000..8e3794f --- /dev/null +++ b/crunchy-cli-core/src/download/command.rs @@ -0,0 +1,483 @@ +use crate::utils::context::Context; +use crate::utils::download::{DownloadBuilder, DownloadFormat, DownloadFormatMetadata}; +use crate::utils::ffmpeg::{FFmpegPreset, SOFTSUB_CONTAINERS}; +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::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, error, warn}; +use std::collections::HashMap; +use std::path::Path; + +#[derive(Clone, Debug, clap::Parser)] +#[clap(about = "Download a video")] +#[command(arg_required_else_help(true))] +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 {}\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: {}\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. \ + If you use one of the following pattern they will get replaced:\n \ + {title} → Title of the video\n \ + {series_name} → Name of the series\n \ + {season_name} → Name of the season\n \ + {audio} → Audio language of the video\n \ + {width} → Width of the video\n \ + {height} → Height of the video\n \ + {season_number} → Number of the season\n \ + {episode_number} → Number of the episode\n \ + {relative_episode_number} → Number of the episode relative to its season\n \ + {sequence_number} → Like '{episode_number}' but without possible non-number characters\n \ + {relative_sequence_number} → Like '{relative_episode_number}' but with support for episode 0's and .5's\n \ + {release_year} → Release year of the video\n \ + {release_month} → Release month of the video\n \ + {release_day} → Release day of the video\n \ + {series_id} → ID of the series\n \ + {season_id} → ID of the season\n \ + {episode_id} → ID of the episode")] + #[arg(short, long, default_value = "{title}.mp4")] + pub(crate) output: String, + #[arg(help = "Name of the output file if the episode is a special")] + #[arg(long_help = "Name of the output file if the episode is a special. \ + If not set, the '-o'/'--output' flag will be used as name template")] + #[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). \ + Specifying the exact pixels is not recommended, use one of the other options instead. \ + Crunchyroll let you choose the quality with pixel abbreviation on their clients, so you might be already familiar with the available options. \ + The available common-use words are 'best' (choose the best resolution available) and 'worst' (worst resolution available)")] + #[arg(short, long, default_value = "best")] + #[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. \ + If you need more specific ffmpeg customizations you can pass ffmpeg output arguments instead of a preset as value. \ + Available presets: \n {}", FFmpegPreset::available_matches_human_readable().join("\n ")))] + #[arg(long)] + #[arg(value_parser = FFmpegPreset::parse)] + pub(crate) ffmpeg_preset: Option, + #[arg( + help = "The number of threads used by ffmpeg to generate the output file. Does not work with every codec/preset" + )] + #[arg( + long_help = "The number of threads used by ffmpeg to generate the output file. \ + Does not work with every codec/preset and is skipped entirely when specifying custom ffmpeg output arguments instead of a preset for `--ffmpeg-preset`. \ + By default, ffmpeg chooses the thread count which works best for the output codec" + )] + #[arg(long)] + pub(crate) ffmpeg_threads: Option, + + #[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, + + #[arg(help = "Force subtitles to be always burnt-in")] + #[arg(long, default_value_t = false)] + pub(crate) force_hardsub: bool, + + #[arg(help = "The number of threads used to download")] + #[arg(short, long, default_value_t = num_cpus::get())] + pub(crate) threads: usize, + + #[arg(help = "Url(s) to Crunchyroll episodes or series")] + #[arg(required = true)] + pub(crate) urls: Vec, +} + +impl Execute for Download { + fn pre_check(&mut self) -> Result<()> { + if !has_ffmpeg() { + bail!("FFmpeg is needed to run this command") + } else if Path::new(&self.output) + .extension() + .unwrap_or_default() + .is_empty() + && !is_special_file(&self.output) + && self.output != "-" + { + bail!("No file extension found. Please specify a file extension (via `-o`) for the output file") + } + + if self.subtitle.is_some() { + if let Some(ext) = Path::new(&self.output).extension() { + if self.force_hardsub { + warn!("Hardsubs are forced. Adding subtitles may take a while") + } else if !["mkv", "mov", "mp4"].contains(&ext.to_string_lossy().as_ref()) { + warn!("Detected a container which does not support softsubs. Adding subtitles may take a while") + } + } + } + + if let Some(special_output) = &self.output_specials { + if Path::new(special_output) + .extension() + .unwrap_or_default() + .is_empty() + && !is_special_file(special_output) + && special_output != "-" + { + bail!("No file extension found. Please specify a file extension (via `--output-specials`) for the output file") + } + if let Some(ext) = Path::new(special_output).extension() { + if self.force_hardsub { + warn!("Hardsubs are forced for special episodes. Adding subtitles may take a while") + } else if !["mkv", "mov", "mp4"].contains(&ext.to_string_lossy().as_ref()) { + warn!("Detected a container which does not support softsubs. Adding subtitles for special episodes may take a while") + } + } + } + + if let Some(language_tagging) = &self.language_tagging { + self.audio = resolve_locales(&[self.audio.clone()]).remove(0); + self.subtitle = self + .subtitle + .as_ref() + .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( + &Path::new(&self.output) + .extension() + .unwrap_or_default() + .to_string_lossy() + .as_ref(), + ); + let special_output_supports_softsubs = if let Some(so) = &self.output_specials { + SOFTSUB_CONTAINERS.contains( + &Path::new(so) + .extension() + .unwrap_or_default() + .to_string_lossy() + .as_ref(), + ) + } else { + output_supports_softsubs + }; + + for (i, url) in self.urls.clone().into_iter().enumerate() { + let progress_handler = progress!("Parsing url {}", i + 1); + match parse_url(&ctx.crunchy, url.clone(), true).await { + Ok((media_collection, url_filter)) => { + progress_handler.stop(format!("Parsed url {}", i + 1)); + parsed_urls.push((media_collection, url_filter)) + } + Err(e) => bail!("url {} could not be parsed: {}", url, e), + }; + } + + for (i, (media_collection, url_filter)) in parsed_urls.into_iter().enumerate() { + let progress_handler = progress!("Fetching series details"); + 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)); + continue; + } + progress_handler.stop(format!("Loaded series information for url {}", i + 1)); + + single_format_collection.full_visual_output(); + + 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 + let single_format = single_formats.remove(0); + + let (download_format, format) = get_format( + &self, + &single_format, + if self.force_hardsub { + true + } else if single_format.is_special() { + !special_output_supports_softsubs + } else { + !output_supports_softsubs + }, + ) + .await?; + + let mut downloader = download_builder.clone().build(); + downloader.add_format(download_format); + + let formatted_path = if format.is_special() { + format.format_path( + 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(), + self.universal_output, + self.language_tagging.as_ref(), + ) + }; + let (path, changed) = free_file(formatted_path.clone()); + + if changed && self.skip_existing { + debug!( + "Skipping already existing file '{}'", + formatted_path.to_string_lossy() + ); + continue; + } + + format.visual_output(&path); + + downloader.download(&path).await? + } + } + + Ok(()) + } +} + +async fn get_format( + download: &Download, + single_format: &SingleFormat, + try_peer_hardsubs: bool, +) -> Result<(DownloadFormat, Format)> { + let stream = single_format.stream().await?; + let Some((video, audio, contains_hardsub)) = stream_data_from_stream( + &stream, + &download.resolution, + if try_peer_hardsubs { + download.subtitle.clone() + } else { + None + }, + ) + .await? + else { + if single_format.is_episode() { + bail!( + "Resolution ({}) is not available for episode {} ({}) of {} season {}", + download.resolution, + single_format.episode_number, + single_format.title, + single_format.series_name, + single_format.season_number, + ) + } else { + bail!( + "Resolution ({}) is not available for {} ({})", + download.resolution, + single_format.source_type(), + single_format.title + ) + } + }; + + let subtitle = if contains_hardsub { + None + } else if let Some(subtitle_locale) = &download.subtitle { + 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 + }; + + let download_format = DownloadFormat { + video: (video.clone(), single_format.audio.clone()), + audios: vec![(audio, single_format.audio.clone())], + subtitles: subtitle.clone().map_or(vec![], |s| { + vec![( + s, + 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(), + video, + subtitle.map_or(vec![], |s| { + vec![( + s, + single_format.audio != Locale::ja_JP && stream.subtitles.len() == 1, + )] + }), + )]); + if contains_hardsub { + let (_, subs) = format.locales.get_mut(0).unwrap(); + subs.push(download.subtitle.clone().unwrap()) + } + + stream.invalidate().await?; + + Ok((download_format, format)) +} diff --git a/crunchy-cli-core/src/download/mod.rs b/crunchy-cli-core/src/download/mod.rs new file mode 100644 index 0000000..47ca304 --- /dev/null +++ b/crunchy-cli-core/src/download/mod.rs @@ -0,0 +1,3 @@ +mod command; + +pub use command::Download; diff --git a/crunchy-cli-core/src/lib.rs b/crunchy-cli-core/src/lib.rs new file mode 100644 index 0000000..1c180e8 --- /dev/null +++ b/crunchy-cli-core/src/lib.rs @@ -0,0 +1,405 @@ +use crate::utils::context::Context; +use crate::utils::locale::system_locale; +use crate::utils::log::{progress, CliLogger}; +use anyhow::bail; +use anyhow::Result; +use clap::{Parser, Subcommand}; +use crunchyroll_rs::crunchyroll::CrunchyrollBuilder; +use crunchyroll_rs::error::Error; +use crunchyroll_rs::{Crunchyroll, Locale}; +use log::{debug, error, warn, LevelFilter}; +use reqwest::{Client, Proxy}; +use std::{env, fs}; + +mod archive; +mod download; +mod login; +mod search; +mod utils; + +use crate::utils::rate_limit::RateLimiterService; +pub use archive::Archive; +use dialoguer::console::Term; +pub use download::Download; +pub use login::Login; +pub use search::Search; + +trait Execute { + fn pre_check(&mut self) -> Result<()> { + Ok(()) + } + async fn execute(self, ctx: Context) -> Result<()>; +} + +#[derive(Debug, Parser)] +#[clap(author, version = version(), about)] +#[clap(name = "crunchy-cli")] +pub struct Cli { + #[clap(flatten)] + verbosity: Verbosity, + + #[arg( + help = "Overwrite the language in which results are returned. Default is your system language" + )] + #[arg(global = true, long)] + lang: Option, + + #[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" + )] + #[arg(global = true, long, default_value_t = false)] + experimental_fixes: bool, + + #[clap(flatten)] + login_method: login::LoginMethod, + + #[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. \ + 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)] + user_agent: Option, + + #[arg( + help = "Maximal speed to download/request (may be a bit off here and there). Must be in format of [B|KB|MB]" + )] + #[arg( + long_help = "Maximal speed to download/request (may be a bit off here and there). Must be in format of [B|KB|MB] (e.g. 500KB or 10MB)" + )] + #[arg(global = true, long, value_parser = crate::utils::clap::clap_parse_speed_limit)] + speed_limit: Option, + + #[clap(subcommand)] + command: Command, +} + +fn version() -> String { + let package_version = env!("CARGO_PKG_VERSION"); + let git_commit_hash = env!("GIT_HASH"); + let build_date = env!("BUILD_DATE"); + + if git_commit_hash.is_empty() { + package_version.to_string() + } else { + format!("{} ({} {})", package_version, git_commit_hash, build_date) + } +} + +#[derive(Debug, Subcommand)] +enum Command { + Archive(Archive), + Download(Download), + Login(Login), + Search(Search), +} + +#[derive(Debug, Parser)] +struct Verbosity { + #[arg(help = "Verbose output")] + #[arg(global = true, short, long)] + verbose: bool, + + #[arg(help = "Quiet output. Does not print anything unless it's a error")] + #[arg( + long_help = "Quiet output. Does not print anything unless it's a error. Can be helpful if you pipe the output to stdout" + )] + #[arg(global = true, short, long)] + quiet: bool, +} + +pub async fn main(args: &[String]) { + let mut cli: Cli = Cli::parse_from(args); + + 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 cli.verbosity.verbose { + CliLogger::init(LevelFilter::Debug).unwrap() + } else if cli.verbosity.quiet { + CliLogger::init(LevelFilter::Error).unwrap() + } + } else { + CliLogger::init(LevelFilter::Info).unwrap() + } + + debug!("cli input: {:?}", cli); + + match &mut cli.command { + Command::Archive(archive) => { + // prevent interactive select to be shown when output should be 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.quiet { + download.yes = true; + } + pre_check_executor(download).await + } + Command::Login(login) => { + if login.remove { + if let Some(session_file) = login::session_file_path() { + let _ = fs::remove_file(session_file); + } + return; + } else { + pre_check_executor(login).await + } + } + Command::Search(search) => pre_check_executor(search).await, + }; + + let ctx = match create_ctx(&mut cli).await { + Ok(ctx) => ctx, + Err(e) => { + error!("{}", e); + std::process::exit(1) + } + }; + debug!("Created context"); + + ctrlc::set_handler(move || { + debug!("Ctrl-c detected"); + if let Ok(dir) = fs::read_dir(env::temp_dir()) { + for file in dir.flatten() { + if file + .path() + .file_name() + .unwrap_or_default() + .to_str() + .unwrap_or_default() + .starts_with(".crunchy-cli_") + { + 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" + } + ) + } + } + } + } + // when pressing ctrl-c while interactively choosing seasons the cursor stays hidden, this + // line shows it again + let _ = Term::stdout().show_cursor(); + std::process::exit(1) + }) + .unwrap(); + debug!("Created ctrl-c handler"); + + match cli.command { + Command::Archive(archive) => execute_executor(archive, ctx).await, + Command::Download(download) => execute_executor(download, ctx).await, + Command::Login(login) => execute_executor(login, ctx).await, + Command::Search(search) => execute_executor(search, ctx).await, + }; +} + +async fn pre_check_executor(executor: &mut impl Execute) { + if let Err(err) = executor.pre_check() { + error!("Misconfigurations detected: {}", err); + std::process::exit(1) + } +} + +async fn execute_executor(executor: impl Execute, ctx: Context) { + if let Err(mut err) = executor.execute(ctx).await { + 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() + } + + error!("An error occurred: {}", crunchy_error) + } else { + error!("An error occurred: {}", err) + } + + std::process::exit(1) + } +} + +async fn create_ctx(cli: &mut Cli) -> Result { + 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, + client: Client, + rate_limiter: Option, +) -> Result { + let supported_langs = vec![ + Locale::ar_ME, + Locale::de_DE, + Locale::en_US, + Locale::es_ES, + Locale::es_419, + Locale::fr_FR, + Locale::it_IT, + Locale::pt_BR, + Locale::pt_PT, + Locale::ru_RU, + ]; + let locale = if let Some(lang) = &cli.lang { + if !supported_langs.contains(lang) { + bail!( + "Via `--lang` specified language is not supported. Supported languages: {}", + supported_langs + .iter() + .map(|l| format!("`{}` ({})", l, l.to_human_readable())) + .collect::>() + .join(", ") + ) + } + lang.clone() + } else { + let mut lang = system_locale(); + if !supported_langs.contains(&lang) { + warn!("Recognized system locale is not supported. Using en-US as default. Use `--lang` to overwrite the used language"); + lang = Locale::en_US + } + lang + }; + + let mut builder = Crunchyroll::builder() + .locale(locale) + .client(client.clone()) + .stabilization_locales(cli.experimental_fixes) + .stabilization_season_number(cli.experimental_fixes); + if let Command::Download(download) = &cli.command { + builder = builder.preferred_audio_locale(download.audio.clone()) + } + 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.anonymous as u8; + + let progress_handler = progress!("Logging in"); + if root_login_methods_count == 0 { + if let Some(login_file_path) = login::session_file_path() { + if login_file_path.exists() { + let session = fs::read_to_string(login_file_path)?; + if let Some((token_type, token)) = session.split_once(':') { + match token_type { + "refresh_token" => { + return match builder.login_with_refresh_token(token).await { + Ok(crunchy) => Ok(crunchy), + Err(e) => { + if let Error::Request { message, .. } = &e { + if message.starts_with("invalid_grant") { + bail!("The stored login is expired, please login again") + } + } + Err(e.into()) + } + } + } + "etp_rt" => bail!("The stored login method (etp-rt) isn't supported anymore. Please login again using your credentials"), + _ => (), + } + } + bail!("Could not read stored session ('{}')", session) + } + } + bail!("Please use a login method ('--credentials' or '--anonymous')") + } else if root_login_methods_count > 1 { + bail!("Please use only one login method ('--credentials' or '--anonymous')") + } + + let crunchy = if let Some(credentials) = &cli.login_method.credentials { + if let Some((email, password)) = credentials.split_once(':') { + builder.login_with_credentials(email, password).await? + } else { + bail!("Invalid credentials format. Please provide your credentials as email:password") + } + } else if cli.login_method.anonymous { + builder.login_anonymously().await? + } else { + bail!("should never happen") + }; + + progress_handler.stop("Logged in"); + + 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 new file mode 100644 index 0000000..4da1898 --- /dev/null +++ b/crunchy-cli-core/src/login/command.rs @@ -0,0 +1,55 @@ +use crate::utils::context::Context; +use crate::Execute; +use anyhow::bail; +use anyhow::Result; +use clap::Parser; +use crunchyroll_rs::crunchyroll::SessionToken; +use log::info; +use std::fs; +use std::path::PathBuf; + +#[derive(Debug, clap::Parser)] +#[clap(about = "Save your login credentials persistent on disk")] +pub struct Login { + #[arg(help = "Remove your stored credentials (instead of saving them)")] + #[arg(long)] + pub remove: bool, +} + +impl Execute for Login { + async fn execute(self, ctx: Context) -> Result<()> { + if let Some(login_file_path) = session_file_path() { + fs::create_dir_all(login_file_path.parent().unwrap())?; + + match ctx.crunchy.session_token().await { + SessionToken::RefreshToken(refresh_token) => { + fs::write(login_file_path, format!("refresh_token:{}", refresh_token))? + } + 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"), + } + + info!("Saved login"); + + Ok(()) + } else { + bail!("Cannot find config path") + } + } +} + +#[derive(Clone, Debug, Parser)] +pub struct LoginMethod { + #[arg( + help = "Login with credentials (email and password). Must be provided as email:password" + )] + #[arg(global = true, long)] + pub credentials: Option, + #[arg(help = "Login anonymously / without an account")] + #[arg(global = true, long, default_value_t = false)] + pub anonymous: bool, +} + +pub fn session_file_path() -> Option { + dirs::config_dir().map(|config_dir| config_dir.join("crunchy-cli").join("session")) +} diff --git a/crunchy-cli-core/src/login/mod.rs b/crunchy-cli-core/src/login/mod.rs new file mode 100644 index 0000000..8c1220a --- /dev/null +++ b/crunchy-cli-core/src/login/mod.rs @@ -0,0 +1,3 @@ +mod command; + +pub use command::{session_file_path, Login, LoginMethod}; diff --git a/crunchy-cli-core/src/search/command.rs b/crunchy-cli-core/src/search/command.rs new file mode 100644 index 0000000..8032bed --- /dev/null +++ b/crunchy-cli-core/src/search/command.rs @@ -0,0 +1,222 @@ +use crate::search::filter::FilterOptions; +use crate::search::format::Format; +use crate::utils::context::Context; +use crate::utils::parse::{parse_url, UrlFilter}; +use crate::Execute; +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")] +#[command(arg_required_else_help(true))] +pub struct Search { + #[arg(help = format!("Audio languages to include. \ + Available languages are: {}", Locale::all().into_iter().map(|l| l.to_string()).collect::>().join(", ")))] + #[arg(long_help = format!("Audio languages to include. \ + Available languages are:\n {}", Locale::all().into_iter().map(|l| format!("{:<6} → {}", l.to_string(), l.to_human_readable())).collect::>().join("\n ")))] + #[arg(long, default_values_t = vec![crate::utils::locale::system_locale()])] + audio: Vec, + + #[arg(help = "Limit of search top search results")] + #[arg(long, default_value_t = 5)] + search_top_results_limit: u32, + #[arg(help = "Limit of search series results")] + #[arg(long, default_value_t = 0)] + search_series_limit: u32, + #[arg(help = "Limit of search movie listing results")] + #[arg(long, default_value_t = 0)] + search_movie_listing_limit: u32, + #[arg(help = "Limit of search episode results")] + #[arg(long, default_value_t = 0)] + search_episode_limit: u32, + #[arg(help = "Limit of search music results")] + #[arg(long, default_value_t = 0)] + search_music_limit: u32, + + /// Format of the output text. + /// + /// You can specify keywords in a specific pattern and they will get replaced in the output text. + /// The required pattern for this begins with `{{`, then the keyword, and closes with `}}` (e.g. `{{episode.title}}`). + /// For example, if you want to get the title of an episode, you can use `Title {{episode.title}}` and `{{episode.title}}` will be replaced with the episode title + /// + /// See the following list for all keywords and their meaning: + /// series.id → Series id + /// series.title → Series title + /// series.description → Series description + /// series.release_year → Series release year + /// + /// season.id → Season id + /// season.title → Season title + /// season.description → Season description + /// season.number → Season number + /// season.episodes → Number of episodes the season has + /// + /// episode.id → Episode id + /// episode.title → Episode title + /// episode.description → Episode description + /// episode.locale → Episode locale/language + /// episode.number → Episode number + /// episode.sequence_number → Episode number. This number is unique unlike `episode.number` which sometimes can be duplicated + /// episode.duration → Episode duration in milliseconds + /// episode.air_date → Episode air date as unix timestamp + /// episode.premium_only → If the episode is only available with Crunchyroll premium + /// + /// movie_listing.id → Movie listing id + /// movie_listing.title → Movie listing title + /// movie_listing.description → Movie listing description + /// + /// movie.id → Movie id + /// movie.title → Movie title + /// movie.description → Movie description + /// movie.duration → Movie duration in milliseconds + /// movie.premium_only → If the movie is only available with Crunchyroll premium + /// + /// music_video.id → Music video id + /// music_video.title → Music video title + /// music_video.description → Music video description + /// music_video.duration → Music video duration in milliseconds + /// music_video.premium_only → If the music video is only available with Crunchyroll premium + /// + /// concert.id → Concert id + /// concert.title → Concert title + /// concert.description → Concert description + /// concert.duration → Concert duration in milliseconds + /// 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. 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, + + input: String, +} + +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], + Err(e) => bail!("url {} could not be parsed: {}", self.input, e), + } + } else { + let mut output = vec![]; + + let query = resolve_query(&self, ctx.crunchy.query(&self.input)).await?; + output.extend(query.0.into_iter().map(|m| (m, UrlFilter::default()))); + output.extend( + query + .1 + .into_iter() + .map(|s| (s.into(), UrlFilter::default())), + ); + output.extend( + query + .2 + .into_iter() + .map(|m| (m.into(), UrlFilter::default())), + ); + output.extend( + query + .3 + .into_iter() + .map(|e| (e.into(), UrlFilter::default())), + ); + output.extend( + query + .4 + .into_iter() + .map(|m| (m.into(), UrlFilter::default())), + ); + + 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, crunchy_arc.clone())?; + println!("{}", format.parse(media_collection).await?); + } + + Ok(()) + } +} + +macro_rules! resolve_query { + ($limit:expr, $vec:expr, $item:expr) => { + if $limit > 0 { + let mut item_results = $item; + while let Some(item) = item_results.next().await { + $vec.push(item?); + if $vec.len() >= $limit as usize { + break; + } + } + } + }; +} + +async fn resolve_query( + search: &Search, + query_results: QueryResults, +) -> Result<( + Vec, + Vec, + Vec, + Vec, + Vec, +)> { + let mut media_collection = vec![]; + let mut series = vec![]; + let mut movie_listing = vec![]; + let mut episode = vec![]; + let mut music_video = vec![]; + + resolve_query!( + search.search_top_results_limit, + media_collection, + query_results.top_results + ); + resolve_query!(search.search_series_limit, series, query_results.series); + resolve_query!( + search.search_movie_listing_limit, + movie_listing, + query_results.movie_listing + ); + resolve_query!(search.search_episode_limit, episode, query_results.episode); + resolve_query!(search.search_music_limit, music_video, query_results.music); + + Ok(( + media_collection, + series, + movie_listing, + episode, + music_video, + )) +} diff --git a/crunchy-cli-core/src/search/filter.rs b/crunchy-cli-core/src/search/filter.rs new file mode 100644 index 0000000..3bb6d9f --- /dev/null +++ b/crunchy-cli-core/src/search/filter.rs @@ -0,0 +1,47 @@ +use crate::utils::parse::UrlFilter; +use crunchyroll_rs::{Episode, Locale, MovieListing, Season, Series}; + +pub struct FilterOptions { + pub audio: Vec, + pub url_filter: UrlFilter, +} + +impl FilterOptions { + pub fn check_series(&self, series: &Series) -> bool { + self.check_audio_language(&series.audio_locales) + } + + pub fn filter_seasons(&self, mut seasons: Vec) -> Vec { + seasons.retain(|s| { + self.check_audio_language(&s.audio_locales) + && self.url_filter.is_season_valid(s.season_number) + }); + seasons + } + + pub fn filter_episodes(&self, mut episodes: Vec) -> Vec { + episodes.retain(|e| { + self.check_audio_language(&[e.audio_locale.clone()]) + && self + .url_filter + .is_episode_valid(e.sequence_number, e.season_number) + }); + episodes + } + + pub fn check_movie_listing(&self, movie_listing: &MovieListing) -> bool { + self.check_audio_language( + &movie_listing + .audio_locale + .clone() + .map_or(vec![], |a| vec![a.clone()]), + ) + } + + fn check_audio_language(&self, audio: &[Locale]) -> bool { + if !self.audio.is_empty() { + return self.audio.iter().any(|a| audio.contains(a)); + } + true + } +} diff --git a/crunchy-cli-core/src/search/format.rs b/crunchy-cli-core/src/search/format.rs new file mode 100644 index 0000000..cf3c5bc --- /dev/null +++ b/crunchy-cli-core/src/search/format.rs @@ -0,0 +1,687 @@ +use crate::search::filter::FilterOptions; +use anyhow::{bail, Result}; +use crunchyroll_rs::media::{Stream, Subtitle}; +use crunchyroll_rs::{ + 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 { + pub id: String, + pub title: String, + pub description: String, + pub release_year: u32, +} + +impl From<&Series> for FormatSeries { + fn from(value: &Series) -> Self { + Self { + id: value.id.clone(), + title: value.title.clone(), + description: value.description.clone(), + release_year: value.series_launch_year.unwrap_or_default(), + } + } +} + +#[derive(Default, Serialize)] +struct FormatSeason { + pub id: String, + pub title: String, + pub description: String, + pub number: u32, + pub episodes: u32, +} + +impl From<&Season> for FormatSeason { + fn from(value: &Season) -> Self { + Self { + id: value.id.clone(), + title: value.title.clone(), + description: value.description.clone(), + number: value.season_number, + episodes: value.number_of_episodes, + } + } +} + +#[derive(Default, Serialize)] +struct FormatEpisode { + pub id: String, + pub title: String, + pub description: String, + pub locale: Locale, + pub number: u32, + pub sequence_number: f32, + pub duration: i64, + pub air_date: i64, + pub premium_only: bool, +} + +impl From<&Episode> for FormatEpisode { + fn from(value: &Episode) -> Self { + Self { + id: value.id.clone(), + title: value.title.clone(), + description: value.description.clone(), + locale: value.audio_locale.clone(), + number: value.episode_number.unwrap_or_default(), + sequence_number: value.sequence_number, + duration: value.duration.num_milliseconds(), + air_date: value.episode_air_date.timestamp(), + premium_only: value.is_premium_only, + } + } +} + +#[derive(Default, Serialize)] +struct FormatMovieListing { + pub id: String, + pub title: String, + pub description: String, +} + +impl From<&MovieListing> for FormatMovieListing { + fn from(value: &MovieListing) -> Self { + Self { + id: value.id.clone(), + title: value.title.clone(), + description: value.description.clone(), + } + } +} + +#[derive(Default, Serialize)] +struct FormatMovie { + pub id: String, + pub title: String, + pub description: String, + pub duration: i64, + pub premium_only: bool, +} + +impl From<&Movie> for FormatMovie { + fn from(value: &Movie) -> Self { + Self { + id: value.id.clone(), + title: value.title.clone(), + description: value.description.clone(), + duration: value.duration.num_milliseconds(), + premium_only: value.is_premium_only, + } + } +} + +#[derive(Default, Serialize)] +struct FormatMusicVideo { + pub id: String, + pub title: String, + pub description: String, + pub duration: i64, + pub premium_only: bool, +} + +impl From<&MusicVideo> for FormatMusicVideo { + fn from(value: &MusicVideo) -> Self { + Self { + id: value.id.clone(), + title: value.title.clone(), + description: value.description.clone(), + duration: value.duration.num_milliseconds(), + premium_only: value.is_premium_only, + } + } +} + +#[derive(Default, Serialize)] +struct FormatConcert { + pub id: String, + pub title: String, + pub description: String, + pub duration: i64, + pub premium_only: bool, +} + +impl From<&Concert> for FormatConcert { + fn from(value: &Concert) -> Self { + Self { + id: value.id.clone(), + title: value.title.clone(), + description: value.description.clone(), + duration: value.duration.num_milliseconds(), + premium_only: value.is_premium_only, + } + } +} + +#[derive(Default, Serialize)] +struct FormatStream { + pub locale: Locale, + pub dash_url: String, + pub is_drm: bool, +} + +impl From<&Stream> for FormatStream { + fn from(value: &Stream) -> Self { + Self { + locale: value.audio_locale.clone(), + dash_url: value.url.clone(), + is_drm: false, + } + } +} + +#[derive(Default, Serialize)] +struct FormatSubtitle { + pub locale: Locale, + pub url: String, +} + +impl From<&Subtitle> for FormatSubtitle { + fn from(value: &Subtitle) -> Self { + Self { + locale: value.locale.clone(), + url: value.url.clone(), + } + } +} + +#[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, + Season, + Episode, + MovieListing, + Movie, + MusicVideo, + Concert, + Stream, + Subtitle, + Account, +} + +macro_rules! must_match_if_true { + ($condition:expr => $media_collection:ident | $field:pat => $expr:expr) => { + if $condition { + match &$media_collection { + $field => Some($expr), + _ => panic!(), + } + } else { + None + } + }; +} + +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, + 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(); + + macro_rules! generate_field_check { + ($($scope:expr => $struct_:ident)+) => { + HashMap::from([ + $( + ( + $scope, + serde_json::from_value::>(serde_json::to_value($struct_::default()).unwrap()).unwrap() + ) + ),+ + ]) + }; + } + let field_check = generate_field_check!( + Scope::Series => FormatSeries + Scope::Season => FormatSeason + Scope::Episode => FormatEpisode + Scope::MovieListing => FormatMovieListing + Scope::Movie => FormatMovie + Scope::MusicVideo => FormatMusicVideo + Scope::Concert => FormatConcert + Scope::Stream => FormatStream + Scope::Subtitle => FormatSubtitle + Scope::Account => FormatAccount + ); + + for capture in scope_regex.captures_iter(&input) { + let full = capture.get(0).unwrap(); + let scope = capture.name("scope").unwrap().as_str(); + let field = capture.name("field").unwrap().as_str(); + + let format_pattern_scope = match scope { + "series" => Scope::Series, + "season" => Scope::Season, + "episode" => Scope::Episode, + "movie_listing" => Scope::MovieListing, + "movie" => Scope::Movie, + "music_video" => Scope::MusicVideo, + "concert" => Scope::Concert, + "stream" => Scope::Stream, + "subtitle" => Scope::Subtitle, + "account" => Scope::Account, + _ => bail!("'{}.{}' is not a valid keyword", scope, field), + }; + + if field_check + .get(&format_pattern_scope) + .unwrap() + .get(field) + .is_none() + { + bail!("'{}.{}' is not a valid keyword", scope, field) + } + + pattern.push(( + full.start()..full.end(), + format_pattern_scope.clone(), + field.to_string(), + )); + *pattern_count.entry(format_pattern_scope).or_default() += 1 + } + + Ok(Self { + pattern, + pattern_count, + input, + filter_options, + crunchyroll, + }) + } + + pub async fn parse(&self, media_collection: MediaCollection) -> Result { + match &media_collection { + MediaCollection::Series(_) + | MediaCollection::Season(_) + | MediaCollection::Episode(_) => { + self.check_scopes(vec![ + Scope::Series, + Scope::Season, + Scope::Episode, + Scope::Stream, + Scope::Subtitle, + Scope::Account, + ])?; + + self.parse_series(media_collection).await + } + MediaCollection::MovieListing(_) | MediaCollection::Movie(_) => { + self.check_scopes(vec![ + Scope::MovieListing, + 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, + Scope::Account, + ])?; + + self.parse_music_video(media_collection).await + } + MediaCollection::Concert(_) => { + self.check_scopes(vec![ + Scope::Concert, + Scope::Stream, + Scope::Subtitle, + Scope::Account, + ])?; + + self.parse_concert(media_collection).await + } + } + } + + async fn parse_series(&self, media_collection: MediaCollection) -> Result { + let series_empty = self.check_pattern_count_empty(Scope::Series); + let season_empty = self.check_pattern_count_empty(Scope::Season); + 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![]; + + let series = if !series_empty { + let series = match &media_collection { + MediaCollection::Series(series) => series.clone(), + MediaCollection::Season(season) => season.series().await?, + MediaCollection::Episode(episode) => episode.series().await?, + _ => panic!(), + }; + if !self.filter_options.check_series(&series) { + return Ok("".to_string()); + } + series + } else { + Series::default() + }; + if !season_empty || !episode_empty || !stream_empty { + let tmp_seasons = match &media_collection { + MediaCollection::Series(series) => series.seasons().await?, + MediaCollection::Season(season) => vec![season.clone()], + MediaCollection::Episode(_) => vec![], + _ => panic!(), + }; + let mut seasons = vec![]; + for season in tmp_seasons { + 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 + .filter_seasons(seasons) + .into_iter() + .map(|s| (s, vec![])), + ) + } else { + tree.push((Season::default(), vec![])) + } + if !episode_empty || !stream_empty { + match &media_collection { + MediaCollection::Episode(episode) => { + 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 + .into_iter() + .filter(|e| self.filter_options.audio.contains(&e.audio_locale)) + .map(|e| (e, vec![])) + .collect(), + )) + } + _ => { + for (season, episodes) in tree.iter_mut() { + episodes.extend( + self.filter_options + .filter_episodes(season.episodes().await?) + .into_iter() + .map(|e| (e, vec![])), + ) + } + } + }; + } else { + for (_, episodes) in tree.iter_mut() { + episodes.push((Episode::default(), vec![])) + } + } + if !stream_empty { + for (_, episodes) in tree.iter_mut() { + for (episode, streams) in episodes { + let stream = episode.stream_maybe_without_drm().await?; + stream.clone().invalidate().await?; + streams.push(stream) + } + } + } else { + for (_, episodes) in tree.iter_mut() { + for (_, streams) in episodes { + streams.push(Stream::default()) + } + } + } + + 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)); + for (episode, streams) in episodes { + let episode_map = self.serializable_to_json_map(FormatEpisode::from(&episode)); + for stream in streams { + let stream_map = self.serializable_to_json_map(FormatStream::from(&stream)); + + output.push( + self.replace_all( + HashMap::from([ + (Scope::Account, &account_map), + (Scope::Series, &series_map), + (Scope::Season, &season_map), + (Scope::Episode, &episode_map), + (Scope::Stream, &stream_map), + ]), + stream, + ) + .unwrap_or_default(), + ) + } + } + } + + Ok(output.join("\n")) + } + + async fn parse_movie_listing(&self, media_collection: MediaCollection) -> Result { + let movie_listing_empty = self.check_pattern_count_empty(Scope::MovieListing); + let movie_empty = self.check_pattern_count_empty(Scope::Movie); + let stream_empty = self.check_pattern_count_empty(Scope::Stream); + + let mut tree: Vec<(Movie, Vec)> = vec![]; + + let movie_listing = if !movie_listing_empty { + let movie_listing = match &media_collection { + MediaCollection::MovieListing(movie_listing) => movie_listing.clone(), + MediaCollection::Movie(movie) => movie.movie_listing().await?, + _ => panic!(), + }; + if !self.filter_options.check_movie_listing(&movie_listing) { + return Ok("".to_string()); + } + movie_listing + } else { + MovieListing::default() + }; + if !movie_empty || !stream_empty { + let movies = match &media_collection { + MediaCollection::MovieListing(movie_listing) => movie_listing.movies().await?, + MediaCollection::Movie(movie) => vec![movie.clone()], + _ => panic!(), + }; + tree.extend(movies.into_iter().map(|m| (m, vec![]))) + } + if !stream_empty { + for (movie, streams) in tree.iter_mut() { + streams.push(movie.stream_maybe_without_drm().await?) + } + } else { + for (_, streams) in tree.iter_mut() { + streams.push(Stream::default()) + } + } + + let mut output = vec![]; + let movie_listing_map = + self.serializable_to_json_map(FormatMovieListing::from(&movie_listing)); + for (movie, streams) in tree { + let movie_map = self.serializable_to_json_map(FormatMovie::from(&movie)); + for stream in streams { + let stream_map = self.serializable_to_json_map(FormatStream::from(&stream)); + + output.push( + self.replace_all( + HashMap::from([ + (Scope::MovieListing, &movie_listing_map), + (Scope::Movie, &movie_map), + (Scope::Stream, &stream_map), + ]), + stream, + ) + .unwrap_or_default(), + ) + } + } + + Ok(output.join("\n")) + } + + async fn parse_music_video(&self, media_collection: MediaCollection) -> Result { + let music_video_empty = self.check_pattern_count_empty(Scope::MusicVideo); + 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_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)); + + let output = self + .replace_all( + HashMap::from([ + (Scope::MusicVideo, &music_video_map), + (Scope::Stream, &stream_map), + ]), + stream, + ) + .unwrap_or_default(); + Ok(output) + } + + async fn parse_concert(&self, media_collection: MediaCollection) -> Result { + let concert_empty = self.check_pattern_count_empty(Scope::Concert); + 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_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)); + + let output = self + .replace_all( + HashMap::from([(Scope::Concert, &concert_map), (Scope::Stream, &stream_map)]), + stream, + ) + .unwrap_or_default(); + Ok(output) + } + + fn serializable_to_json_map(&self, s: S) -> Map { + serde_json::from_value(serde_json::to_value(s).unwrap()).unwrap() + } + + fn check_pattern_count_empty(&self, scope: Scope) -> bool { + self.pattern_count.get(&scope).cloned().unwrap_or_default() == 0 + } + + fn check_scopes(&self, available_scopes: Vec) -> Result<()> { + for (_, scope, field) in self.pattern.iter() { + if !available_scopes.contains(scope) { + bail!( + "'{}.{}' is not a valid keyword", + format!("{:?}", scope).to_lowercase(), + field + ) + } + } + Ok(()) + } + + fn replace_all( + &self, + values: HashMap>, + mut stream: Stream, + ) -> Option { + if stream.subtitles.is_empty() { + if !self.check_pattern_count_empty(Scope::Subtitle) { + return None; + } + stream + .subtitles + .insert(Locale::Custom("".to_string()), Subtitle::default()); + } + + let mut output = vec![]; + for (_, subtitle) in stream.subtitles { + let subtitle_map = self.serializable_to_json_map(FormatSubtitle::from(&subtitle)); + let mut tmp_values = values.clone(); + tmp_values.insert(Scope::Subtitle, &subtitle_map); + output.push(self.replace(tmp_values)) + } + + Some(output.join("\n")) + } + + fn replace(&self, values: HashMap>) -> String { + let mut output = self.input.clone(); + let mut offset = 0; + for (range, scope, field) in &self.pattern { + let item = + serde_plain::to_string(values.get(scope).unwrap().get(field.as_str()).unwrap()) + .unwrap(); + let start = (range.start as i32 + offset) as usize; + let end = (range.end as i32 + offset) as usize; + output.replace_range(start..end, &item); + offset += item.len() as i32 - range.len() as i32; + } + + output + } +} diff --git a/crunchy-cli-core/src/search/mod.rs b/crunchy-cli-core/src/search/mod.rs new file mode 100644 index 0000000..839c844 --- /dev/null +++ b/crunchy-cli-core/src/search/mod.rs @@ -0,0 +1,5 @@ +mod command; +mod filter; +mod format; + +pub use command::Search; diff --git a/crunchy-cli-core/src/utils/clap.rs b/crunchy-cli-core/src/utils/clap.rs new file mode 100644 index 0000000..35de71f --- /dev/null +++ b/crunchy-cli-core/src/utils/clap.rs @@ -0,0 +1,61 @@ +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_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 { + let quota = s.to_lowercase(); + + let bytes = if let Ok(b) = quota.parse() { + b + } else if let Ok(b) = quota.trim_end_matches('b').parse::() { + b + } else if let Ok(kb) = quota.trim_end_matches("kb").parse::() { + kb * 1024 + } else if let Ok(mb) = quota.trim_end_matches("mb").parse::() { + mb * 1024 * 1024 + } else { + return Err("Invalid speed limit".to_string()); + }; + Ok(bytes) +} diff --git a/crunchy-cli-core/src/utils/context.rs b/crunchy-cli-core/src/utils/context.rs new file mode 100644 index 0000000..693174d --- /dev/null +++ b/crunchy-cli-core/src/utils/context.rs @@ -0,0 +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 new file mode 100644 index 0000000..2e8f321 --- /dev/null +++ b/crunchy-cli-core/src/utils/download.rs @@ -0,0 +1,1453 @@ +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, 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, HashMap}; +use std::io::Write; +use std::ops::Add; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::time::Duration; +use std::{env, fs}; +use tempfile::TempPath; +use time::Time; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader}; +use tokio::select; +use tokio::sync::mpsc::unbounded_channel; +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 { + pub fn parse(s: &str) -> Result { + Ok(match s.to_lowercase().as_str() { + "video" => MergeBehavior::Video, + "audio" => MergeBehavior::Audio, + "auto" => MergeBehavior::Auto, + "sync" => MergeBehavior::Sync, + _ => return Err(format!("'{}' is not a valid merge behavior", s)), + }) + } +} + +#[derive(Clone, derive_setters::Setters)] +pub struct DownloadBuilder { + client: Client, + rate_limiter: Option, + ffmpeg_preset: FFmpegPreset, + default_subtitle: Option, + output_format: Option, + audio_sort: Option>, + 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, rate_limiter: Option) -> DownloadBuilder { + Self { + client, + rate_limiter, + ffmpeg_preset: FFmpegPreset::default(), + default_subtitle: None, + output_format: None, + audio_sort: None, + 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, + audio_sort: self.audio_sort, + subtitle_sort: self.subtitle_sort, + + 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 FFmpegVideoMeta { + path: TempPath, + 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: (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, + output_format: Option, + audio_sort: Option>, + subtitle_sort: Option>, + + 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 { + pub fn add_format(&mut self, format: DownloadFormat) { + self.formats.push(format); + } + + pub async fn download(mut self, dst: &Path) -> Result<()> { + // `.unwrap_or_default()` here unless https://doc.rust-lang.org/stable/std/path/fn.absolute.html + // gets stabilized as the function might throw error on weird file paths + let required = self.check_free_space(dst).await.unwrap_or_default(); + if let Some((path, tmp_required)) = &required.0 { + let kb = (*tmp_required as f64) / 1024.0; + let mb = kb / 1024.0; + let gb = mb / 1024.0; + warn!( + "You may have not enough disk space to store temporary files. The temp directory ({}) should have at least {}{} free space", + path.to_string_lossy(), + if gb < 1.0 { mb.ceil().to_string() } else { format!("{:.2}", gb) }, + if gb < 1.0 { "MB" } else { "GB" } + ) + } + if let Some((path, dst_required)) = &required.1 { + let kb = (*dst_required as f64) / 1024.0; + let mb = kb / 1024.0; + let gb = mb / 1024.0; + warn!( + "You may have not enough disk space to store the output file. The directory {} should have at least {}{} free space", + path.to_string_lossy(), + if gb < 1.0 { mb.ceil().to_string() } else { format!("{:.2}", gb) }, + if gb < 1.0 { "MB" } else { "GB" } + ) + } + + if let Some(audio_sort_locales) = &self.audio_sort { + self.formats.sort_by(|a, b| { + audio_sort_locales + .iter() + .position(|l| l == &a.video.1) + .cmp(&audio_sort_locales.iter().position(|l| l == &b.video.1)) + }); + } + for format in self.formats.iter_mut() { + if let Some(audio_sort_locales) = &self.audio_sort { + format.audios.sort_by(|(_, a), (_, b)| { + audio_sort_locales + .iter() + .position(|l| l == a) + .cmp(&audio_sort_locales.iter().position(|l| l == b)) + }) + } + if let Some(subtitle_sort) = &self.subtitle_sort { + format + .subtitles + .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_cc.cmp(b_cc).reverse() + } else { + ordering + } + }) + } + } + + 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 chapters = None; + let mut max_len = TimeDelta::min_value(); + let mut max_frames = 0; + let fmt_space = self + .formats + .iter() + .flat_map(|f| { + f.audios + .iter() + .map(|(_, locale)| format!("Downloading {} audio", locale).len()) + }) + .max() + .unwrap(); + + // downloads all audios + for (i, format) in self.formats.iter().enumerate() { + for (stream_data, locale) in &format.audios { + let path = self + .download_audio( + stream_data, + format!("{:<1$}", format!("Downloading {} audio", locale), fmt_space), + ) + .await?; + raw_audios.push(SyncAudio { + format_id: i, + path, + locale: locale.clone(), + sample_rate: stream_data.sampling_rate().unwrap(), + video_idx: i, + }) + } + } + + 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 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 + } + } + + 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 + && !self.force_hardsub + && dst.extension().unwrap_or_default().to_str().unwrap() == "mkv" + { + let mut font_names = vec![]; + for subtitle in subtitles.iter() { + font_names.extend(get_subtitle_stats(&subtitle.path)?) + } + real_dedup_vec(&mut font_names); + + 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 fonts", 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 font_name in font_names { + if let Some(pb) = &progress_spinner { + let mut progress_message = pb.message(); + if !progress_message.is_empty() { + progress_message += ", " + } + progress_message += &font_name; + pb.set_message(progress_message) + } + if let Some((font, cached)) = self.download_font(&font_name).await? { + if cached { + if let Some(pb) = &progress_spinner { + let mut progress_message = pb.message(); + progress_message += " (cached)"; + pb.set_message(progress_message) + } + debug!("Downloaded font {} (cached)", font_name); + } else { + debug!("Downloaded font {}", font_name); + } + + fonts.push(font) + } + } + } + + let mut input = vec![]; + let mut maps = vec![]; + let mut attachments = vec![]; + 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={}", + 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={}", + self.audio_locale_output_map + .get(&meta.locale) + .unwrap_or(&meta.locale.to_string()) + ), + ]); + metadata.extend([ + format!("-metadata:s:a:{}", i), + format!( + "title={}", + if videos.len() == 1 { + meta.locale.to_human_readable() + } else { + format!( + "{} [Video: #{}]", + meta.locale.to_human_readable(), + meta.video_idx + 1 + ) + } + ), + ]); + } + + for (i, font) in fonts.iter().enumerate() { + attachments.extend(["-attach".to_string(), font.to_string_lossy().to_string()]); + metadata.extend([ + format!("-metadata:s:t:{}", i), + "mimetype=font/woff2".to_string(), + ]) + } + + // this formats are supporting embedding subtitles into the video container instead of + // burning it into the video stream directly + let container_supports_softsubs = !self.force_hardsub + && ["mkv", "mov", "mp4"] + .contains(&dst.extension().unwrap_or_default().to_str().unwrap()); + + 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(), + (i + videos.len() + audios.len()).to_string(), + ]); + metadata.extend([ + format!("-metadata:s:s:{}", i), + 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={}", { + 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()?; + + let mut command_args = vec![ + "-y".to_string(), + "-hide_banner".to_string(), + "-vstats_file".to_string(), + fifo.path().to_string_lossy().to_string(), + ]; + command_args.extend(input_presets); + command_args.extend(input); + command_args.extend(maps); + command_args.extend(attachments); + command_args.extend(metadata); + if !preset_custom { + if let Some(ffmpeg_threads) = self.ffmpeg_threads { + command_args.extend(vec!["-threads".to_string(), ffmpeg_threads.to_string()]) + } + } + + // set default subtitle + if let Some(default_subtitle) = self.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([ + "-movflags".to_string(), + "faststart".to_string(), + "-c:s".to_string(), + "mov_text".to_string(), + ]), + _ => (), + } + } else { + // remove '-c:v copy' and '-c:a copy' from output presets as its causes issues with + // burning subs into the video + let mut last = String::new(); + let mut remove_count = 0; + for (i, s) in output_presets.clone().iter().enumerate() { + if (last == "-c:v" || last == "-c:a") && s == "copy" { + // remove last + output_presets.remove(i - remove_count - 1); + remove_count += 1; + output_presets.remove(i - remove_count); + remove_count += 1; + } + last.clone_from(s); + } + + output_presets.extend([ + "-vf".to_string(), + format!( + "ass='{}'", + // ffmpeg doesn't removes all ':' and '\' from the filename when using + // the ass filter. well, on windows these characters are used in + // absolute paths, so they have to be correctly escaped here + if cfg!(windows) { + subtitles + .get(position) + .unwrap() + .path + .to_str() + .unwrap() + .replace('\\', "\\\\") + .replace(':', "\\:") + } else { + subtitles + .get(position) + .unwrap() + .path + .to_string_lossy() + .to_string() + } + ), + ]) + } + } + + if container_supports_softsubs { + if let Some(position) = subtitles + .iter() + .position(|meta| meta.locale == default_subtitle) + { + command_args.extend([ + format!("-disposition:s:s:{}", position), + "default".to_string(), + ]) + } + } + } + + // set the 'forced' flag to CC subtitles + for (i, subtitle) in subtitles.iter().enumerate() { + if !subtitle.cc { + continue; + } + + command_args.extend([format!("-disposition:s:s:{}", i), "forced".to_string()]) + } + + command_args.extend(output_presets); + if let Some(output_format) = self.output_format { + command_args.extend(["-f".to_string(), output_format]); + } + + // prepend './' to the path on linux since ffmpeg may interpret the path incorrectly if it's just the filename. + // see https://github.com/crunchy-labs/crunchy-cli/issues/303 for example + if !cfg!(windows) + && dst + .parent() + .map_or(true, |p| p.to_string_lossy().is_empty()) + { + command_args.push(Path::new("./").join(dst).to_string_lossy().to_string()); + } else { + command_args.push(dst.to_string_lossy().to_string()) + } + + debug!("ffmpeg {}", command_args.join(" ")); + + // create parent directory if it does not exist + if let Some(parent) = dst.parent() { + if !parent.exists() { + fs::create_dir_all(parent)? + } + } + + let ffmpeg = Command::new("ffmpeg") + // pass ffmpeg stdout to real stdout only if output file is stdout + .stdout(if dst.to_str().unwrap() == "-" { + Stdio::inherit() + } else { + Stdio::null() + }) + .stderr(Stdio::piped()) + .args(command_args) + .spawn()?; + let ffmpeg_progress_cancel = CancellationToken::new(); + let ffmpeg_progress_cancellation_token = ffmpeg_progress_cancel.clone(); + let ffmpeg_progress = tokio::spawn(async move { + ffmpeg_progress( + max_frames, + fifo, + format!("{:<1$}", "Generating output file", fmt_space + 1), + ffmpeg_progress_cancellation_token, + ) + .await + }); + + let result = ffmpeg.wait_with_output()?; + if !result.status.success() { + ffmpeg_progress.abort(); + bail!("{}", String::from_utf8_lossy(result.stderr.as_slice())) + } + ffmpeg_progress_cancel.cancel(); + ffmpeg_progress.await? + } + + async fn check_free_space( + &self, + dst: &Path, + ) -> Result<(Option<(PathBuf, u64)>, Option<(PathBuf, u64)>)> { + let mut all_stream_data = vec![]; + for format in &self.formats { + 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 stream_data in all_stream_data { + let segments = stream_data.segments(); + + // sum the length of all streams up + estimated_required_space += estimate_stream_data_file_size(stream_data, &segments); + } + + let tmp_stat = fs2::statvfs(temp_directory()).unwrap(); + let mut dst_file = if dst.is_absolute() { + dst.to_path_buf() + } else { + env::current_dir()?.join(dst) + }; + for ancestor in dst_file.ancestors() { + if ancestor.exists() { + dst_file = ancestor.to_path_buf(); + break; + } + } + let dst_stat = fs2::statvfs(&dst_file).unwrap(); + + let mut tmp_space = tmp_stat.available_space(); + let mut dst_space = dst_stat.available_space(); + + // this checks if the partition the two directories are located on are the same to prevent + // that the space fits both file sizes each but not together. this is done by checking the + // total space if each partition and the free space of each partition (the free space can + // differ by 10MB as some tiny I/O operations could be performed between the two calls which + // are checking the disk space) + if tmp_stat.total_space() == dst_stat.total_space() + && (tmp_stat.available_space() as i64 - dst_stat.available_space() as i64).abs() < 10240 + { + tmp_space *= 2; + dst_space *= 2; + } + + let mut tmp_required = None; + let mut dst_required = None; + + if tmp_space < estimated_required_space { + tmp_required = Some((temp_directory(), estimated_required_space)) + } + if (!is_special_file(dst) && dst.to_string_lossy() != "-") + && dst_space < estimated_required_space + { + dst_required = Some((dst_file, estimated_required_space)) + } + Ok((tmp_required, dst_required)) + } + + async fn download_video( + &self, + stream_data: &StreamData, + message: String, + max_segments: Option, + ) -> Result { + let tempfile = tempfile(".mp4")?; + let (mut file, path) = tempfile.into_parts(); + + self.download_segments(&mut file, message, stream_data, max_segments) + .await?; + + Ok(path) + } + + 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, stream_data, None) + .await?; + + Ok(path) + } + + async fn download_subtitle( + &self, + subtitle: Subtitle, + max_length: TimeDelta, + ) -> Result { + let buf = subtitle.data().await?; + let mut ass = match subtitle.format.as_str() { + "ass" => SSA::parse(String::from_utf8_lossy(&buf))?, + "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 path = tempfile.into_temp_path(); + + fs::write(&path, ass.to_string())?; + + Ok(path) + } + + async fn download_font(&self, name: &str) -> Result> { + let Some((_, font_file)) = FONTS.iter().find(|(f, _)| f == &name) else { + return Ok(None); + }; + + let cache_dir = cache_dir("fonts")?; + let file = cache_dir.join(font_file); + if file.exists() { + return Ok(Some((file, true))); + } + + // the speed limiter does not apply to this + let font = self + .client + .get(format!( + "https://static.crunchyroll.com/vilos-v2/web/vilos/assets/libass-fonts/{}", + font_file + )) + .send() + .await? + .bytes() + .await?; + fs::write(&file, font)?; + + Ok(Some((file, false))) + } + + async fn download_segments( + &self, + writer: &mut impl Write, + message: String, + stream_data: &StreamData, + max_segments: Option, + ) -> Result<()> { + 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_stream_data_file_size(stream_data, &segments); + + let progress = ProgressBar::new(estimated_file_size) + .with_style( + ProgressStyle::with_template( + ":: {msg} {bytes:>10} {bytes_per_sec:>12} [{wide_bar}] {percent:>3}%", + ) + .unwrap() + .progress_chars("##-"), + ) + .with_message(message) + .with_finish(ProgressFinish::Abandon); + Some(progress) + } else { + None + }; + + let cpus = self.download_threads.min(segments.len()); + let mut segs: Vec> = Vec::with_capacity(cpus); + for _ in 0..cpus { + segs.push(vec![]) + } + for (i, segment) in segments.clone().into_iter().enumerate() { + segs[i - ((i / cpus) * cpus)].push(segment); + } + + let (sender, mut receiver) = unbounded_channel(); + + let mut join_set: JoinSet> = JoinSet::new(); + 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(); + + // the download process is encapsulated in its own function. this is done to easily + // catch errors which get returned with `...?` and `bail!(...)` and that the thread + // itself can report that an error has occurred + let download = || async move { + for (i, segment) in thread_segments.into_iter().enumerate() { + let mut retry_count = 0; + let buf = loop { + 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 segment [{}/{} {:.2}%] {}", + num + (i * cpus) + 1, + total_segments, + ((*c + 1) as f64 / total_segments as f64) * 100f64, + segment.url + ); + + thread_sender.send((num as i32 + (i * cpus) as i32, buf))?; + + *c += 1; + } + Ok(()) + }; + + + let result = download().await; + if result.is_err() { + after_download_sender.send((-1, vec![]))?; + } + + result + }); + } + // drop the sender already here so it does not outlive all download threads which are the only + // real consumers of it + drop(sender); + + // this is the main loop which writes the data. it uses a BTreeMap as a buffer as the write + // happens synchronized. the download consist of multiple segments. the map keys are representing + // the segment number and the values the corresponding bytes + let mut data_pos = 0; + let mut buf: BTreeMap> = BTreeMap::new(); + while let Some((pos, bytes)) = receiver.recv().await { + // if the position is lower than 0, an error occurred in the sending download thread + if pos < 0 { + break; + } + + if let Some(p) = &progress { + let progress_len = p.length().unwrap(); + let estimated_segment_len = (stream_data.bandwidth / 8) + * segments.get(pos as usize).unwrap().length.as_secs(); + let bytes_len = bytes.len() as u64; + + p.set_length(progress_len - estimated_segment_len + bytes_len); + p.inc(bytes_len) + } + + // check if the currently sent bytes are the next in the buffer. if so, write them directly + // to the target without first adding them to the buffer. + // if not, add them to the buffer + if data_pos == pos { + writer.write_all(bytes.borrow())?; + data_pos += 1; + } else { + buf.insert(pos, bytes); + } + // check if the buffer contains the next segment(s) + while let Some(b) = buf.remove(&data_pos) { + writer.write_all(b.borrow())?; + data_pos += 1; + } + } + + // if any error has occurred while downloading it gets returned here + while let Some(joined) = join_set.join_next().await { + joined?? + } + + // write the remaining buffer, if existent + while let Some(b) = buf.remove(&data_pos) { + writer.write_all(b.borrow())?; + data_pos += 1; + } + + if !buf.is_empty() { + bail!( + "Download buffer is not empty. Remaining segments: {}", + buf.into_keys() + .map(|k| k.to_string()) + .collect::>() + .join(", ") + ) + } + + Ok(()) + } +} + +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<(TimeDelta, f64)> { + let video_length = Regex::new(r"Duration:\s(?P