+# This project has been sunset as Crunchyroll moved to a DRM-only system. See [#362](https://github.com/crunchy-labs/crunchy-cli/issues/362).
-# crunchyroll-go
+# crunchy-cli
-A [Go](https://golang.org) library & cli for the undocumented [crunchyroll](https://www.crunchyroll.com) api. To use it, you need a crunchyroll premium account to for full (api) access.
+👇 A Command-line downloader for [Crunchyroll](https://www.crunchyroll.com).
-# 🖥️ 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).
-- Archive episode or seasons in an `.mkv` file with multiple subtitles and audios and compress them to gzip or zip files.
-- Specify a range which episodes to download from an anime.
+- 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 [here](https://github.com/ByteDream/crunchyroll-go/releases/latest) or get it from below:
- - [Linux (x64)](https://smartrelease.bytedream.org/github/ByteDream/crunchyroll-go/crunchy-{tag}_linux)
- - [Windows (x64)](https://smartrelease.bytedream.org/github/ByteDream/crunchyroll-go/crunchy-{tag}_windows.exe)
- - [MacOS (x64)](https://smartrelease.bytedream.org/github/ByteDream/crunchyroll-go/crunchy-{tag}_darwin)
-- If you use Arch btw. or any other Linux distro which is based on Arch Linux, you can download the package via the [AUR](https://aur.archlinux.org/packages/crunchyroll-go/):
- ```
- $ yay -S crunchyroll-go
- ```
-- 🛠 Build it yourself
- - use `make` (requires `go` to be installed):
- ```
- $ git clone https://github.com/ByteDream/crunchyroll-go
- $ cd crunchyroll-go
- $ make && sudo make install
- ```
- - use `go`:
- ```
- $ git clone https://github.com/ByteDream/crunchyroll-go
- $ cd crunchyroll-go/cmd/crunchyroll-go
- $ go build -o crunchy
+### 📥 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/)
-_Before reading_: Because of the huge functionality not all cases can be covered in the README.
-Make sure to check the [wiki](https://github.com/ByteDream/crunchyroll-go/wiki/Cli), further usages and options are described there.
+ For Windows users, we support the [scoop](https://scoop.sh/#/) command-line installer.
+
+ ```shell
+ $ scoop bucket add extras
+ $ scoop install extras/crunchy-cli
+ ```
+
+- [Homebrew](https://brew.sh/)
+
+ 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.
+
+ ```shell
+ $ brew install crunchy-cli
+ ```
+
+ Supported archs: `x86_64_linux`, `arm64_monterey`, `sonoma`, `ventura`
+
+- [Nix](https://nixos.org/)
+
+ 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 .
+```
+
+## 🖥️ Usage
+
+> All shown commands are examples 🧑🏼🍳
+
+### Global Flags
+
+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
-Before you can do something, you have to login first.
+The `login` command can store your session, so you don't have to authenticate every time you execute a command.
-This can be performed via crunchyroll account email and password.
-```
-$ crunchy login user@example.com password
+```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"
```
-or via session id
-```
-$ crunchy login --session-id 8e9gs135defhga790dvrf2i0eris8gts
-```
+With the session stored, you do not need to pass `--credentials` / `--anonymous` anymore when you want to execute a command.
### Download
-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.**
+The `download` command lets you download episodes with a specific audio language and optional subtitles.
-```
-$ crunchy download https://www.crunchyroll.com/darling-in-the-franxx/episode-1-alone-and-lonesome-759575
-```
+**Supported urls**
-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
-```
+- 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
+ ```
-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
-```
+**Options**
-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
-```
+- Audio language
-##### Flags
+ 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.
-The following flags can be (optional) passed to modify the [download](#download) process.
+ ```shell
+ $ crunchy-cli download -a de-DE https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
+ ```
-| Short | Extended | Description |
-|-------|----------------|--------------------------------------------------------------------------------|
-| `-a` | `--audio` | Forces audio of the video(s). |
-| `-s` | `--subtitle` | Forces subtitle of the video(s). |
-| `-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. |
-| `-g` | `--goroutines` | Sets how many parallel segment downloads should be used. |
+ 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
-Archive works just like [download](#download). It downloads the given videos as `.mkv` files and stores all (soft) subtitles in it.
-Default audio locales are japanese and your system language (if available) but you can set more or less with the `--language` flag.
+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:
-Archive a file
```shell
-$ crunchy archive https://www.crunchyroll.com/darling-in-the-franxx/darling-in-the-franxx/episode-1-alone-and-lonesome-759575
+$ 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'
```
-Downloads the first two episode of Darling in the FranXX and stores it compressed in a file.
-```shell
-$ crunchy archive -c "ditf.tar.gz" https://www.crunchyroll.com/darling-in-the-franxx/darling-in-the-franxx
+#### Episode filtering
+
+Filters patterns can be used to download a specific range of episodes from a single series.
+
+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`.
+
+There are many possible patterns, for example:
+
+- `...[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 practice, it would look like this:
+
+```
+https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx[E1-E5]
```
-##### Flags
+# 📜 Disclaimer
-The following flags can be (optional) passed to modify the [archive](#archive) process.
+This tool is meant for private use only.
+You need a [Crunchyroll Premium](https://www.crunchyroll.com/welcome#plans) subscription to access premium content.
-| Short | Extended | Description |
-|-------|----------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| `-l` | `--language` | Audio locale which should be downloaded. Can be used multiple times. |
-| `-d` | `--directory` | Directory to download the video(s) to. |
-| `-o` | `--output` | Name of the output file. |
-| `-m` | `--merge` | Sets the behavior of the stream merging. Valid behaviors are 'auto', 'audio', 'video'. See the [wiki](https://github.com/ByteDream/crunchyroll-go/wiki/Cli#archive) for more information. |
-| `-c` | `--compress` | If is set, all output will be compresses into an archive. This flag sets the name of the compressed output file and the file ending specifies the compression algorithm (gzip, tar, zip are supported). |
-| `-r` | `--resolution` | The resolution of the video(s). `best` for best resolution, `worst` for worst. |
-| `-g` | `--goroutines` | Sets how many parallel segment downloads should be used. |
-
-### Help
-
-- General help
- ```shell
- $ crunchy help
- ```
-- Login help
- ```shell
- $ crunchy help login
- ```
-- Download help
- ```shell
- $ crunchy help download
- ```
-
-- Archive help
- ```shell
- $ crunchy help archive
- ```
-
-### Global flags
-
-These flags you can use across every sub-command
-
-| Flag | Description |
-|------|------------------------------------------------------|
-| `-q` | Disables all output. |
-| `-v` | Shows additional debug output. |
-| `-p` | Use a proxy to hide your ip / redirect your traffic. |
-
-# 📚 Library
-
-Download the library via `go get`
-```shell
-$ go get github.com/ByteDream/crunchyroll-go
-```
-
-The documentation is available on [pkg.go.dev](https://pkg.go.dev/github.com/ByteDream/crunchyroll-go).
-
-Examples how to use the library and some features of it are described in the [wiki](https://github.com/ByteDream/crunchyroll-go/wiki/Library).
-
-# ☝️ Disclaimer
-
-This tool is **ONLY** meant to be used for private purposes.
-To use this tool you need crunchyroll premium anyway, so there is no reason why rip and share the episodes.
-
-**The responsibility for what happens to the downloaded videos lies entirely with the user who downloaded them.**
+**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/archive.go b/cmd/crunchyroll-go/cmd/archive.go
deleted file mode 100644
index a36f806..0000000
--- a/cmd/crunchyroll-go/cmd/archive.go
+++ /dev/null
@@ -1,805 +0,0 @@
-package cmd
-
-import (
- "archive/tar"
- "archive/zip"
- "bufio"
- "bytes"
- "compress/gzip"
- "context"
- "fmt"
- "github.com/ByteDream/crunchyroll-go"
- "github.com/ByteDream/crunchyroll-go/utils"
- "github.com/grafov/m3u8"
- "github.com/spf13/cobra"
- "io"
- "os"
- "os/exec"
- "os/signal"
- "path/filepath"
- "regexp"
- "runtime"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
-)
-
-var (
- archiveLanguagesFlag []string
-
- archiveDirectoryFlag string
- archiveOutputFlag string
-
- archiveMergeFlag string
-
- archiveCompressFlag string
-
- archiveResolutionFlag string
-
- archiveGoroutinesFlag int
-)
-
-var archiveCmd = &cobra.Command{
- Use: "archive",
- Short: "Stores the given videos with all subtitles and multiple audios in a .mkv file",
- Args: cobra.MinimumNArgs(1),
-
- PreRunE: func(cmd *cobra.Command, args []string) error {
- out.Debug("Validating arguments")
-
- if !hasFFmpeg() {
- return fmt.Errorf("ffmpeg is needed to run this command correctly")
- }
- out.Debug("FFmpeg detected")
-
- if filepath.Ext(archiveOutputFlag) != ".mkv" {
- return fmt.Errorf("currently only matroska / .mkv files are supported")
- }
-
- for _, locale := range archiveLanguagesFlag {
- if !utils.ValidateLocale(crunchyroll.LOCALE(locale)) {
- // if locale is 'all', match all known locales
- if locale == "all" {
- archiveLanguagesFlag = allLocalesAsStrings()
- break
- }
- return fmt.Errorf("%s is not a valid locale. Choose from: %s", locale, strings.Join(allLocalesAsStrings(), ", "))
- }
- }
- out.Debug("Using following audio locales: %s", strings.Join(archiveLanguagesFlag, ", "))
-
- var found bool
- for _, mode := range []string{"auto", "audio", "video"} {
- if archiveMergeFlag == mode {
- out.Debug("Using %s merge behavior", archiveMergeFlag)
- found = true
- break
- }
- }
- if !found {
- return fmt.Errorf("'%s' is no valid merge flag. Use 'auto', 'audio' or 'video'", archiveMergeFlag)
- }
-
- if archiveCompressFlag != "" {
- found = false
- for _, algo := range []string{".tar", ".tar.gz", ".tgz", ".zip"} {
- if strings.HasSuffix(archiveCompressFlag, algo) {
- out.Debug("Using %s compression", algo)
- found = true
- break
- }
- }
- if !found {
- return fmt.Errorf("'%s' is no valid compress algorithm. Valid algorithms / file endings are '.tar', '.tar.gz', '.zip'",
- archiveCompressFlag)
- }
- }
-
- switch archiveResolutionFlag {
- case "1080p", "720p", "480p", "360p", "240p":
- intRes, _ := strconv.ParseFloat(strings.TrimSuffix(archiveResolutionFlag, "p"), 84)
- archiveResolutionFlag = fmt.Sprintf("%dx%s", int(intRes*(16/9)), strings.TrimSuffix(archiveResolutionFlag, "p"))
- case "1920x1080", "1280x720", "640x480", "480x360", "428x240", "best", "worst":
- default:
- return fmt.Errorf("'%s' is not a valid resolution", archiveResolutionFlag)
- }
- out.Debug("Using resolution '%s'", archiveResolutionFlag)
-
- return nil
- },
- RunE: func(cmd *cobra.Command, args []string) error {
- loadCrunchy()
-
- return archive(args)
- },
-}
-
-func init() {
- archiveCmd.Flags().StringSliceVarP(&archiveLanguagesFlag,
- "language",
- "l",
- []string{string(systemLocale(false)), string(crunchyroll.JP)},
- "Audio locale which should be downloaded. Can be used multiple times")
-
- cwd, _ := os.Getwd()
- archiveCmd.Flags().StringVarP(&archiveDirectoryFlag,
- "directory",
- "d",
- cwd,
- "The directory to store the files into")
- archiveCmd.Flags().StringVarP(&archiveOutputFlag,
- "output",
- "o",
- "{title}.mkv",
- "Name of the output file. If you use the following things in the name, the will get replaced:\n"+
- "\t{title} » Title of the video\n"+
- "\t{series_name} » Name of the series\n"+
- "\t{season_name} » Name of the season\n"+
- "\t{season_number} » Number of the season\n"+
- "\t{episode_number} » Number of the episode\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")
-
- archiveCmd.Flags().StringVarP(&archiveMergeFlag,
- "merge",
- "m",
- "auto",
- "Sets the behavior of the stream merging. Valid behaviors are 'auto', 'audio', 'video'")
-
- archiveCmd.Flags().StringVarP(&archiveCompressFlag,
- "compress",
- "c",
- "",
- "If is set, all output will be compresses into an archive (every url generates a new one). "+
- "This flag sets the name of the compressed output file. The file ending specifies the compression algorithm. "+
- "The following algorithms are supported: gzip, tar, zip")
-
- archiveCmd.Flags().StringVarP(&archiveResolutionFlag,
- "resolution",
- "r",
- "best",
- "The video resolution. Can either be specified via the pixels, the abbreviation for pixels, or 'common-use' words\n"+
- "\tAvailable pixels: 1920x1080, 1280x720, 640x480, 480x360, 428x240\n"+
- "\tAvailable abbreviations: 1080p, 720p, 480p, 360p, 240p\n"+
- "\tAvailable common-use words: best (best available resolution), worst (worst available resolution)")
-
- archiveCmd.Flags().IntVarP(&archiveGoroutinesFlag,
- "goroutines",
- "g",
- runtime.NumCPU(),
- "Number of parallel segment downloads")
-
- rootCmd.AddCommand(archiveCmd)
-}
-
-func archive(urls []string) error {
- for i, url := range urls {
- out.SetProgress("Parsing url %d", i+1)
- episodes, err := archiveExtractEpisodes(url)
- if err != nil {
- out.StopProgress("Failed to parse url %d", i+1)
- return err
- }
- out.StopProgress("Parsed url %d", i+1)
-
- var compressFile *os.File
- var c compress
-
- if archiveCompressFlag != "" {
- compressFile, err = os.Create(generateFilename(archiveCompressFlag, ""))
- if err != nil {
- return fmt.Errorf("failed to create archive file: %v", err)
- }
- if strings.HasSuffix(archiveCompressFlag, ".tar") {
- c = newTarCompress(compressFile)
- } else if strings.HasSuffix(archiveCompressFlag, ".tar.gz") || strings.HasSuffix(archiveCompressFlag, ".tgz") {
- c = newGzipCompress(compressFile)
- } else if strings.HasSuffix(archiveCompressFlag, ".zip") {
- c = newZipCompress(compressFile)
- }
- }
-
- for _, season := range episodes {
- out.Info("%s Season %d", season[0].SeriesName, season[0].SeasonNumber)
-
- for j, info := range season {
- out.Info("\t%d. %s » %spx, %.2f FPS (S%02dE%02d)",
- j+1,
- info.Title,
- info.Resolution,
- info.FPS,
- info.SeasonNumber,
- info.EpisodeNumber)
- }
- }
- out.Empty()
-
- for _, season := range episodes {
- for _, info := range season {
- var filename string
- var writeCloser io.WriteCloser
- if c != nil {
- filename = info.Format(archiveOutputFlag)
- writeCloser, err = c.NewFile(info)
- if err != nil {
- return fmt.Errorf("failed to pre generate new archive file: %v", err)
- }
- } else {
- dir := info.Format(downloadDirectoryFlag)
- if _, err = os.Stat(dir); os.IsNotExist(err) {
- if err = os.MkdirAll(dir, 0777); err != nil {
- return fmt.Errorf("error while creating directory: %v", err)
- }
- }
- filename = generateFilename(info.Format(archiveOutputFlag), dir)
- writeCloser, err = os.Create(filename)
- if err != nil {
- return fmt.Errorf("failed to create new file: %v", err)
- }
- }
-
- if err = archiveInfo(info, writeCloser, filename); err != nil {
- writeCloser.Close()
- if f, ok := writeCloser.(*os.File); ok {
- os.Remove(f.Name())
- } else {
- c.Close()
- compressFile.Close()
- os.RemoveAll(compressFile.Name())
- }
- return err
- }
-
- writeCloser.Close()
- }
- }
- if c != nil {
- c.Close()
- }
- if compressFile != nil {
- compressFile.Close()
- }
- }
- return nil
-}
-
-func archiveInfo(info formatInformation, writeCloser io.WriteCloser, filename string) error {
- out.Debug("Entering season %d, episode %d with %d additional formats", info.SeasonNumber, info.EpisodeNumber, len(info.additionalFormats))
-
- downloadProgress, err := createArchiveProgress(info)
- if err != nil {
- return fmt.Errorf("error while setting up downloader: %v", err)
- }
- defer func() {
- if downloadProgress.Total != downloadProgress.Current {
- fmt.Println()
- }
- }()
-
- rootFile, err := os.CreateTemp("", fmt.Sprintf("%s_*.ts", strings.TrimSuffix(filepath.Base(filename), filepath.Ext(filename))))
- if err != nil {
- return fmt.Errorf("failed to create temp file: %v", err)
- }
- defer os.Remove(rootFile.Name())
- defer rootFile.Close()
-
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- downloader := crunchyroll.NewDownloader(ctx, rootFile, downloadGoroutinesFlag, func(segment *m3u8.MediaSegment, current, total int, file *os.File) error {
- // check if the context was cancelled.
- // must be done in to not print any progress messages if ctrl+c was pressed
- if ctx.Err() != nil {
- return nil
- }
-
- if out.IsDev() {
- downloadProgress.UpdateMessage(fmt.Sprintf("Downloading %d/%d (%.2f%%) » %s", current, total, float32(current)/float32(total)*100, segment.URI), false)
- } else {
- downloadProgress.Update()
- }
-
- if current == total {
- downloadProgress.UpdateMessage("Merging segments", false)
- }
- return nil
- })
-
- sig := make(chan os.Signal, 1)
- signal.Notify(sig, os.Interrupt)
- go func() {
- select {
- case <-sig:
- signal.Stop(sig)
- out.Exit("Exiting... (may take a few seconds)")
- out.Exit("To force exit press ctrl+c (again)")
- cancel()
- // os.Exit(1) is not called since an immediate exit after the cancel function does not let
- // the download process enough time to stop gratefully. A result of this is that the temporary
- // directory where the segments are downloaded to will not be deleted
- case <-ctx.Done():
- // this is just here to end the goroutine and prevent it from running forever without a reason
- }
- }()
- out.Debug("Set up signal catcher")
-
- var additionalDownloaderOpts []string
- var mergeMessage string
- switch archiveMergeFlag {
- case "auto":
- additionalDownloaderOpts = []string{"-vn"}
- for _, format := range info.additionalFormats {
- if format.Video.Bandwidth != info.format.Video.Bandwidth {
- // revoke the changed FFmpegOpts above
- additionalDownloaderOpts = []string{}
- break
- }
- }
- if len(additionalDownloaderOpts) > 0 {
- mergeMessage = "merging audio for additional formats"
- } else {
- mergeMessage = "merging video for additional formats"
- }
- case "audio":
- additionalDownloaderOpts = []string{"-vn"}
- mergeMessage = "merging audio for additional formats"
- case "video":
- mergeMessage = "merging video for additional formats"
- }
-
- out.Info("Downloading episode `%s` to `%s` (%s)", info.Title, filepath.Base(filename), mergeMessage)
- out.Info("\tEpisode: S%02dE%02d", info.SeasonNumber, info.EpisodeNumber)
- out.Info("\tAudio: %s", info.Audio)
- out.Info("\tSubtitle: %s", info.Subtitle)
- out.Info("\tResolution: %spx", info.Resolution)
- out.Info("\tFPS: %.2f", info.FPS)
-
- var videoFiles, audioFiles, subtitleFiles []string
- defer func() {
- for _, f := range append(append(videoFiles, audioFiles...), subtitleFiles...) {
- os.RemoveAll(f)
- }
- }()
-
- var f []string
- if f, err = archiveDownloadVideos(downloader, filepath.Base(filename), true, info.format); err != nil {
- if err != ctx.Err() {
- return fmt.Errorf("error while downloading: %v", err)
- }
- return err
- }
- videoFiles = append(videoFiles, f[0])
-
- if len(additionalDownloaderOpts) == 0 {
- var videos []string
- downloader.FFmpegOpts = additionalDownloaderOpts
- if videos, err = archiveDownloadVideos(downloader, filepath.Base(filename), true, info.additionalFormats...); err != nil {
- return fmt.Errorf("error while downloading additional videos: %v", err)
- }
- downloader.FFmpegOpts = []string{}
- videoFiles = append(videoFiles, videos...)
- } else {
- var audios []string
- if audios, err = archiveDownloadVideos(downloader, filepath.Base(filename), false, info.additionalFormats...); err != nil {
- return fmt.Errorf("error while downloading additional videos: %v", err)
- }
- audioFiles = append(audioFiles, audios...)
- }
-
- sort.Sort(utils.SubtitlesByLocale(info.format.Subtitles))
-
- sortSubtitles, _ := strconv.ParseBool(os.Getenv("SORT_SUBTITLES"))
- if sortSubtitles && len(archiveLanguagesFlag) > 0 {
- // this sort the subtitle locales after the languages which were specified
- // with the `archiveLanguagesFlag` flag
- for _, language := range archiveLanguagesFlag {
- for i, subtitle := range info.format.Subtitles {
- if subtitle.Locale == crunchyroll.LOCALE(language) {
- info.format.Subtitles = append([]*crunchyroll.Subtitle{subtitle}, append(info.format.Subtitles[:i], info.format.Subtitles[i+1:]...)...)
- break
- }
- }
- }
- }
-
- var subtitles []string
- if subtitles, err = archiveDownloadSubtitles(filepath.Base(filename), info.format.Subtitles...); err != nil {
- return fmt.Errorf("error while downloading subtitles: %v", err)
- }
- subtitleFiles = append(subtitleFiles, subtitles...)
-
- if err = archiveFFmpeg(ctx, writeCloser, videoFiles, audioFiles, subtitleFiles); err != nil {
- return fmt.Errorf("failed to merge files: %v", err)
- }
-
- downloadProgress.UpdateMessage("Download finished", false)
-
- signal.Stop(sig)
- out.Debug("Stopped signal catcher")
-
- out.Empty()
- out.Empty()
-
- return nil
-}
-
-func createArchiveProgress(info formatInformation) (*downloadProgress, error) {
- var progressCount int
- if err := info.format.InitVideo(); err != nil {
- return nil, fmt.Errorf("error while initializing a video: %v", err)
- }
- // + number of segments a video has +1 is for merging
- progressCount += int(info.format.Video.Chunklist.Count()) + 1
- for _, f := range info.additionalFormats {
- if f == info.format {
- continue
- }
-
- if err := f.InitVideo(); err != nil {
- return nil, err
- }
- // + number of segments a video has +1 is for merging
- progressCount += int(f.Video.Chunklist.Count()) + 1
- }
-
- downloadProgress := &downloadProgress{
- Prefix: out.InfoLog.Prefix(),
- Message: "Downloading video",
- // number of segments a video +1 is for the success message
- Total: progressCount + 1,
- Dev: out.IsDev(),
- Quiet: out.IsQuiet(),
- }
- if out.IsDev() {
- downloadProgress.Prefix = out.DebugLog.Prefix()
- }
-
- return downloadProgress, nil
-}
-
-func archiveDownloadVideos(downloader crunchyroll.Downloader, filename string, video bool, formats ...*crunchyroll.Format) ([]string, error) {
- var files []string
-
- for _, format := range formats {
- var name string
- if video {
- name = fmt.Sprintf("%s_%s_video_*.ts", filename, format.AudioLocale)
- } else {
- name = fmt.Sprintf("%s_%s_audio_*.aac", filename, format.AudioLocale)
- }
-
- f, err := os.CreateTemp("", name)
- if err != nil {
- return nil, err
- }
- files = append(files, f.Name())
-
- downloader.Writer = f
- if err = format.Download(downloader); err != nil {
- f.Close()
- for _, file := range files {
- os.Remove(file)
- }
- return nil, err
- }
- f.Close()
-
- out.Debug("Downloaded '%s' video", format.AudioLocale)
- }
-
- return files, nil
-}
-
-func archiveDownloadSubtitles(filename string, subtitles ...*crunchyroll.Subtitle) ([]string, error) {
- var files []string
-
- for _, subtitle := range subtitles {
- f, err := os.CreateTemp("", fmt.Sprintf("%s_%s_subtitle_*.ass", filename, subtitle.Locale))
- if err != nil {
- return nil, err
- }
- files = append(files, f.Name())
-
- if err := subtitle.Save(f); err != nil {
- f.Close()
- for _, file := range files {
- os.Remove(file)
- }
- return nil, err
- }
- f.Close()
-
- out.Debug("Downloaded '%s' subtitles", subtitle.Locale)
- }
-
- return files, nil
-}
-
-func archiveFFmpeg(ctx context.Context, dst io.Writer, videoFiles, audioFiles, subtitleFiles []string) error {
- var input, maps, metadata []string
- re := regexp.MustCompile(`(?m)_([a-z]{2}-([A-Z]{2}|[0-9]{3}))_(video|audio|subtitle)`)
-
- for i, video := range videoFiles {
- input = append(input, "-i", video)
- maps = append(maps, "-map", strconv.Itoa(i))
- locale := crunchyroll.LOCALE(re.FindStringSubmatch(video)[1])
- metadata = append(metadata, fmt.Sprintf("-metadata:s:v:%d", i), fmt.Sprintf("language=%s", utils.LocaleLanguage(locale)))
- metadata = append(metadata, fmt.Sprintf("-metadata:s:a:%d", i), fmt.Sprintf("language=%s", utils.LocaleLanguage(locale)))
- }
-
- for i, audio := range audioFiles {
- input = append(input, "-i", audio)
- maps = append(maps, "-map", strconv.Itoa(i+len(videoFiles)))
- locale := crunchyroll.LOCALE(re.FindStringSubmatch(audio)[1])
- metadata = append(metadata, fmt.Sprintf("-metadata:s:a:%d", i), fmt.Sprintf("language=%s", utils.LocaleLanguage(locale)))
- }
-
- for i, subtitle := range subtitleFiles {
- input = append(input, "-i", subtitle)
- maps = append(maps, "-map", strconv.Itoa(i+len(videoFiles)+len(audioFiles)))
- locale := crunchyroll.LOCALE(re.FindStringSubmatch(subtitle)[1])
- metadata = append(metadata, fmt.Sprintf("-metadata:s:s:%d", i), fmt.Sprintf("title=%s", utils.LocaleLanguage(locale)))
- }
-
- commandOptions := []string{"-y"}
- commandOptions = append(commandOptions, input...)
- commandOptions = append(commandOptions, maps...)
- commandOptions = append(commandOptions, metadata...)
- // we have to create a temporary file here because it must be seekable
- // for ffmpeg.
- // ffmpeg could write to dst too, but this would require to re-encode
- // the audio which results in much higher time and resource consumption
- // (0-1 second with the temp file, ~20 seconds with re-encoding on my system)
- file, err := os.CreateTemp("", "")
- if err != nil {
- return err
- }
- file.Close()
- defer os.Remove(file.Name())
-
- commandOptions = append(commandOptions, "-c", "copy", "-f", "matroska", file.Name())
-
- // just a little nicer debug output to copy and paste the ffmpeg for debug reasons
- if out.IsDev() {
- var debugOptions []string
-
- for _, option := range commandOptions {
- if strings.HasPrefix(option, "title=") {
- debugOptions = append(debugOptions, "title=\""+strings.TrimPrefix(option, "title=")+"\"")
- } else if strings.HasPrefix(option, "language=") {
- debugOptions = append(debugOptions, "language=\""+strings.TrimPrefix(option, "language=")+"\"")
- } else if strings.Contains(option, " ") {
- debugOptions = append(debugOptions, "\""+option+"\"")
- } else {
- debugOptions = append(debugOptions, option)
- }
- }
- out.Debug("FFmpeg merge command: ffmpeg %s", strings.Join(debugOptions, " "))
- }
-
- var errBuf bytes.Buffer
- cmd := exec.CommandContext(ctx, "ffmpeg", commandOptions...)
- cmd.Stderr = &errBuf
- if err = cmd.Run(); err != nil {
- return fmt.Errorf(errBuf.String())
- }
-
- file, err = os.Open(file.Name())
- if err != nil {
- return err
- }
- defer file.Close()
-
- _, err = bufio.NewWriter(dst).ReadFrom(file)
- return err
-}
-
-func archiveExtractEpisodes(url string) ([][]formatInformation, error) {
- var hasJapanese bool
- languagesAsLocale := []crunchyroll.LOCALE{crunchyroll.JP}
- for _, language := range archiveLanguagesFlag {
- locale := crunchyroll.LOCALE(language)
- if locale == crunchyroll.JP {
- hasJapanese = true
- } else {
- languagesAsLocale = append(languagesAsLocale, locale)
- }
- }
-
- episodes, err := extractEpisodes(url, languagesAsLocale...)
- if err != nil {
- return nil, err
- }
-
- if !hasJapanese && len(episodes[1:]) == 0 {
- return nil, fmt.Errorf("no episodes found")
- }
-
- for i, eps := range episodes {
- if len(eps) == 0 {
- out.SetProgress("%s has no matching episodes", languagesAsLocale[i])
- } else if len(episodes[0]) > len(eps) {
- out.SetProgress("%s has %d less episodes than existing in japanese (%d)", languagesAsLocale[i], len(episodes[0])-len(eps), len(episodes[0]))
- }
- }
-
- if !hasJapanese {
- episodes = episodes[1:]
- }
-
- eps := make(map[int]map[int]*formatInformation)
- for _, lang := range episodes {
- for _, season := range utils.SortEpisodesBySeason(lang) {
- if _, ok := eps[season[0].SeasonNumber]; !ok {
- eps[season[0].SeasonNumber] = map[int]*formatInformation{}
- }
- for _, episode := range season {
- format, err := episode.GetFormat(archiveResolutionFlag, "", false)
- if err != nil {
- return nil, fmt.Errorf("error while receiving format for %s: %v", episode.Title, err)
- }
-
- if _, ok := eps[episode.SeasonNumber][episode.EpisodeNumber]; !ok {
- eps[episode.SeasonNumber][episode.EpisodeNumber] = &formatInformation{
- format: format,
- additionalFormats: make([]*crunchyroll.Format, 0),
-
- Title: episode.Title,
- SeriesName: episode.SeriesTitle,
- SeasonName: episode.SeasonTitle,
- SeasonNumber: episode.SeasonNumber,
- EpisodeNumber: episode.EpisodeNumber,
- Resolution: format.Video.Resolution,
- FPS: format.Video.FrameRate,
- Audio: format.AudioLocale,
- }
- } else {
- eps[episode.SeasonNumber][episode.EpisodeNumber].additionalFormats = append(eps[episode.SeasonNumber][episode.EpisodeNumber].additionalFormats, format)
- }
- }
- }
- }
-
- var infoFormat [][]formatInformation
- for _, e := range eps {
- var tmpFormatInfo []formatInformation
-
- var keys []int
- for episodeNumber := range e {
- keys = append(keys, episodeNumber)
- }
- sort.Ints(keys)
-
- for _, key := range keys {
- tmpFormatInfo = append(tmpFormatInfo, *e[key])
- }
-
- infoFormat = append(infoFormat, tmpFormatInfo)
- }
-
- return infoFormat, nil
-}
-
-type compress interface {
- io.Closer
-
- NewFile(information formatInformation) (io.WriteCloser, error)
-}
-
-func newGzipCompress(file *os.File) *tarCompress {
- gw := gzip.NewWriter(file)
- return &tarCompress{
- parent: gw,
- dst: tar.NewWriter(gw),
- }
-}
-
-func newTarCompress(file *os.File) *tarCompress {
- return &tarCompress{
- dst: tar.NewWriter(file),
- }
-}
-
-type tarCompress struct {
- compress
-
- wg sync.WaitGroup
-
- parent *gzip.Writer
- dst *tar.Writer
-}
-
-func (tc *tarCompress) Close() error {
- // we have to wait here in case the actual content isn't copied completely into the
- // writer yet
- tc.wg.Wait()
-
- var err, err2 error
- if tc.parent != nil {
- err2 = tc.parent.Close()
- }
- err = tc.dst.Close()
-
- if err != nil && err2 != nil {
- // best way to show double errors at once that i've found
- return fmt.Errorf("%v\n%v", err, err2)
- } else if err == nil && err2 != nil {
- err = err2
- }
-
- return err
-}
-
-func (tc *tarCompress) NewFile(information formatInformation) (io.WriteCloser, error) {
- rp, wp := io.Pipe()
- go func() {
- tc.wg.Add(1)
- defer tc.wg.Done()
- var buf bytes.Buffer
- io.Copy(&buf, rp)
-
- header := &tar.Header{
- Name: filepath.Join(fmt.Sprintf("S%2d", information.SeasonNumber), information.Title),
- ModTime: time.Now(),
- Mode: 0644,
- Typeflag: tar.TypeReg,
- // fun fact: i did not set the size for quiet some time because i thought that it isn't
- // required. well because of this i debugged this part for multiple hours because without
- // proper size information only a tiny amount gets copied into the tar (or zip) writer.
- // this is also the reason why the file content is completely copied into a buffer before
- // writing it to the writer. i could bypass this and save some memory but this requires
- // some rewriting and im nearly at the (planned) finish for version 2 so nah in the future
- // maybe
- Size: int64(buf.Len()),
- }
- tc.dst.WriteHeader(header)
- io.Copy(tc.dst, &buf)
- }()
- return wp, nil
-}
-
-func newZipCompress(file *os.File) *zipCompress {
- return &zipCompress{
- dst: zip.NewWriter(file),
- }
-}
-
-type zipCompress struct {
- compress
-
- wg sync.WaitGroup
-
- dst *zip.Writer
-}
-
-func (zc *zipCompress) Close() error {
- zc.wg.Wait()
- return zc.dst.Close()
-}
-
-func (zc *zipCompress) NewFile(information formatInformation) (io.WriteCloser, error) {
- rp, wp := io.Pipe()
- go func() {
- zc.wg.Add(1)
- defer zc.wg.Done()
-
- var buf bytes.Buffer
- io.Copy(&buf, rp)
-
- header := &zip.FileHeader{
- Name: filepath.Join(fmt.Sprintf("S%2d", information.SeasonNumber), information.Title),
- Modified: time.Now(),
- Method: zip.Deflate,
- UncompressedSize64: uint64(buf.Len()),
- }
- header.SetMode(0644)
-
- hw, _ := zc.dst.CreateHeader(header)
- io.Copy(hw, &buf)
- }()
-
- return wp, nil
-}
diff --git a/cmd/crunchyroll-go/cmd/download.go b/cmd/crunchyroll-go/cmd/download.go
deleted file mode 100644
index bbf9a3e..0000000
--- a/cmd/crunchyroll-go/cmd/download.go
+++ /dev/null
@@ -1,325 +0,0 @@
-package cmd
-
-import (
- "context"
- "fmt"
- "github.com/ByteDream/crunchyroll-go"
- "github.com/ByteDream/crunchyroll-go/utils"
- "github.com/grafov/m3u8"
- "github.com/spf13/cobra"
- "os"
- "os/signal"
- "path/filepath"
- "runtime"
- "sort"
- "strconv"
- "strings"
-)
-
-var (
- downloadAudioFlag string
- downloadSubtitleFlag string
-
- downloadDirectoryFlag string
- downloadOutputFlag string
-
- downloadResolutionFlag string
-
- downloadGoroutinesFlag int
-)
-
-var getCmd = &cobra.Command{
- Use: "download",
- Short: "Download a video",
- Args: cobra.MinimumNArgs(1),
-
- PreRunE: func(cmd *cobra.Command, args []string) error {
- out.Debug("Validating arguments")
-
- if filepath.Ext(downloadOutputFlag) != ".ts" {
- if !hasFFmpeg() {
- return fmt.Errorf("the file ending for the output file (%s) is not `.ts`. "+
- "Install ffmpeg (https://ffmpeg.org/download.html) to use other media file endings (e.g. `.mp4`)", downloadOutputFlag)
- } else {
- out.Debug("Custom file ending '%s' (ffmpeg is installed)", filepath.Ext(downloadOutputFlag))
- }
- }
-
- if !utils.ValidateLocale(crunchyroll.LOCALE(downloadAudioFlag)) {
- return fmt.Errorf("%s is not a valid audio locale. Choose from: %s", downloadAudioFlag, strings.Join(allLocalesAsStrings(), ", "))
- } else if downloadSubtitleFlag != "" && !utils.ValidateLocale(crunchyroll.LOCALE(downloadSubtitleFlag)) {
- return fmt.Errorf("%s is not a valid subtitle locale. Choose from: %s", downloadSubtitleFlag, strings.Join(allLocalesAsStrings(), ", "))
- }
- out.Debug("Locales: audio: %s / subtitle: %s", downloadAudioFlag, downloadSubtitleFlag)
-
- switch downloadResolutionFlag {
- case "1080p", "720p", "480p", "360p", "240p":
- intRes, _ := strconv.ParseFloat(strings.TrimSuffix(downloadResolutionFlag, "p"), 84)
- downloadResolutionFlag = fmt.Sprintf("%dx%s", int(intRes*(16/9)), strings.TrimSuffix(downloadResolutionFlag, "p"))
- case "1920x1080", "1280x720", "640x480", "480x360", "428x240", "best", "worst":
- default:
- return fmt.Errorf("'%s' is not a valid resolution", downloadResolutionFlag)
- }
- out.Debug("Using resolution '%s'", downloadResolutionFlag)
-
- return nil
- },
- RunE: func(cmd *cobra.Command, args []string) error {
- loadCrunchy()
-
- return download(args)
- },
-}
-
-func init() {
- getCmd.Flags().StringVarP(&downloadAudioFlag, "audio",
- "a",
- string(systemLocale(false)),
- "The locale of the audio. Available locales: "+strings.Join(allLocalesAsStrings(), ", "))
- getCmd.Flags().StringVarP(&downloadSubtitleFlag,
- "subtitle",
- "s",
- "",
- "The locale of the subtitle. Available locales: "+strings.Join(allLocalesAsStrings(), ", "))
-
- cwd, _ := os.Getwd()
- getCmd.Flags().StringVarP(&downloadDirectoryFlag,
- "directory",
- "d",
- cwd,
- "The directory to download the file(s) into")
- getCmd.Flags().StringVarP(&downloadOutputFlag,
- "output",
- "o",
- "{title}.ts",
- "Name of the output file. "+
- "If you use the following things in the name, the will get replaced:\n"+
- "\t{title} » Title of the video\n"+
- "\t{series_name} » Name of the series\n"+
- "\t{season_name} » Name of the season\n"+
- "\t{season_number} » Number of the season\n"+
- "\t{episode_number} » Number of the episode\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")
-
- getCmd.Flags().StringVarP(&downloadResolutionFlag,
- "resolution",
- "r",
- "best",
- "The video resolution. Can either be specified via the pixels, the abbreviation for pixels, or 'common-use' words\n"+
- "\tAvailable pixels: 1920x1080, 1280x720, 640x480, 480x360, 428x240\n"+
- "\tAvailable abbreviations: 1080p, 720p, 480p, 360p, 240p\n"+
- "\tAvailable common-use words: best (best available resolution), worst (worst available resolution)")
-
- getCmd.Flags().IntVarP(&downloadGoroutinesFlag,
- "goroutines",
- "g",
- runtime.NumCPU(),
- "Sets how many parallel segment downloads should be used")
-
- rootCmd.AddCommand(getCmd)
-}
-
-func download(urls []string) error {
- for i, url := range urls {
- out.SetProgress("Parsing url %d", i+1)
- episodes, err := downloadExtractEpisodes(url)
- if err != nil {
- out.StopProgress("Failed to parse url %d", i+1)
- return err
- }
- out.StopProgress("Parsed url %d", i+1)
-
- for _, season := range episodes {
- out.Info("%s Season %d", season[0].SeriesName, season[0].SeasonNumber)
-
- for j, info := range season {
- out.Info("\t%d. %s » %spx, %.2f FPS (S%02dE%02d)",
- j+1,
- info.Title,
- info.Resolution,
- info.FPS,
- info.SeasonNumber,
- info.EpisodeNumber)
- }
- }
- out.Empty()
-
- for _, season := range episodes {
- for _, info := range season {
- dir := info.Format(downloadDirectoryFlag)
- if _, err = os.Stat(dir); os.IsNotExist(err) {
- if err = os.MkdirAll(dir, 0777); err != nil {
- return fmt.Errorf("error while creating directory: %v", err)
- }
- }
- file, err := os.Create(generateFilename(info.Format(downloadOutputFlag), dir))
- if err != nil {
- return fmt.Errorf("failed to create output file: %v", err)
- }
-
- if err = downloadInfo(info, file); err != nil {
- file.Close()
- os.Remove(file.Name())
- return err
- }
- file.Close()
- }
- }
- }
- return nil
-}
-
-func downloadInfo(info formatInformation, file *os.File) error {
- out.Debug("Entering season %d, episode %d", info.SeasonNumber, info.EpisodeNumber)
-
- if err := info.format.InitVideo(); err != nil {
- return fmt.Errorf("error while initializing the video: %v", err)
- }
-
- downloadProgress := &downloadProgress{
- Prefix: out.InfoLog.Prefix(),
- Message: "Downloading video",
- // number of segments a video has +2 is for merging and the success message
- Total: int(info.format.Video.Chunklist.Count()) + 2,
- Dev: out.IsDev(),
- Quiet: out.IsQuiet(),
- }
- if out.IsDev() {
- downloadProgress.Prefix = out.DebugLog.Prefix()
- }
- defer func() {
- if downloadProgress.Total != downloadProgress.Current {
- fmt.Println()
- }
- }()
-
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- downloader := crunchyroll.NewDownloader(ctx, file, downloadGoroutinesFlag, func(segment *m3u8.MediaSegment, current, total int, file *os.File) error {
- // check if the context was cancelled.
- // must be done in to not print any progress messages if ctrl+c was pressed
- if ctx.Err() != nil {
- return nil
- }
-
- if out.IsDev() {
- downloadProgress.UpdateMessage(fmt.Sprintf("Downloading %d/%d (%.2f%%) » %s", current, total, float32(current)/float32(total)*100, segment.URI), false)
- } else {
- downloadProgress.Update()
- }
-
- if current == total {
- downloadProgress.UpdateMessage("Merging segments", false)
- }
- return nil
- })
-
- sig := make(chan os.Signal, 1)
- signal.Notify(sig, os.Interrupt)
- go func() {
- select {
- case <-sig:
- signal.Stop(sig)
- out.Exit("Exiting... (may take a few seconds)")
- out.Exit("To force exit press ctrl+c (again)")
- cancel()
- // os.Exit(1) is not called because an immediate exit after the cancel function does not let
- // the download process enough time to stop gratefully. A result of this is that the temporary
- // directory where the segments are downloaded to will not be deleted
- case <-ctx.Done():
- // this is just here to end the goroutine and prevent it from running forever without a reason
- }
- }()
- out.Debug("Set up signal catcher")
-
- out.Info("Downloading episode `%s` to `%s`", info.Title, filepath.Base(file.Name()))
- out.Info("\tEpisode: S%02dE%02d", info.SeasonNumber, info.EpisodeNumber)
- out.Info("\tAudio: %s", info.Audio)
- out.Info("\tSubtitle: %s", info.Subtitle)
- out.Info("\tResolution: %spx", info.Resolution)
- out.Info("\tFPS: %.2f", info.FPS)
- if err := info.format.Download(downloader); err != nil {
- return fmt.Errorf("error while downloading: %v", err)
- }
-
- downloadProgress.UpdateMessage("Download finished", false)
-
- signal.Stop(sig)
- out.Debug("Stopped signal catcher")
-
- out.Empty()
- out.Empty()
-
- return nil
-}
-
-func downloadExtractEpisodes(url string) ([][]formatInformation, error) {
- episodes, err := extractEpisodes(url, crunchyroll.JP, crunchyroll.LOCALE(downloadAudioFlag))
- if err != nil {
- return nil, err
- }
- japanese := episodes[0]
- custom := episodes[1]
-
- sort.Sort(utils.EpisodesByNumber(japanese))
- sort.Sort(utils.EpisodesByNumber(custom))
-
- var errMessages []string
-
- var final []*crunchyroll.Episode
- if len(japanese) == 0 || len(japanese) == len(custom) {
- final = custom
- } else {
- for _, jp := range japanese {
- before := len(final)
- for _, episode := range custom {
- if jp.SeasonNumber == episode.SeasonNumber && jp.EpisodeNumber == episode.EpisodeNumber {
- final = append(final, episode)
- }
- }
- if before == len(final) {
- errMessages = append(errMessages, fmt.Sprintf("%s has no %s audio, using %s as fallback", jp.Title, crunchyroll.LOCALE(downloadAudioFlag), crunchyroll.JP))
- final = append(final, jp)
- }
- }
- }
-
- if len(errMessages) > 10 {
- for _, msg := range errMessages[:10] {
- out.SetProgress(msg)
- }
- out.SetProgress("... and %d more", len(errMessages)-10)
- } else {
- for _, msg := range errMessages {
- out.SetProgress(msg)
- }
- }
-
- var infoFormat [][]formatInformation
- for _, season := range utils.SortEpisodesBySeason(final) {
- tmpFormatInformation := make([]formatInformation, 0)
- for _, episode := range season {
- format, err := episode.GetFormat(downloadResolutionFlag, crunchyroll.LOCALE(downloadSubtitleFlag), true)
- if err != nil {
- return nil, fmt.Errorf("error while receiving format for %s: %v", episode.Title, err)
- }
- tmpFormatInformation = append(tmpFormatInformation, formatInformation{
- format: format,
-
- Title: episode.Title,
- SeriesName: episode.SeriesTitle,
- SeasonName: episode.SeasonTitle,
- SeasonNumber: episode.SeasonNumber,
- EpisodeNumber: episode.EpisodeNumber,
- Resolution: format.Video.Resolution,
- FPS: format.Video.FrameRate,
- Audio: format.AudioLocale,
- })
- }
- infoFormat = append(infoFormat, tmpFormatInformation)
- }
- return infoFormat, nil
-}
diff --git a/cmd/crunchyroll-go/cmd/logger.go b/cmd/crunchyroll-go/cmd/logger.go
deleted file mode 100644
index 83bc214..0000000
--- a/cmd/crunchyroll-go/cmd/logger.go
+++ /dev/null
@@ -1,193 +0,0 @@
-package cmd
-
-import (
- "fmt"
- "io"
- "log"
- "os"
- "runtime"
- "strings"
- "sync"
- "time"
-)
-
-var prefix, progressDown, progressDownFinish string
-
-func initPrefixBecauseWindowsSucksBallsHard() {
- // dear windows user, please change to a good OS, linux in the best case.
- // MICROSHIT DOES NOT GET IT DONE TO SHOW THE SYMBOLS IN THE ELSE CLAUSE
- // CORRECTLY. NOT IN THE CMD NOR POWERSHELL. WHY TF, IT IS ONE OF THE MOST
- // PROFITABLE COMPANIES ON THIS PLANET AND CANNOT SHOW A PROPER UTF-8 SYMBOL
- // IN THEIR OWN PRODUCT WHICH GETS USED MILLION TIMES A DAY
- if runtime.GOOS == "windows" {
- prefix = "=>"
- progressDown = "|"
- progressDownFinish = "->"
- } else {
- prefix = "➞"
- progressDown = "↓"
- progressDownFinish = "↳"
- }
-}
-
-type progress struct {
- message string
- stop bool
-}
-
-type logger struct {
- DebugLog *log.Logger
- InfoLog *log.Logger
- ErrLog *log.Logger
-
- devView bool
-
- progress chan progress
- done chan interface{}
- lock sync.Mutex
-}
-
-func newLogger(debug, info, err bool) *logger {
- initPrefixBecauseWindowsSucksBallsHard()
-
- debugLog, infoLog, errLog := log.New(io.Discard, prefix+" ", 0), log.New(io.Discard, prefix+" ", 0), log.New(io.Discard, prefix+" ", 0)
-
- if debug {
- debugLog.SetOutput(os.Stdout)
- }
- if info {
- infoLog.SetOutput(os.Stdout)
- }
- if err {
- errLog.SetOutput(os.Stderr)
- }
-
- 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) IsDev() bool {
- return l.devView
-}
-
-func (l *logger) IsQuiet() bool {
- return l.DebugLog.Writer() == io.Discard && l.InfoLog.Writer() == io.Discard && l.ErrLog.Writer() == io.Discard
-}
-
-func (l *logger) Debug(format string, v ...interface{}) {
- l.DebugLog.Printf(format, v...)
-}
-
-func (l *logger) Info(format string, v ...interface{}) {
- l.InfoLog.Printf(format, v...)
-}
-
-func (l *logger) Err(format string, v ...interface{}) {
- l.ErrLog.Printf(format, v...)
-}
-
-func (l *logger) Exit(format string, v ...interface{}) {
- fmt.Fprintln(l.ErrLog.Writer(), fmt.Sprintf(format, v...))
-}
-
-func (l *logger) Empty() {
- if !l.devView && l.InfoLog.Writer() != io.Discard {
- fmt.Println("")
- }
-}
-
-func (l *logger) SetProgress(format string, v ...interface{}) {
- if out.InfoLog.Writer() == io.Discard {
- return
- } else if l.devView {
- l.Debug(format, v...)
- return
- }
-
- initialMessage := fmt.Sprintf(format, v...)
-
- p := progress{
- message: initialMessage,
- }
-
- l.lock.Lock()
- if l.done != nil {
- l.progress <- p
- return
- } else {
- l.progress = make(chan progress, 1)
- l.progress <- p
- l.done = make(chan interface{})
- }
-
- go func() {
- states := []string{"-", "\\", "|", "/"}
-
- var count int
-
- for i := 0; ; i++ {
- select {
- case p := <-l.progress:
- if p.stop {
- fmt.Printf("\r" + strings.Repeat(" ", len(prefix)+len(initialMessage)))
- if count > 1 {
- fmt.Printf("\r%s %s\n", progressDownFinish, p.message)
- } else {
- fmt.Printf("\r%s %s\n", prefix, p.message)
- }
-
- if l.done != nil {
- l.done <- nil
- }
- l.progress = nil
-
- l.lock.Unlock()
- return
- } else {
- if count > 0 {
- fmt.Printf("\r%s %s\n", progressDown, p.message)
- }
- l.progress = make(chan progress, 1)
-
- count++
-
- fmt.Printf("\r%s %s", states[i/10%4], initialMessage)
- l.lock.Unlock()
- }
- default:
- if i%10 == 0 {
- fmt.Printf("\r%s %s", states[i/10%4], initialMessage)
- }
- time.Sleep(35 * time.Millisecond)
- }
- }
- }()
-}
-
-func (l *logger) StopProgress(format string, v ...interface{}) {
- if out.InfoLog.Writer() == io.Discard {
- return
- } else if l.devView {
- l.Debug(format, v...)
- return
- }
-
- l.lock.Lock()
- l.progress <- progress{
- message: fmt.Sprintf(format, v...),
- stop: true,
- }
- <-l.done
- l.done = nil
-}
diff --git a/cmd/crunchyroll-go/cmd/login.go b/cmd/crunchyroll-go/cmd/login.go
deleted file mode 100644
index 1303516..0000000
--- a/cmd/crunchyroll-go/cmd/login.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package cmd
-
-import (
- "fmt"
- "github.com/ByteDream/crunchyroll-go"
- "github.com/spf13/cobra"
- "os"
- "os/user"
- "path/filepath"
- "runtime"
-)
-
-var (
- loginPersistentFlag bool
-
- loginSessionIDFlag bool
-)
-
-var loginCmd = &cobra.Command{
- Use: "login",
- Short: "Login to crunchyroll",
- Args: cobra.RangeArgs(1, 2),
-
- Run: func(cmd *cobra.Command, args []string) {
- if loginSessionIDFlag {
- loginSessionID(args[0])
- } else {
- loginCredentials(args[0], args[1])
- }
- },
-}
-
-func init() {
- loginCmd.Flags().BoolVar(&loginPersistentFlag,
- "persistent",
- false,
- "If the given credential should be stored persistent")
-
- loginCmd.Flags().BoolVar(&loginSessionIDFlag,
- "session-id",
- false,
- "Use a session id to login instead of username and password")
-
- rootCmd.AddCommand(loginCmd)
-}
-
-func loginCredentials(user, password string) error {
- out.Debug("Logging in via credentials")
- if _, err := crunchyroll.LoginWithCredentials(user, password, systemLocale(false), client); err != nil {
- out.Err(err.Error())
- os.Exit(1)
- }
-
- return os.WriteFile(loginStorePath(), []byte(fmt.Sprintf("%s\n%s", user, password)), 0600)
-}
-
-func loginSessionID(sessionID string) error {
- out.Debug("Logging in via session id")
- if _, err := crunchyroll.LoginWithSessionID(sessionID, systemLocale(false), client); err != nil {
- out.Err(err.Error())
- os.Exit(1)
- }
-
- return os.WriteFile(loginStorePath(), []byte(sessionID), 0600)
-}
-
-func loginStorePath() string {
- path := filepath.Join(os.TempDir(), ".crunchy")
- if loginPersistentFlag {
- if runtime.GOOS != "windows" {
- usr, _ := user.Current()
- path = filepath.Join(usr.HomeDir, ".config/crunchy")
- }
-
- out.Info("The login information will be stored permanently UNENCRYPTED on your drive (%s)", path)
- } else if runtime.GOOS != "windows" {
- out.Info("Due to security reasons, you have to login again on the next reboot")
- }
-
- return path
-}
diff --git a/cmd/crunchyroll-go/cmd/root.go b/cmd/crunchyroll-go/cmd/root.go
deleted file mode 100644
index 25c8270..0000000
--- a/cmd/crunchyroll-go/cmd/root.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package cmd
-
-import (
- "context"
- "github.com/ByteDream/crunchyroll-go"
- "github.com/spf13/cobra"
- "net/http"
- "os"
- "runtime/debug"
- "strings"
-)
-
-var (
- client *http.Client
- crunchy *crunchyroll.Crunchyroll
- out = newLogger(false, true, true)
-
- quietFlag bool
- verboseFlag bool
- proxyFlag string
-)
-
-var rootCmd = &cobra.Command{
- Use: "crunchyroll",
- Short: "Download crunchyroll videos with ease. See the wiki for details about the cli and library: https://github.com/ByteDream/crunchyroll-go/wiki",
-
- SilenceErrors: true,
- SilenceUsage: true,
-
- PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
- if verboseFlag {
- out = newLogger(true, true, true)
- } else if quietFlag {
- out = newLogger(false, false, false)
- }
-
- out.DebugLog.Printf("Executing `%s` command with %d arg(s)\n", cmd.Name(), len(args))
-
- 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")
-}
-
-func Execute() {
- rootCmd.CompletionOptions.DisableDefaultCmd = true
- defer func() {
- if r := recover(); r != nil {
- if out.IsDev() {
- out.Err("%v: %s", r, debug.Stack())
- } else {
- out.Err("Unexpected error: %v", r)
- }
- os.Exit(1)
- }
- }()
- if err := rootCmd.Execute(); err != nil {
- if !strings.HasSuffix(err.Error(), context.Canceled.Error()) {
- out.Exit("An error occurred: %v", err)
- }
- os.Exit(1)
- }
-}
diff --git a/cmd/crunchyroll-go/cmd/utils.go b/cmd/crunchyroll-go/cmd/utils.go
deleted file mode 100644
index b4afb73..0000000
--- a/cmd/crunchyroll-go/cmd/utils.go
+++ /dev/null
@@ -1,407 +0,0 @@
-package cmd
-
-import (
- "fmt"
- "github.com/ByteDream/crunchyroll-go"
- "github.com/ByteDream/crunchyroll-go/utils"
- "net/http"
- "net/url"
- "os"
- "os/exec"
- "os/user"
- "path/filepath"
- "reflect"
- "regexp"
- "runtime"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
-)
-
-var (
- // ahh i love windows :)))
- invalidWindowsChars = []string{"\\", "<", ">", ":", "\"", "/", "|", "?", "*"}
- invalidNotWindowsChars = []string{"/"}
-)
-
-var urlFilter = regexp.MustCompile(`(S(\d+))?(E(\d+))?((-)(S(\d+))?(E(\d+))?)?(,|$)`)
-
-// systemLocale receives the system locale
-// https://stackoverflow.com/questions/51829386/golang-get-system-language/51831590#51831590
-func systemLocale(verbose bool) crunchyroll.LOCALE {
- if runtime.GOOS != "windows" {
- if lang, ok := os.LookupEnv("LANG"); ok {
- prefix := strings.Split(lang, "_")[0]
- suffix := strings.Split(strings.Split(lang, ".")[0], "_")[1]
- l := crunchyroll.LOCALE(fmt.Sprintf("%s-%s", prefix, suffix))
- if !utils.ValidateLocale(l) {
- if verbose {
- out.Err("%s is not a supported locale, using %s as fallback", l, crunchyroll.US)
- }
- l = crunchyroll.US
- }
- return l
- }
- } else {
- cmd := exec.Command("powershell", "Get-Culture | select -exp Name")
- if output, err := cmd.Output(); err == nil {
- l := crunchyroll.LOCALE(strings.Trim(string(output), "\r\n"))
- if !utils.ValidateLocale(l) {
- if verbose {
- out.Err("%s is not a supported locale, using %s as fallback", l, crunchyroll.US)
- }
- l = crunchyroll.US
- }
- return l
- }
- }
- if verbose {
- out.Err("Failed to get locale, using %s", crunchyroll.US)
- }
- return crunchyroll.US
-}
-
-func allLocalesAsStrings() (locales []string) {
- for _, locale := range utils.AllLocales {
- locales = append(locales, string(locale))
- }
- sort.Strings(locales)
- return
-}
-
-func createOrDefaultClient(proxy string) (*http.Client, error) {
- if proxy == "" {
- return http.DefaultClient, nil
- } else {
- out.Info("Using custom proxy %s", 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 freeFileName(filename string) (string, bool) {
- ext := filepath.Ext(filename)
- base := strings.TrimSuffix(filename, ext)
- // checks if a .tar stands before the "actual" file ending
- if extraExt := filepath.Ext(base); extraExt == ".tar" {
- ext = extraExt + ext
- base = strings.TrimSuffix(base, extraExt)
- }
- j := 0
- for ; ; j++ {
- if _, stat := os.Stat(filename); stat != nil && !os.IsExist(stat) {
- break
- }
- filename = fmt.Sprintf("%s (%d)%s", base, j+1, ext)
- }
- return filename, j != 0
-}
-
-func loadCrunchy() {
- out.SetProgress("Logging in")
-
- files := []string{filepath.Join(os.TempDir(), ".crunchy")}
-
- if runtime.GOOS != "windows" {
- usr, _ := user.Current()
- files = append(files, filepath.Join(usr.HomeDir, ".config/crunchy"))
- }
-
- var body []byte
- var err error
- for _, file := range files {
- if _, err = os.Stat(file); os.IsNotExist(err) {
- continue
- }
- body, err = os.ReadFile(file)
- break
- }
- if body == nil {
- out.StopProgress("To use this command, login first. Type `%s login -h` to get help", os.Args[0])
- os.Exit(1)
- } else if err != nil {
- out.StopProgress("Failed to read login information: %v", err)
- os.Exit(1)
- }
-
- split := strings.SplitN(string(body), "\n", 2)
- if len(split) == 1 || split[1] == "" {
- if crunchy, err = crunchyroll.LoginWithSessionID(split[0], systemLocale(true), client); err != nil {
- out.StopProgress(err.Error())
- os.Exit(1)
- }
- out.Debug("Logged in with session id %s. BLANK THIS LINE OUT IF YOU'RE ASKED TO POST THE DEBUG OUTPUT SOMEWHERE", split[0])
- } else {
- if crunchy, err = crunchyroll.LoginWithCredentials(split[0], split[1], systemLocale(true), client); err != nil {
- out.StopProgress(err.Error())
- os.Exit(1)
- }
- out.Debug("Logged in with username '%s' and password '%s'. BLANK THIS LINE OUT IF YOU'RE ASKED TO POST THE DEBUG OUTPUT SOMEWHERE", split[0], split[1])
- }
-
- out.StopProgress("Logged in")
-}
-
-func hasFFmpeg() bool {
- return exec.Command("ffmpeg", "-h").Run() == nil
-}
-
-func terminalWidth() int {
- if runtime.GOOS != "windows" {
- cmd := exec.Command("stty", "size")
- cmd.Stdin = os.Stdin
- res, err := cmd.Output()
- if err != nil {
- return 60
- }
- // on alpine linux the command `stty size` does not respond the terminal size
- // but something like "stty: standard input". this may also apply to other systems
- splitOutput := strings.SplitN(strings.ReplaceAll(string(res), "\n", ""), " ", 2)
- if len(splitOutput) == 1 {
- return 60
- }
- width, err := strconv.Atoi(splitOutput[1])
- if err != nil {
- return 60
- }
- return width
- }
- return 60
-}
-
-func generateFilename(name, directory string) string {
- if runtime.GOOS != "windows" {
- for _, char := range invalidNotWindowsChars {
- name = strings.ReplaceAll(name, char, "")
- }
- out.Debug("Replaced invalid characters (not windows)")
- } else {
- for _, char := range invalidWindowsChars {
- name = strings.ReplaceAll(name, char, "")
- }
- out.Debug("Replaced invalid characters (windows)")
- }
-
- filename, changed := freeFileName(filepath.Join(directory, name))
- if changed {
- out.Debug("File `%s` already exists, changing name to `%s`", filepath.Base(name), filepath.Base(filename))
- }
-
- return filename
-}
-
-func extractEpisodes(url string, locales ...crunchyroll.LOCALE) ([][]*crunchyroll.Episode, error) {
- var matches [][]string
-
- lastOpen := strings.LastIndex(url, "[")
- if strings.HasSuffix(url, "]") && lastOpen != -1 && lastOpen < len(url) {
- matches = urlFilter.FindAllStringSubmatch(url[lastOpen+1:len(url)-1], -1)
-
- var all string
- for _, match := range matches {
- all += match[0]
- }
- if all != url[lastOpen+1:len(url)-1] {
- return nil, fmt.Errorf("invalid episode filter")
- }
- url = url[:lastOpen]
- }
-
- final := make([][]*crunchyroll.Episode, len(locales))
- episodes, err := crunchy.ExtractEpisodesFromUrl(url, locales...)
- if err != nil {
- return nil, fmt.Errorf("failed to get episodes: %v", err)
- }
-
- if len(episodes) == 0 {
- return nil, fmt.Errorf("no episodes found")
- }
-
- if matches != nil {
- for _, match := range matches {
- fromSeason, fromEpisode, toSeason, toEpisode := -1, -1, -1, -1
- if match[2] != "" {
- fromSeason, _ = strconv.Atoi(match[2])
- }
- if match[4] != "" {
- fromEpisode, _ = strconv.Atoi(match[4])
- }
- if match[8] != "" {
- toSeason, _ = strconv.Atoi(match[8])
- }
- if match[10] != "" {
- toEpisode, _ = strconv.Atoi(match[10])
- }
-
- if match[6] != "-" {
- toSeason = fromSeason
- toEpisode = fromEpisode
- }
-
- tmpEps := make([]*crunchyroll.Episode, 0)
- for _, episode := range episodes {
- if fromSeason != -1 && (episode.SeasonNumber < fromSeason || (fromEpisode != -1 && episode.EpisodeNumber < fromEpisode)) {
- continue
- } else if fromSeason == -1 && fromEpisode != -1 && episode.EpisodeNumber < fromEpisode {
- continue
- } else if toSeason != -1 && (episode.SeasonNumber > toSeason || (toEpisode != -1 && episode.EpisodeNumber > toEpisode)) {
- continue
- } else if toSeason == -1 && toEpisode != -1 && episode.EpisodeNumber > toEpisode {
- continue
- } else {
- tmpEps = append(tmpEps, episode)
- }
- }
-
- if len(tmpEps) == 0 {
- return nil, fmt.Errorf("no episodes are matching the given filter")
- }
-
- episodes = tmpEps
- }
- }
-
- localeSorted, err := utils.SortEpisodesByAudio(episodes)
- if err != nil {
- return nil, fmt.Errorf("failed to get audio locale: %v", err)
- }
- for i, locale := range locales {
- final[i] = append(final[i], localeSorted[locale]...)
- }
-
- return final, nil
-}
-
-type formatInformation struct {
- // the format to download
- format *crunchyroll.Format
-
- // additional formats which are only used by archive.go
- additionalFormats []*crunchyroll.Format
-
- Title string `json:"title"`
- SeriesName string `json:"series_name"`
- SeasonName string `json:"season_name"`
- SeasonNumber int `json:"season_number"`
- EpisodeNumber int `json:"episode_number"`
- Resolution string `json:"resolution"`
- FPS float64 `json:"fps"`
- Audio crunchyroll.LOCALE `json:"audio"`
- Subtitle crunchyroll.LOCALE `json:"subtitle"`
-}
-
-func (fi formatInformation) Format(source string) string {
- fields := reflect.TypeOf(fi)
- values := reflect.ValueOf(fi)
-
- for i := 0; i < fields.NumField(); i++ {
- var valueAsString string
- switch value := values.Field(i); value.Kind() {
- case reflect.String:
- valueAsString = value.String()
- case reflect.Int:
- valueAsString = fmt.Sprintf("%02d", value.Int())
- case reflect.Float64:
- valueAsString = fmt.Sprintf("%.2f", value.Float())
- case reflect.Bool:
- valueAsString = fields.Field(i).Tag.Get("json")
- if !value.Bool() {
- valueAsString = "no " + valueAsString
- }
- }
-
- if runtime.GOOS != "windows" {
- for _, char := range invalidNotWindowsChars {
- valueAsString = strings.ReplaceAll(valueAsString, char, "")
- }
- out.Debug("Replaced invalid characters (not windows)")
- } else {
- for _, char := range invalidWindowsChars {
- valueAsString = strings.ReplaceAll(valueAsString, char, "")
- }
- out.Debug("Replaced invalid characters (windows)")
- }
-
- source = strings.ReplaceAll(source, "{"+fields.Field(i).Tag.Get("json")+"}", valueAsString)
- }
-
- return source
-}
-
-type downloadProgress struct {
- Prefix string
- Message string
-
- Total int
- Current int
-
- Dev bool
- Quiet bool
-
- lock sync.Mutex
-}
-
-func (dp *downloadProgress) Update() {
- dp.update("", false)
-}
-
-func (dp *downloadProgress) UpdateMessage(msg string, permanent bool) {
- dp.update(msg, permanent)
-}
-
-func (dp *downloadProgress) update(msg string, permanent bool) {
- if dp.Quiet {
- return
- }
-
- if dp.Current >= dp.Total {
- return
- }
-
- dp.lock.Lock()
- defer dp.lock.Unlock()
- dp.Current++
-
- if msg == "" {
- msg = dp.Message
- }
- if permanent {
- dp.Message = msg
- }
-
- if dp.Dev {
- fmt.Printf("%s%s\n", dp.Prefix, msg)
- return
- }
-
- percentage := float32(dp.Current) / float32(dp.Total) * 100
-
- pre := fmt.Sprintf("%s%s [", dp.Prefix, msg)
- post := fmt.Sprintf("]%4d%% %8d/%d", int(percentage), dp.Current, dp.Total)
-
- // i don't really know why +2 is needed here but without it the Printf below would not print to the line end
- progressWidth := terminalWidth() - len(pre) - len(post) + 2
- repeatCount := int(percentage / float32(100) * float32(progressWidth))
- // it can be lower than zero when the terminal is very tiny
- if repeatCount < 0 {
- repeatCount = 0
- }
- progressPercentage := strings.Repeat("=", repeatCount)
- if dp.Current != dp.Total {
- progressPercentage += ">"
- }
-
- fmt.Printf("\r%s%-"+fmt.Sprint(progressWidth)+"s%s", pre, progressPercentage, post)
-}
diff --git a/cmd/crunchyroll-go/main.go b/cmd/crunchyroll-go/main.go
deleted file mode 100644
index efc6a1e..0000000
--- a/cmd/crunchyroll-go/main.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package main
-
-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