├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── pull_request_template.md └── workflows │ ├── release.yml │ └── rust.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── SECURITY.md └── src ├── cli.rs ├── download.rs ├── errors.rs └── main.rs /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | 4 | 5 | ## Breaking Changes 6 | 7 | 8 | 9 | ## Notes & open questions 10 | 11 | 12 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | push: 8 | tags: 9 | - v[0-9]+.* 10 | 11 | jobs: 12 | create-release: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: taiki-e/create-gh-release-action@v1 17 | with: 18 | # (required) GitHub token for creating GitHub Releases. 19 | token: ${{ secrets.GITHUB_TOKEN }} 20 | 21 | upload-assets: 22 | needs: create-release 23 | strategy: 24 | matrix: 25 | include: 26 | - target: aarch64-unknown-linux-gnu 27 | os: ubuntu-latest 28 | - target: x86_64-unknown-linux-gnu 29 | os: ubuntu-latest 30 | - target: x86_64-apple-darwin 31 | os: macos-latest 32 | - target: aarch64-apple-darwin 33 | os: macos-latest 34 | - target: x86_64-pc-windows-msvc 35 | os: windows-latest 36 | runs-on: ${{ matrix.os }} 37 | steps: 38 | - uses: actions/checkout@v4 39 | - uses: taiki-e/upload-rust-binary-action@v1 40 | with: 41 | # (required) Comma-separated list of binary names (non-extension portion of filename) to build and upload. 42 | # Note that glob pattern is not supported yet. 43 | bin: cc-downloader 44 | # (optional) Target triple, default is host triple. 45 | # This is optional but it is recommended that this always be set to 46 | # clarify which target you are building for if macOS is included in 47 | # the matrix because GitHub Actions changed the default architecture 48 | # of macos-latest since macos-14. 49 | target: ${{ matrix.target }} 50 | # (optional) Archive name (non-extension portion of filename) to be uploaded. 51 | # [default value: $bin-$target] 52 | # [possible values: the following variables and any string] 53 | # variables: 54 | # - $bin - Binary name (non-extension portion of filename). 55 | # - $target - Target triple. 56 | # - $tag - Tag of this release. 57 | # When multiple binary names are specified, default archive name or $bin variable cannot be used. 58 | archive: $bin-$tag-$target 59 | # (optional) On which platform to distribute the `.tar.gz` file. 60 | # [default value: unix] 61 | # [possible values: all, unix, windows, none] 62 | tar: unix 63 | # (optional) On which platform to distribute the `.zip` file. 64 | # [default value: windows] 65 | # [possible values: all, unix, windows, none] 66 | zip: windows 67 | # (optional) Comma-separated list of additional files to be included to archive. 68 | # Note that glob pattern is not supported yet. 69 | include: LICENSE-APACHE,LICENSE-MIT,README.md 70 | # (optional) Checksums to release with the asset. 71 | checksum: sha512 72 | # (required) GitHub token for uploading assets to GitHub Releases. 73 | token: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ "main", "dev" ] 6 | pull_request: 7 | branches: [ "main", "dev" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v4 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | - name: Run clippy 24 | run: cargo clippy --verbose 25 | 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # General 2 | .DS_Store 3 | .AppleDouble 4 | .LSOverride 5 | 6 | # Icon must end with two \r 7 | Icon 8 | 9 | # Thumbnails 10 | ._* 11 | 12 | # Files that might appear in the root of a volume 13 | .DocumentRevisions-V100 14 | .fseventsd 15 | .Spotlight-V100 16 | .TemporaryItems 17 | .Trashes 18 | .VolumeIcon.icns 19 | .com.apple.timemachine.donotpresent 20 | 21 | # Directories potentially created on remote AFP share 22 | .AppleDB 23 | .AppleDesktop 24 | Network Trash Folder 25 | Temporary Items 26 | .apdisk 27 | 28 | # Generated by Cargo 29 | # will have compiled files and executables 30 | debug/ 31 | target/ 32 | 33 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 34 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 35 | Cargo.lock 36 | 37 | # These are backup files generated by rustfmt 38 | **/*.rs.bk 39 | 40 | # MSVC Windows builds of rustc generate these, which store debugging information 41 | *.pdb 42 | 43 | # Project specific files 44 | test-download 45 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | pedro@commoncrawl.org. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute to cc-downloader? 2 | 3 | [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg)](CODE_OF_CONDUCT.md) 4 | 5 | `cc-downloader` is an open source project, so all contributions and suggestions are welcome. 6 | 7 | You can contribute in many different ways: giving ideas, answering questions, reporting bugs, proposing enhancements, 8 | improving the documentation, fixing bugs,... 9 | 10 | Many thanks in advance to every contributor. 11 | 12 | In order to facilitate healthy, constructive behavior in an open and inclusive community, we all respect and abide by 13 | our [code of conduct](CODE_OF_CONDUCT.md). 14 | 15 | ## How to work on an open Issue? 16 | 17 | You have the list of open Issues at: [https://github.com/commoncrawl/cc-downloader/issues](https://github.com/commoncrawl/cc-downloader/issues) 18 | 19 | Some of them may have the label `help wanted`: that means that any contributor is welcomed! 20 | 21 | If you would like to work on any of the open Issues: 22 | 23 | 1. Make sure it is not already assigned to someone else. You have the assignee (if any) on the top of the right column of the Issue page. 24 | 25 | 2. You can self-assign it by commenting on the Issue page with the keyword: `#self-assign`. 26 | 27 | 3. Work on your self-assigned issue and eventually create a Pull Request. 28 | 29 | ## How to create a Pull Request? 30 | 31 | 1. Fork the [repository](https://github.com/commoncrawl/cc-downloader) by clicking on the 'Fork' button on the repository's page. This creates a copy of the code under your GitHub user account. 32 | 33 | 2. Clone your fork to your local disk, and add the base repository as a remote: 34 | 35 | ```bash 36 | git clone git@github.com:/cc-downloader.git 37 | cd datasets 38 | git remote add upstream git@github.com:commoncrawl/cc-downloader.git 39 | ``` 40 | 41 | 3. Switch to the `dev` branch and then create a new branch to hold your development changes: 42 | 43 | ```bash 44 | git checkout dev 45 | git checkout -b a-descriptive-name-for-my-changes 46 | ``` 47 | 48 | **do not** work on the `main` or `dev` branches. 49 | 50 | 4. Develop the features on your branch. 51 | 52 | 5. Once you're happy with your contribution, add your changed files and make a commit to record your changes locally: 53 | 54 | ```bash 55 | git add -u 56 | git commit 57 | ``` 58 | 59 | It is a good idea to sync your copy of the code with the original 60 | repository regularly. This way you can quickly account for changes: 61 | 62 | ```bash 63 | git fetch upstream 64 | git rebase upstream/dev 65 | ``` 66 | 67 | 6. Once you are satisfied, push the changes to your fork repo using: 68 | 69 | ```bash 70 | git push -u origin a-descriptive-name-for-my-changes 71 | ``` 72 | 73 | Go the webpage of your fork on GitHub. Click on "Pull request" to send your to the project maintainers for review, and select the `dev` branch as the brach you'd like to merge your changes into. 74 | 75 | Thank you for your contribution! 76 | 77 | ## Code of conduct 78 | 79 | This project adheres to the HuggingFace [code of conduct](CODE_OF_CONDUCT.md). 80 | By participating, you are expected to abide by this code. 81 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cc-downloader" 3 | version = "0.6.1" 4 | edition = "2024" 5 | authors = ["Pedro Ortiz Suarez "] 6 | description = "A polite and user-friendly downloader for Common Crawl data." 7 | license = "MIT OR Apache-2.0" 8 | rust-version = "1.85" 9 | readme = "README.md" 10 | homepage = "https://commoncrawl.org" 11 | repository = "https://github.com/commoncrawl/cc-downloader" 12 | documentation = "https://docs.rs/cc-downloader" 13 | 14 | [dependencies] 15 | clap = { version = "4.5.32", features = ["derive"] } 16 | flate2 = "1.1.0" 17 | futures = "0.3.31" 18 | indicatif = "0.17.11" 19 | regex = "1.11.1" 20 | reqwest = { version = "0.12.14", default-features = false, features = [ 21 | "stream", 22 | "rustls-tls", 23 | ] } 24 | reqwest-middleware = "0.4.1" 25 | reqwest-retry = "0.7.0" 26 | tokio = { version = "1.44.1", features = ["full"] } 27 | tokio-util = { version = "0.7.14", features = ["compat"] } 28 | url = "2.5.4" 29 | 30 | [dev-dependencies] 31 | serde = { version = "1.0.219", features = ["derive"] } 32 | reqwest = { version = "0.12.14", default-features = false, features = [ 33 | "stream", 34 | "rustls-tls", 35 | "json", 36 | ] } 37 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2025 Common Crawl Foundation 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Common Crawl Foundation 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CC-Downloader 2 | 3 | This is an experimental polite downloader for Common Crawl data written in `rust`. This tool is intended for use outside of AWS. 4 | 5 | ## Todo 6 | 7 | - [ ] Add Python bindings 8 | - [ ] Add more tests 9 | - [ ] Handle unrecoverable errors 10 | 11 | ## Installation 12 | 13 | You can install `cc-downloader` via our pre-built binaries, or by compiling it from source. 14 | 15 | ### Pre-built binaries 16 | 17 | You can find our pre-built binaries on our [GitHub releases page](https://github.com/commoncrawl/cc-downloader/releases). They are available for `Linux`, `macOS`, and `Windows`, in `x86_64` and `aarch64` architectures (Windows is only supported in `x86_64`). In order to use them please select and download the correct binary for your system. 18 | 19 | ```bash 20 | wget https://github.com/commoncrawl/cc-downloader/releases/download/[VERSION]/cc-downloader-[VERSION]-[ARCH]-[OS].[COMPRESSION-FORMAT] 21 | ``` 22 | 23 | After downloading it, please verify the checksum of the binary. You can find the checksum file in the same location as the binary. The checksum is generated using `sha512sum`. You can verify it by running the following command: 24 | 25 | ```bash 26 | wget https://github.com/commoncrawl/cc-downloader/releases/download/[VERSION]/cc-downloader-[VERSION]-[ARCH]-[OS].sha512 27 | sha512sum -c cc-downloader-[VERSION]-[ARCH]-[OS].sha512 28 | ``` 29 | 30 | If the checksum is valid, which will be indicated by and `OK` message, you can proceed to extract the binary. For `tar.gz` files you can use the following command: 31 | 32 | ```bash 33 | tar -xzf cc-downloader-[VERSION]-[ARCH]-[OS].tar.gz 34 | ``` 35 | 36 | For `zip` files you can use the following command: 37 | 38 | ```bash 39 | unzip cc-downloader-[VERSION]-[ARCH]-[OS].zip 40 | ``` 41 | 42 | This will extract the binary, the licenses and the readme file **in the current folder**. After extracting the binary, you can run it by executing the following command: 43 | 44 | ```bash 45 | ./cc-downloader 46 | ``` 47 | 48 | If you want to use the binary from anywhere, you can move it to a folder in your `PATH`. For more information on how to do this, please refer to the documentation of your operating system. For example, on `Linux` and `macOS` you can move it to `~/.bin`: 49 | 50 | ```bash 51 | mv cc-downloader ~/.bin 52 | ``` 53 | 54 | And then add the following line to your `~/.bashrc` or `~/.zshrc` file: 55 | 56 | ```bash 57 | export PATH=$PATH:~/.bin 58 | ``` 59 | 60 | then run the following command to apply the changes: 61 | 62 | ```bash 63 | source ~/.bashrc 64 | ``` 65 | 66 | or 67 | 68 | ```bash 69 | source ~/.zshrc 70 | ``` 71 | 72 | Then, you can run the binary from anywhere. If you want to update the binary, you can repeat the process and download the new version. Make sure to replace the binary that is stored in the folder that you added to your `PATH`. If you want to remove the binary, you can simply delete from this folder. 73 | 74 | ### Compiling from source 75 | 76 | For this you need to have `rust` installed. You can install `rust` by following the instructions on the [official website](https://www.rust-lang.org/tools/install). 77 | 78 | Or by running the following command: 79 | 80 | ```bash 81 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh 82 | ``` 83 | 84 | Even if you have `rust` a system-wide installation, we recommend the linked installation method. A system-wide installation and a user installation can co-exist without any problems. 85 | 86 | When compiling from source, please make sure you have the latest version of `rust` installed by running the following command: 87 | 88 | ```bash 89 | rustup update 90 | ``` 91 | 92 | Now you can install the `cc-downloader` tool by running the following command: 93 | 94 | ```bash 95 | cargo install cc-downloader 96 | ``` 97 | 98 | ## Usage 99 | 100 | ```text 101 | ➜ cc-downloader -h 102 | A polite and user-friendly downloader for Common Crawl data. 103 | 104 | Usage: cc-downloader [COMMAND] 105 | 106 | Commands: 107 | download-paths Download paths for a given crawl 108 | download Download files from a crawl 109 | help Print this message or the help of the given subcommand(s) 110 | 111 | Options: 112 | -h, --help Print help 113 | -V, --version Print version 114 | 115 | ------ 116 | 117 | ➜ cc-downloader download-paths -h 118 | Download paths for a given crawl 119 | 120 | Usage: cc-downloader download-paths 121 | 122 | Arguments: 123 | Crawl reference, e.g. CC-MAIN-2021-04 or CC-NEWS-2025-01 124 | Data type [possible values: segment, warc, wat, wet, robotstxt, non200responses, cc-index, cc-index-table] 125 | Destination folder 126 | 127 | Options: 128 | -h, --help Print help 129 | ------ 130 | 131 | ➜ cc-downloader download -h 132 | Download files from a crawl 133 | 134 | Usage: cc-downloader download [OPTIONS] 135 | 136 | Arguments: 137 | Path file 138 | Destination folder 139 | 140 | Options: 141 | -f, --files-only Download files without the folder structure. This only works for WARC/WET/WAT files 142 | -n, --numbered Enumerate output files for compatibility with Ungoliant Pipeline. This only works for WET files 143 | -t, --threads Number of threads to use [default: 10] 144 | -r, --retries Maximum number of retries per file [default: 1000] 145 | -p, --progress Print progress 146 | -h, --help Print help 147 | ``` 148 | 149 | ## Number of threads 150 | 151 | The number of threads can be set using the `-t` flag. The default value is 10. It is advised to use the default value to avoid being blocked by the server. If you make too many requests in a short period of time, you will start receiving `403` errors which are unrecoverable and cannot be retried by the downloader. 152 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Only the latest minor version is being supported 6 | 7 | | Version | Supported | 8 | | ------- | ------------------ | 9 | | 0.6.x | :white_check_mark: | 10 | | < 0.6.0 | :x: | 11 | 12 | ## Reporting a Vulnerability 13 | 14 | To report a security vulnerability, please contact: info[at]commoncrawl[dot]org 15 | -------------------------------------------------------------------------------- /src/cli.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | 3 | use clap::{Parser, Subcommand, ValueEnum}; 4 | use regex::Regex; 5 | 6 | #[derive(Parser)] 7 | #[command(version, about, long_about = None)] 8 | pub struct Cli { 9 | #[command(subcommand)] 10 | pub command: Option, 11 | } 12 | 13 | #[derive(Subcommand)] 14 | pub enum Commands { 15 | /// Download paths for a given crawl 16 | DownloadPaths { 17 | /// Crawl reference, e.g. CC-MAIN-2021-04 or CC-NEWS-2025-01 18 | #[arg(value_name = "CRAWL", value_parser = crawl_name_format)] 19 | snapshot: String, 20 | 21 | /// Data type 22 | #[arg(value_name = "SUBSET")] 23 | data_type: DataType, 24 | 25 | /// Destination folder 26 | #[arg(value_name = "DESTINATION")] 27 | dst: PathBuf, 28 | }, 29 | 30 | /// Download files from a crawl 31 | Download { 32 | /// Path file 33 | #[arg(value_name = "PATHS")] 34 | path_file: PathBuf, 35 | 36 | /// Destination folder 37 | #[arg(value_name = "DESTINATION")] 38 | dst: PathBuf, 39 | 40 | /// Download files without the folder structure. This only works for WARC/WET/WAT files 41 | #[arg(short, long)] 42 | files_only: bool, 43 | 44 | ///Enumerate output files for compatibility with Ungoliant Pipeline. This only works for WET files 45 | #[arg(short, long)] 46 | numbered: bool, 47 | 48 | /// Number of threads to use 49 | #[arg(short, long, default_value = "10", value_name = "NUMBER OF THREADS")] 50 | threads: usize, 51 | 52 | /// Maximum number of retries per file 53 | #[arg( 54 | short, 55 | long, 56 | default_value = "1000", 57 | value_name = "MAX RETRIES PER FILE" 58 | )] 59 | retries: usize, 60 | 61 | /// Print progress 62 | #[arg(short, long, action)] 63 | progress: bool, 64 | }, 65 | } 66 | 67 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] 68 | pub enum DataType { 69 | Segment, 70 | Warc, 71 | Wat, 72 | Wet, 73 | Robotstxt, 74 | Non200responses, 75 | CcIndex, 76 | CcIndexTable, 77 | } 78 | 79 | impl DataType { 80 | pub fn as_str(&self) -> &str { 81 | match self { 82 | DataType::Segment => "segment", 83 | DataType::Warc => "warc", 84 | DataType::Wat => "wat", 85 | DataType::Wet => "wet", 86 | DataType::Robotstxt => "robotstxt", 87 | DataType::Non200responses => "non200responses", 88 | DataType::CcIndex => "cc-index", 89 | DataType::CcIndexTable => "cc-index-table", 90 | } 91 | } 92 | } 93 | 94 | fn crawl_name_format(crawl: &str) -> Result { 95 | let main_re = Regex::new(r"^(CC\-MAIN)\-([0-9]{4})\-([0-9]{2})$").unwrap(); 96 | let news_re = Regex::new(r"^(CC\-NEWS)\-([0-9]{4})\-([0-9]{2})$").unwrap(); 97 | 98 | let crawl_ref = crawl.to_uppercase(); 99 | 100 | if !(main_re.is_match(&crawl_ref) || news_re.is_match(&crawl_ref)) { 101 | Err("Please use the CC-MAIN-YYYY-WW or the CC-NEWS-YYYY-MM format.".to_string()) 102 | } else { 103 | Ok(crawl_ref) 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/download.rs: -------------------------------------------------------------------------------- 1 | use flate2::read::GzDecoder; 2 | use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; 3 | use regex::Regex; 4 | use reqwest::{Client, Url, header}; 5 | use reqwest_middleware::{ClientBuilder, ClientWithMiddleware}; 6 | use reqwest_retry::{Jitter, RetryTransientMiddleware, policies::ExponentialBackoff}; 7 | use std::{ 8 | fs::File, 9 | io::{BufRead, BufReader}, 10 | path::{Path, PathBuf}, 11 | process, str, 12 | sync::Arc, 13 | time::Duration, 14 | }; 15 | use tokio::{ 16 | io::{AsyncWriteExt, BufWriter}, 17 | sync::Semaphore, 18 | task::JoinSet, 19 | }; 20 | 21 | use crate::errors::DownloadError; 22 | 23 | const BASE_URL: &str = "https://data.commoncrawl.org/"; 24 | 25 | static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),); 26 | 27 | pub struct DownloadOptions<'a> { 28 | pub snapshot: String, 29 | pub data_type: &'a str, 30 | pub paths: &'a Path, 31 | pub dst: &'a Path, 32 | pub threads: usize, 33 | pub max_retries: usize, 34 | pub numbered: bool, 35 | pub files_only: bool, 36 | pub progress: bool, 37 | } 38 | 39 | pub struct TaskOptions { 40 | pub number: usize, 41 | pub path: String, 42 | pub dst: PathBuf, 43 | pub numbered: bool, 44 | pub files_only: bool, 45 | pub progress: bool, 46 | } 47 | 48 | impl Default for DownloadOptions<'_> { 49 | fn default() -> Self { 50 | DownloadOptions { 51 | snapshot: "".to_string(), 52 | data_type: "", 53 | paths: Path::new(""), 54 | dst: Path::new(""), 55 | threads: 1, 56 | max_retries: 1000, 57 | numbered: false, 58 | files_only: false, 59 | progress: false, 60 | } 61 | } 62 | } 63 | 64 | fn new_client(max_retries: usize) -> Result { 65 | let retry_policy = ExponentialBackoff::builder() 66 | .retry_bounds(Duration::from_secs(1), Duration::from_secs(3600)) 67 | .jitter(Jitter::Bounded) 68 | .base(2) 69 | .build_with_max_retries(u32::try_from(max_retries).unwrap()); 70 | 71 | let client_base = Client::builder().user_agent(APP_USER_AGENT).build()?; 72 | 73 | Ok(ClientBuilder::new(client_base) 74 | .with(RetryTransientMiddleware::new_with_policy(retry_policy)) 75 | .build()) 76 | } 77 | 78 | pub async fn download_paths(mut options: DownloadOptions<'_>) -> Result<(), DownloadError> { 79 | let news_re = Regex::new(r"^(CC\-NEWS)\-([0-9]{4})\-([0-9]{2})$").unwrap(); 80 | 81 | // Check if the snapshot is a news snapshot and reformat it 82 | // The format of the main crawl urls is different from the news crawl urls 83 | // https://data.commoncrawl.org/crawl-data/CC-NEWS/2025/01/warc.paths.gz 84 | // https://data.commoncrawl.org/crawl-data/CC-MAIN-2025-08/warc.paths.gz 85 | let snapshot_original_ref = options.snapshot.clone(); 86 | if news_re.is_match(&options.snapshot) { 87 | let caps = news_re.captures(&options.snapshot).unwrap(); 88 | options.snapshot = format!("{}/{}/{}", &caps[1], &caps[2], &caps[3]); 89 | } 90 | let paths = format!( 91 | "{}crawl-data/{}/{}.paths.gz", 92 | BASE_URL, options.snapshot, options.data_type 93 | ); 94 | println!("Downloading paths from: {}", paths); 95 | let url = Url::parse(&paths)?; 96 | 97 | let client = new_client(options.max_retries)?; 98 | 99 | let filename = url 100 | .path_segments() // Splits into segments of the URL 101 | .and_then(|segments| segments.last()) // Retrieves the last segment 102 | .unwrap_or("file.download"); // Fallback to generic filename 103 | 104 | let resp = client.head(url.as_str()).send().await?; 105 | match resp.status() { 106 | status if status.is_success() => (), 107 | status if status.as_u16() == 404 => { 108 | return Err(format!( 109 | "\n\nThe reference combination you requested:\n\tCRAWL: {}\n\tSUBSET: {}\n\tURL: {}\n\nDoesn't seem to exist or it is currently not accessible.\n\tError code: {} {}", 110 | snapshot_original_ref, options.data_type, url, status.as_str(), status.canonical_reason().unwrap_or("") 111 | ) 112 | .into()); 113 | } 114 | status => { 115 | return Err(format!( 116 | "Couldn't download URL: {}. Error code: {} {}", 117 | url, 118 | status.as_str(), 119 | status.canonical_reason().unwrap_or("") 120 | ) 121 | .into()); 122 | } 123 | } 124 | 125 | let request = client.get(url.as_str()); 126 | 127 | let mut dst = options.dst.to_path_buf(); 128 | 129 | dst.push(filename); 130 | 131 | let outfile = tokio::fs::File::create(dst.clone()).await?; 132 | let mut outfile = BufWriter::new(outfile); 133 | 134 | let mut download = request.send().await?; 135 | 136 | while let Some(chunk) = download.chunk().await? { 137 | outfile.write_all(&chunk).await?; // Write chunk to output file 138 | } 139 | 140 | outfile.flush().await?; 141 | 142 | println!("Downloaded paths to: {}", dst.to_str().unwrap()); 143 | 144 | Ok(()) 145 | } 146 | 147 | // Based on: https://github.com/benkay86/async-applied/blob/master/indicatif-reqwest-tokio/src/bin/indicatif-reqwest-tokio-multi.rs 148 | 149 | async fn download_task( 150 | client: ClientWithMiddleware, 151 | multibar: Arc, 152 | task_options: TaskOptions, 153 | ) -> Result<(), DownloadError> { 154 | // Parse URL into Url type 155 | let url = Url::parse(&task_options.path)?; 156 | 157 | // We need to determine the file size before we download, so we can create a ProgressBar 158 | // A Header request for the CONTENT_LENGTH header gets us the file size 159 | let download_size = { 160 | let resp = client.head(url.as_str()).send().await?; 161 | if resp.status().is_success() { 162 | resp.headers() // Gives us the HeaderMap 163 | .get(header::CONTENT_LENGTH) // Gives us an Option containing the HeaderValue 164 | .and_then(|ct_len| ct_len.to_str().ok()) // Unwraps the Option as &str 165 | .and_then(|ct_len| ct_len.parse().ok()) // Parses the Option as u64 166 | .unwrap_or(0) // Fallback to 0 167 | } else { 168 | // We return an Error if something goes wrong here 169 | return Err( 170 | format!("Couldn't download URL: {}. Error: {:?}", url, resp.status()).into(), 171 | ); 172 | } 173 | }; 174 | 175 | // Parse the filename from the given URL 176 | let filename = if task_options.numbered { 177 | &format!("{}{}", task_options.number, ".txt.gz") 178 | } else if task_options.files_only { 179 | url.path_segments() 180 | .and_then(|segments| segments.last()) 181 | .unwrap_or("file.download") 182 | } else { 183 | url.path().strip_prefix("/").unwrap_or("file.download") 184 | }; 185 | 186 | let mut dst = task_options.dst.clone(); 187 | 188 | dst.push(filename); 189 | 190 | // Here we build the actual Request with a RequestBuilder from the Client 191 | let request = client.get(url.as_str()); 192 | 193 | // Create the ProgressBar with the aquired size from before 194 | // and add it to the multibar 195 | let progress_bar = multibar.add(ProgressBar::new(download_size)); 196 | 197 | if task_options.progress { 198 | // Set Style to the ProgressBar 199 | progress_bar.set_style( 200 | ProgressStyle::default_bar() 201 | .template("[{bar:40.cyan/blue}] {bytes}/{total_bytes} - {msg}")? 202 | .progress_chars("#>-"), 203 | ); 204 | 205 | // Set the filename as message part of the progress bar 206 | progress_bar.set_message(filename.to_owned()); 207 | } else { 208 | println!("Downloading: {}", url.as_str()); 209 | } 210 | 211 | // Create the directory if it doesn't exist 212 | if !task_options.numbered { 213 | if let Some(parent) = dst.parent() { 214 | tokio::fs::create_dir_all(parent).await?; 215 | } 216 | } 217 | 218 | // Create the output file with tokio's async fs lib 219 | let outfile = tokio::fs::File::create(dst.clone()).await?; 220 | let mut outfile = BufWriter::new(outfile); 221 | 222 | // Do the actual request to download the file 223 | let mut download = request.send().await?; 224 | 225 | // Do an asynchronous, buffered copy of the download to the output file. 226 | // 227 | // We use the part from the reqwest-tokio example here on purpose 228 | // This way, we are able to increase the ProgressBar with every downloaded chunk 229 | while let Some(chunk) = download.chunk().await? { 230 | if task_options.progress { 231 | progress_bar.inc(chunk.len() as u64); // Increase ProgressBar by chunk size 232 | } 233 | outfile.write_all(&chunk).await?; // Write chunk to output file 234 | } 235 | 236 | if task_options.progress { 237 | // Finish the progress bar to prevent glitches 238 | progress_bar.finish(); 239 | 240 | // Remove the progress bar from the multibar 241 | multibar.remove(&progress_bar); 242 | } else { 243 | multibar.remove(&progress_bar); 244 | println!("Downloaded file to: {}", dst.to_str().unwrap()); 245 | } 246 | 247 | // Must flush tokio::io::BufWriter manually. 248 | // It will *not* flush itself automatically when dropped. 249 | outfile.flush().await?; 250 | 251 | Ok(()) 252 | } 253 | 254 | pub async fn download(options: DownloadOptions<'_>) -> Result<(), DownloadError> { 255 | // A vector containing all the URLs to download 256 | 257 | let file = { 258 | let gzip_file = match File::open(options.paths) { 259 | Ok(file) => file, 260 | Err(e) => { 261 | eprintln!( 262 | "Could not open file {}\nError: {}", 263 | options.paths.display(), 264 | e 265 | ); 266 | process::exit(1) 267 | } 268 | }; 269 | let file_decoded = GzDecoder::new(gzip_file); 270 | BufReader::new(file_decoded) 271 | }; 272 | 273 | let paths: Vec<(usize, String)> = file 274 | .lines() 275 | .map(|line| { 276 | let line = line.unwrap(); 277 | format!("{}{}", BASE_URL, line) 278 | }) 279 | .enumerate() 280 | .collect(); 281 | 282 | // Set up a new multi-progress bar. 283 | // The bar is stored in an `Arc` to facilitate sharing between threads. 284 | let multibar = std::sync::Arc::new(indicatif::MultiProgress::new()); 285 | 286 | // Add an overall progress indicator to the multibar. 287 | // It has as many steps as the download_links Vector and will increment on completion of each task. 288 | let main_pb = std::sync::Arc::new( 289 | multibar 290 | .clone() 291 | .add(indicatif::ProgressBar::new(paths.len() as u64)), 292 | ); 293 | 294 | // Only set the style if we are showing progress 295 | if options.progress { 296 | main_pb.set_style( 297 | indicatif::ProgressStyle::default_bar().template("{msg} {bar:10} {pos}/{len}")?, 298 | ); 299 | main_pb.set_message("total "); 300 | 301 | // Make the main progress bar render immediately rather than waiting for the 302 | // first task to finish. 303 | main_pb.tick(); 304 | } 305 | 306 | let client = new_client(options.max_retries)?; 307 | 308 | let semaphore = Arc::new(Semaphore::new(options.threads)); 309 | let mut set = JoinSet::new(); 310 | 311 | for (number, path) in paths { 312 | // Clone multibar and main_pb. We will move the clones into each task. 313 | let multibar = multibar.clone(); 314 | let main_pb = main_pb.clone(); 315 | let client = client.clone(); 316 | let dst = options.dst.to_path_buf(); 317 | let semaphore = semaphore.clone(); 318 | set.spawn(async move { 319 | let _permit = semaphore.acquire().await; 320 | let task_options = TaskOptions { 321 | path, 322 | number, 323 | dst, 324 | numbered: options.numbered, 325 | files_only: options.files_only, 326 | progress: options.progress, 327 | }; 328 | let res = download_task(client, multibar, task_options).await; 329 | if options.progress { 330 | // Increment the main progress bar. 331 | main_pb.inc(1); 332 | } 333 | res 334 | }); 335 | } 336 | 337 | // Set up a future to manage rendering of the multiple progress bars. 338 | let multibar = { 339 | // Create a clone of the multibar, which we will move into the task. 340 | let multibar = multibar.clone(); 341 | 342 | // multibar.join() is *not* async and will block until all the progress 343 | // bars are done, therefore we must spawn it on a separate scheduler 344 | // on which blocking behavior is allowed. 345 | tokio::task::spawn_blocking(move || multibar) 346 | }; 347 | 348 | // Wait for the tasks to finish. 349 | while let Some(result) = set.join_next().await { 350 | match result { 351 | Ok(Ok(())) => {} 352 | Ok(Err(e)) => eprintln!("Error: {:?}", e), 353 | Err(e) => eprintln!("Error: {:?}", e), 354 | } 355 | } 356 | 357 | if options.progress { 358 | // Change the message on the overall progress indicator. 359 | main_pb.finish_with_message("done"); 360 | 361 | // Wait for the progress bars to finish rendering. 362 | // The first ? unwraps the outer join() in which we are waiting for the 363 | // future spawned by tokio::task::spawn_blocking to finish. 364 | // The second ? unwraps the inner multibar.join(). 365 | multibar.await?; 366 | } else { 367 | println!("All downloads completed"); 368 | } 369 | Ok(()) 370 | } 371 | 372 | #[cfg(test)] 373 | mod tests { 374 | use super::*; 375 | use serde::Deserialize; 376 | use std::collections::HashMap; 377 | 378 | #[derive(Deserialize, Debug)] 379 | pub struct HeadersEcho { 380 | pub headers: HashMap, 381 | } 382 | 383 | #[test] 384 | fn user_agent_format() { 385 | assert_eq!( 386 | APP_USER_AGENT, 387 | concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),) 388 | ); 389 | } 390 | 391 | #[tokio::test] 392 | async fn user_agent_test() -> Result<(), DownloadError> { 393 | let client = new_client(1000)?; 394 | let response = client.get("http://httpbin.org/headers").send().await?; 395 | 396 | let out: HeadersEcho = response.json().await?; 397 | assert_eq!(out.headers["User-Agent"], APP_USER_AGENT); 398 | Ok(()) 399 | } 400 | } 401 | -------------------------------------------------------------------------------- /src/errors.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | #[derive(Debug)] 4 | pub enum DownloadError { 5 | Reqwest(reqwest::Error), 6 | ReqwestMiddleware(reqwest_middleware::Error), 7 | Tokio(tokio::io::Error), 8 | Url(url::ParseError), 9 | Indicatif(indicatif::style::TemplateError), 10 | Join(tokio::task::JoinError), 11 | Custom(String), 12 | } 13 | 14 | impl fmt::Display for DownloadError { 15 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 16 | match *self { 17 | DownloadError::Reqwest(ref err) => err.fmt(f), 18 | DownloadError::ReqwestMiddleware(ref err) => err.fmt(f), 19 | DownloadError::Tokio(ref err) => err.fmt(f), 20 | DownloadError::Url(ref err) => err.fmt(f), 21 | DownloadError::Indicatif(ref err) => err.fmt(f), 22 | DownloadError::Join(ref err) => err.fmt(f), 23 | DownloadError::Custom(ref err) => err.fmt(f), 24 | } 25 | } 26 | } 27 | 28 | impl From for DownloadError { 29 | fn from(err: reqwest::Error) -> Self { 30 | DownloadError::Reqwest(err) 31 | } 32 | } 33 | 34 | impl From for DownloadError { 35 | fn from(err: reqwest_middleware::Error) -> Self { 36 | DownloadError::ReqwestMiddleware(err) 37 | } 38 | } 39 | 40 | impl From for DownloadError { 41 | fn from(err: tokio::io::Error) -> Self { 42 | DownloadError::Tokio(err) 43 | } 44 | } 45 | 46 | impl From for DownloadError { 47 | fn from(err: url::ParseError) -> Self { 48 | DownloadError::Url(err) 49 | } 50 | } 51 | 52 | impl From for DownloadError { 53 | fn from(err: indicatif::style::TemplateError) -> Self { 54 | DownloadError::Indicatif(err) 55 | } 56 | } 57 | 58 | impl From for DownloadError { 59 | fn from(err: tokio::task::JoinError) -> Self { 60 | DownloadError::Join(err) 61 | } 62 | } 63 | 64 | impl From for DownloadError { 65 | fn from(s: String) -> DownloadError { 66 | DownloadError::Custom(s) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | 3 | use crate::cli::Commands; 4 | 5 | mod cli; 6 | mod download; 7 | mod errors; 8 | 9 | #[tokio::main] 10 | async fn main() { 11 | let cli = cli::Cli::parse(); 12 | 13 | match &cli.command { 14 | Some(Commands::DownloadPaths { 15 | snapshot, 16 | data_type, 17 | dst, 18 | }) => { 19 | let options = download::DownloadOptions { 20 | snapshot: snapshot.to_string(), 21 | data_type: data_type.as_str(), 22 | dst, 23 | ..Default::default() 24 | }; 25 | match download::download_paths(options).await { 26 | Ok(_) => (), 27 | Err(e) => { 28 | eprintln!("Error downloading paths: {}", e); 29 | } 30 | }; 31 | } 32 | Some(Commands::Download { 33 | path_file, 34 | dst, 35 | progress, 36 | threads, 37 | retries, 38 | numbered, 39 | files_only, 40 | }) => { 41 | if *numbered && *files_only { 42 | eprintln!("Numbered and Files Only flags are incompatible"); 43 | } else { 44 | let options = download::DownloadOptions { 45 | paths: path_file, 46 | dst, 47 | progress: *progress, 48 | threads: *threads, 49 | max_retries: *retries, 50 | numbered: *numbered, 51 | files_only: *files_only, 52 | ..Default::default() 53 | }; 54 | match download::download(options).await { 55 | Ok(_) => (), 56 | Err(e) => { 57 | eprintln!("Error downloading paths: {}", e); 58 | } 59 | }; 60 | } 61 | } 62 | None => { 63 | eprintln!("No command specified"); 64 | } 65 | } 66 | } 67 | --------------------------------------------------------------------------------