zenodo-dl 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d251d15d68d4f3069872550e6c2aad92b61040c513c6871435c5756441631012
4
+ data.tar.gz: 21b46ea6c957a1b0028c3cffacac48eeabffd1af25d63768693b0cbee283c8ba
5
+ SHA512:
6
+ metadata.gz: 2d5ac82166e41fc0246e450e0bad2f935d32ed03b9cfe98c6f75a0f547ce98bdbc170f7acb4428fb2f3f0dca49172f60d8a18bb0b890e3c0c4a8cf23b00c50c2
7
+ data.tar.gz: 22368fce8132cc2aec88446167bd0fc6862f3adbe0b63bffd103cfb6c55926e54ac320f430616253d04d7bba22bd44934557e4d10addede7d177e7c2dcaab698
data/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ ## [0.1.0]
2
+
3
+ First version. Per-publication offline archive of Zenodo records, any version, built on [dl-core](https://github.com/xoengineering/dl-core).
4
+
5
+ - Accepts Zenodo record and concept IDs, `10.5281/zenodo` DOIs, and zenodo.org and doi.org URLs.
6
+ - Saves every file in the record, each verified against Zenodo's MD5 checksum, plus Zenodo's record verbatim and four sidecar metadata files. Authors carry their affiliations.
7
+ - Layout: `YYYY/MM/DD/<type>/<concept-id>-<slug>/`, flat for a publication with only v1 archived, `v<N>/` folders otherwise.
8
+ - Archives publications only. Datasets and software raise `Zenodo::Downloader::NotAPublication`. Records that are not open access raise `Zenodo::Downloader::NotAvailable`. A checksum mismatch raises `Zenodo::Downloader::ChecksumMismatch` and leaves nothing behind.
@@ -0,0 +1,83 @@
1
+ # Contributor Covenant 3.0 Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We pledge to make our community welcoming, safe, and equitable for all.
6
+
7
+ We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant.
8
+
9
+ ## Encouraged Behaviors
10
+
11
+ While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language.
12
+
13
+ With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including:
14
+
15
+ 1. Respecting the **purpose of our community**, our activities, and our ways of gathering.
16
+ 2. Engaging **kindly and honestly** with others.
17
+ 3. Respecting **different viewpoints** and experiences.
18
+ 4. **Taking responsibility** for our actions and contributions.
19
+ 5. Gracefully giving and accepting **constructive feedback**.
20
+ 6. Committing to **repairing harm** when it occurs.
21
+ 7. Behaving in other ways that promote and sustain the **well-being of our community**.
22
+
23
+ ## Restricted Behaviors
24
+
25
+ We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct.
26
+
27
+ 1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop.
28
+ 2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people.
29
+ 3. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits.
30
+ 4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community.
31
+ 5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission.
32
+ 6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group.
33
+ 7. Behaving in other ways that **threaten the well-being** of our community.
34
+
35
+ ### Other Restrictions
36
+
37
+ 1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions.
38
+ 2. **Failing to credit sources.** Not properly crediting the sources of content you contribute.
39
+ 3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community.
40
+ 4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors.
41
+
42
+ ## Reporting an Issue
43
+
44
+ Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm.
45
+
46
+ When an incident does occur, it is important to report it promptly. To report a possible violation, **email the maintainer at [veganstraightedge@gmail.com](mailto:veganstraightedge@gmail.com).**
47
+
48
+ Community Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution.
49
+
50
+ ## Addressing and Repairing Harm
51
+
52
+ If an investigation by the Community Moderators finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped.
53
+
54
+ 1. Warning
55
+ 1. Event: A violation involving a single incident or series of incidents.
56
+ 2. Consequence: A private, written warning from the Community Moderators.
57
+ 3. Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations.
58
+ 2. Temporarily Limited Activities
59
+ 1. Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation.
60
+ 2. Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members.
61
+ 3. Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over.
62
+ 3. Temporary Suspension
63
+ 1. Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation.
64
+ 2. Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behavior and possible corrective actions.
65
+ 3. Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted.
66
+ 4. Permanent Ban
67
+ 1. Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member.
68
+ 2. Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behavior.
69
+ 3. Repair: There is no possible repair in cases of this severity.
70
+
71
+ This enforcement ladder is intended as a guideline. It does not limit the ability of Community Managers to use their discretion and judgment, in keeping with the best interests of our community.
72
+
73
+ ## Scope
74
+
75
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
76
+
77
+ ## Attribution
78
+
79
+ This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/).
80
+
81
+ Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/)
82
+
83
+ For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion).
data/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Shane Becker
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,122 @@
1
+ # zenodo-dl
2
+
3
+ Download publications and metadata from [Zenodo](https://zenodo.org) for offline archives.
4
+
5
+ For each publication version, `zenodo-dl` saves:
6
+
7
+ - Every file in the record, each checked against the MD5 checksum Zenodo publishes for it
8
+ - Zenodo's own record (`zenodo.json`), verbatim
9
+ - Four sidecar metadata files: `metadata.md`, `metadata.yaml`, `metadata.json`, `metadata.bib`
10
+
11
+ Any version can be archived, not just the latest.
12
+
13
+ Only records whose resource type is **publication** (articles, preprints, reports, theses, and so on) are archived. Zenodo also hosts datasets and software, often many gigabytes, and `zenodo-dl` refuses those. Only open-access records are archived. Restricted, embargoed, and closed records have no downloadable files.
14
+
15
+ ## Zenodo's terms
16
+
17
+ From Zenodo's [terms of use](https://about.zenodo.org/terms/): access to Zenodo's content is open to all, for non-military purposes only. Users of content shall respect applicable license conditions (`zenodo-dl` records each record's `license`). Zenodo metadata may be reused under CC0 unless specified otherwise. Download and use of content does not transfer any intellectual property rights.
18
+
19
+ Zenodo limits guest API use to 30 search requests a minute. `zenodo-dl`'s default of one request every 3 seconds stays under that.
20
+
21
+ ## Installation
22
+
23
+ ```sh
24
+ gem install zenodo-dl
25
+ ```
26
+
27
+ ## CLI usage
28
+
29
+ ```sh
30
+ zenodo-dl <ZENODO_ID_OR_URL> [<ZENODO_ID_OR_URL>...]
31
+ ```
32
+
33
+ Accepted input forms:
34
+
35
+ | Form | Example |
36
+ | --------------- | ---------------------------------------------------------------- |
37
+ | Record ID | `884117` |
38
+ | DOI | `10.5281/zenodo.884117`, `doi:10.5281/zenodo.884117` |
39
+ | DOI URL | `https://doi.org/10.5281/zenodo.884117` |
40
+ | Record URL | `https://zenodo.org/records/884117`, `https://zenodo.org/record/884117` |
41
+ | File URL | `https://zenodo.org/records/884117/files/<name>` |
42
+ | API URL | `https://zenodo.org/api/records/884117` |
43
+
44
+ A version's record ID archives that version. A concept record ID (the ID for all versions) archives the latest version.
45
+
46
+ ### Flags
47
+
48
+ | Flag | Description |
49
+ | ------------------------- | ----------------------------------------------------------------------------- |
50
+ | `-i FILE`, `--input FILE` | Read IDs/URLs from FILE, one per line (`-` for stdin, blanks and `#` skipped) |
51
+ | `-p PATH`, `--path PATH` | Root download directory |
52
+ | `--rate-limit SECONDS` | Seconds between HTTP requests (`0` disables throttling) |
53
+ | `-v`, `--verbose` | Print step lines and per-request URL/byte logs to stdout |
54
+ | `-q`, `--quiet` | Print nothing to stdout. Errors still go to stderr. |
55
+ | `--version` | Print the gem version and exit |
56
+ | `-h`, `--help` | Print help and exit |
57
+
58
+ `-v` and `-q` are mutually exclusive.
59
+
60
+ ### Environment variables
61
+
62
+ | Variable | Effect |
63
+ | ---------------------- | ------------------------------------------------------------------ |
64
+ | `ZENODO_DOWNLOAD_PATH` | Root download directory (default: `$HOME/Downloads/Zenodo_Papers`) |
65
+ | `ZENODO_RATE_LIMIT` | Seconds between HTTP requests (default: `3`, `0` disables) |
66
+
67
+ Precedence: CLI flag, then ENV var, then default.
68
+
69
+ ### Errors and exit status
70
+
71
+ A target that fails (unrecognized ID, no such record, not a publication, not open access, checksum mismatch, HTTP error, network failure) is reported on stderr as `<target>: <message>`, and the remaining targets still download. Exit status is `0` when every target succeeds and `1` when any fails.
72
+
73
+ ## Output layout
74
+
75
+ ```txt
76
+ $ZENODO_DOWNLOAD_PATH/ # default: $HOME/Downloads/Zenodo_Papers
77
+ YYYY/MM/DD/<type>/<concept-id>-<slug>/
78
+ <file>, <file>, ... # every file in the record
79
+ zenodo.json # Zenodo's record, verbatim
80
+ metadata.md # YAML frontmatter + Markdown body
81
+ metadata.yaml
82
+ metadata.json
83
+ metadata.bib # synthesized @misc with the DOI
84
+ ```
85
+
86
+ `YYYY/MM/DD` is the publication date. `<type>` is the publication type (`preprint`, `article`, `report`, and so on). The folder is keyed on the concept ID, so every version of a publication lands in the same folder. `<slug>` is derived from the title.
87
+
88
+ A publication with only v1 archived is kept flat, as above. When it has more than one version, each version gets its own `v<N>/` folder with the same contents. Archiving a second version of a flat publication first moves the existing files into `v<N>/`. A publication whose latest version is v2 or later starts out in `v<N>/` folders.
89
+
90
+ Each version downloads into a sibling `.partial` folder and is renamed into place only when every file matched its checksum. Re-running skips versions already archived.
91
+
92
+ ## Library usage
93
+
94
+ ```ruby
95
+ require 'zenodo/downloader'
96
+
97
+ identifier = Zenodo::Downloader::Identifier.new 'https://doi.org/10.5281/zenodo.884117'
98
+ client = Zenodo::Downloader::Client.new # 3-second rate limit by default
99
+ path = Zenodo::Downloader::Archive.new(identifier, root: '/tmp/papers', client: client).run
100
+ ```
101
+
102
+ ## Development
103
+
104
+ ```sh
105
+ script/setup # install dependencies
106
+ script/test # run specs and rubocop
107
+ script/console # interactive prompt
108
+ ```
109
+
110
+ Specs run offline against recorded fixtures in `spec/fixtures/http/`. To check the record fixtures against the live Zenodo API, run:
111
+
112
+ ```sh
113
+ ZENODO_LIVE=1 script/test
114
+ ```
115
+
116
+ ## License
117
+
118
+ MIT. See [LICENSE.md](LICENSE.md).
119
+
120
+ ## Code of Conduct
121
+
122
+ This project follows the [Contributor Covenant](https://www.contributor-covenant.org/version/3/0/) 3.0. See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
data/exe/zenodo-dl ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'zenodo/downloader'
4
+
5
+ exit Zenodo::Downloader::CLI.new(ARGV).run
@@ -0,0 +1,99 @@
1
+ require 'digest'
2
+ require 'fileutils'
3
+
4
+ module Zenodo
5
+ module Downloader
6
+ class Archive
7
+ def initialize identifier, root:, client: Client.new
8
+ @identifier = identifier
9
+ @root = root
10
+ @client = client
11
+ end
12
+
13
+ # Downloads into <destination>.partial/ and
14
+ # renames it into place only once every file matched its checksum.
15
+ # An archived version is always complete and is skipped.
16
+ # PaperFolder decides flat (single version) vs v<N>/ (several versions).
17
+ def run
18
+ raise NotAPublication unless parser.publication?
19
+ raise NotAvailable unless parser.downloadable?
20
+ return paper_folder.location_of(metadata.version) if paper_folder.archived? metadata.version
21
+
22
+ paper_folder.unflatten!
23
+ FileUtils.rm_rf staging_dir
24
+ FileUtils.mkdir_p staging_dir
25
+
26
+ download_files
27
+ write_record
28
+ write_sidecars
29
+
30
+ File.rename staging_dir, destination
31
+ destination
32
+ end
33
+
34
+ private
35
+
36
+ # a concept ID resolves to its latest version
37
+ def record
38
+ @record ||= @client.get("https://zenodo.org/api/records/#{@identifier}").to_s
39
+ rescue DL::Core::HTTPError => e
40
+ raise PaperNotFound if e.status == 404
41
+
42
+ raise
43
+ end
44
+
45
+ def parser
46
+ @parser ||= RecordParser.new record
47
+ end
48
+
49
+ def metadata
50
+ @metadata ||= parser.metadata
51
+ end
52
+
53
+ def paper_folder
54
+ @paper_folder ||= DL::Core::PaperFolder.new File.join(@root, Path.new(metadata).to_s)
55
+ end
56
+
57
+ # evaluated after unflatten!, which can turn a flat folder into v<N>/ folders
58
+ def destination
59
+ @destination ||= paper_folder.destination_for metadata.version
60
+ end
61
+
62
+ # a sibling of destination, so the rename is a single atomic step
63
+ def staging_dir
64
+ "#{destination}.partial"
65
+ end
66
+
67
+ # File.basename keeps a name from the record from pointing outside the folder
68
+ def download_files
69
+ parser.files.each do |file|
70
+ body = @client.get(file.url).to_s
71
+ verify file, body
72
+ File.binwrite File.join(staging_dir, File.basename(file.name)), body
73
+ end
74
+ end
75
+
76
+ def verify file, body
77
+ actual = Digest::MD5.hexdigest body
78
+ return if actual == file.md5
79
+
80
+ raise ChecksumMismatch, "#{file.name}: expected MD5 #{file.md5}, got #{actual}"
81
+ end
82
+
83
+ # Zenodo's own record, verbatim
84
+ def write_record
85
+ File.write File.join(staging_dir, 'zenodo.json'), record
86
+ end
87
+
88
+ def write_sidecars
89
+ body = MarkdownBody.new(metadata).to_s
90
+ key = Bibtex.new(metadata).key
91
+
92
+ DL::Core::Sidecar::Markdown.new(metadata, body:, extras: { bibtex_key: key }).write to: staging_dir
93
+ DL::Core::Sidecar::YAML.new(metadata).write to: staging_dir
94
+ DL::Core::Sidecar::JSON.new(metadata).write to: staging_dir
95
+ File.write File.join(staging_dir, 'metadata.bib'), Bibtex.new(metadata).to_s
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,49 @@
1
+ module Zenodo
2
+ module Downloader
3
+ # Synthesized from the record metadata
4
+ class Bibtex
5
+ def initialize metadata
6
+ @metadata = metadata
7
+ end
8
+
9
+ def to_s
10
+ <<~BIBTEX
11
+ @misc{#{key},
12
+ title={#{@metadata.title}},
13
+ author={#{authors}},
14
+ year={#{year}},
15
+ publisher={Zenodo},
16
+ doi={#{@metadata.doi}},
17
+ url={#{@metadata.zenodo_url}},
18
+ }
19
+ BIBTEX
20
+ end
21
+
22
+ def key
23
+ title_word = DL::Core::Slug.new(@metadata.title).to_s.split('-').first
24
+
25
+ "#{surname}#{year}#{title_word}"
26
+ end
27
+
28
+ private
29
+
30
+ def authors
31
+ @metadata.authors.map(&:name).join ' and '
32
+ end
33
+
34
+ # "Henman, Paul" and "Paul Henman" both give a lowercase surname
35
+ def surname
36
+ first_author = @metadata.authors.first
37
+ return 'anonymous' if first_author.nil?
38
+
39
+ name = first_author.name
40
+ last = name.include?(',') ? name.split(',').first : name.split.last
41
+ last.downcase.gsub(/[^a-z]/, '')
42
+ end
43
+
44
+ def year
45
+ @metadata.published.to_s[0, 4]
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,5 @@
1
+ module Zenodo
2
+ module Downloader
3
+ class ChecksumMismatch < Error; end
4
+ end
5
+ end
@@ -0,0 +1,24 @@
1
+ module Zenodo
2
+ module Downloader
3
+ class CLI < DL::Core::CLI
4
+ def program = 'zenodo-dl'
5
+
6
+ def target_name = 'ZENODO_ID_OR_URL'
7
+
8
+ # ZENODO_DOWNLOAD_PATH, ZENODO_RATE_LIMIT
9
+ def env_prefix = 'ZENODO'
10
+
11
+ def default_path = File.join(Dir.home, 'Downloads', 'Zenodo_Papers')
12
+
13
+ def version = VERSION
14
+
15
+ def user_agent = Client::USER_AGENT
16
+
17
+ def client_for(rate_limit:, log:) = Client.new(rate_limit:, log:)
18
+
19
+ def identifier_for(target) = Identifier.new(target)
20
+
21
+ def archive_for(identifier, root:, client:) = Archive.new(identifier, root:, client:)
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,14 @@
1
+ module Zenodo
2
+ module Downloader
3
+ # DL::Core::Client with zenodo-dl's User-Agent filled in. Zenodo allows guests
4
+ # 30 search requests a minute. The 3-second default stays under that.
5
+ class Client < DL::Core::Client
6
+ SOURCE_URL = 'https://github.com/xoengineering/zenodo-dl'.freeze
7
+ USER_AGENT = "zenodo-dl/#{VERSION} (+#{SOURCE_URL})".freeze
8
+
9
+ def initialize log: nil, rate_limit: DEFAULT_RATE_LIMIT
10
+ super(user_agent: USER_AGENT, log:, rate_limit:)
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,5 @@
1
+ module Zenodo
2
+ module Downloader
3
+ class Error < DL::Core::Error; end
4
+ end
5
+ end
@@ -0,0 +1,53 @@
1
+ require 'uri'
2
+
3
+ module Zenodo
4
+ module Downloader
5
+ # A Zenodo record ID. It can name one version, or a concept (all versions),
6
+ # which Zenodo resolves to the latest version.
7
+ class Identifier
8
+ class Invalid < Error; end
9
+
10
+ ID = /\A\d+\z/
11
+ DOI = %r{\A(?:doi:)?10\.5281/zenodo\.(\d+)\z}i
12
+ PATH = %r{\A(?:/api)?/records?/(\d+)(?:/|\z)}
13
+
14
+ attr_reader :id, :input
15
+
16
+ def initialize input
17
+ @input = input
18
+ @id = parse input.to_s.strip
19
+ raise Invalid, "not a Zenodo identifier: #{input}" if @id.nil?
20
+ end
21
+
22
+ def to_s = id
23
+
24
+ private
25
+
26
+ def parse text
27
+ return text if ID.match? text
28
+ return Regexp.last_match(1) if DOI.match text
29
+
30
+ parse_url text
31
+ end
32
+
33
+ # zenodo.org/records/<id>, /record/<id>, /api/records/<id>, /doi/10.5281/zenodo.<id>, and doi.org
34
+ def parse_url text
35
+ uri = URI.parse(text.include?('://') ? text : "https://#{text}")
36
+ path = uri.path.to_s
37
+
38
+ case uri.host
39
+ when 'doi.org', 'dx.doi.org' then DOI.match(path.delete_prefix('/'))&.captures&.first
40
+ when 'zenodo.org', 'www.zenodo.org' then zenodo_path path
41
+ end
42
+ rescue URI::InvalidURIError
43
+ nil
44
+ end
45
+
46
+ def zenodo_path path
47
+ return DOI.match(path.delete_prefix('/doi/'))&.captures&.first if path.start_with? '/doi/'
48
+
49
+ PATH.match(path)&.captures&.first
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,41 @@
1
+ module Zenodo
2
+ module Downloader
3
+ # The body of metadata.md. Zenodo's terms ask users to respect each record's license.
4
+ class MarkdownBody
5
+ def initialize metadata
6
+ @metadata = metadata
7
+ end
8
+
9
+ def to_s
10
+ <<~MARKDOWN
11
+
12
+ # #{@metadata.title}
13
+
14
+ #{authors_list}
15
+
16
+ - Published: #{@metadata.published}
17
+ - Type: #{@metadata.resource_type}
18
+ - Version: #{@metadata.version}
19
+ - Zenodo: [#{@metadata.doi}](#{@metadata.zenodo_url})
20
+ - License: #{@metadata.license}
21
+
22
+ ## Description
23
+
24
+ #{@metadata.description}
25
+ MARKDOWN
26
+ end
27
+
28
+ private
29
+
30
+ def authors_list
31
+ @metadata.authors.map { |author| "- #{author_line author}" }.join "\n"
32
+ end
33
+
34
+ def author_line author
35
+ return author.name if author.affiliations.empty?
36
+
37
+ "#{author.name} (#{author.affiliations.join '; '})"
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,21 @@
1
+ module Zenodo
2
+ module Downloader
3
+ # Field order is the reading order of the metadata sidecars.
4
+ Metadata = Data.define(
5
+ :zenodo_id,
6
+ :concept_id,
7
+ :version,
8
+ :doi,
9
+ :zenodo_url,
10
+ :title,
11
+ :authors,
12
+ :description,
13
+ :published,
14
+ :resource_type,
15
+ :journal,
16
+ :keywords,
17
+ :license,
18
+ :access_right
19
+ )
20
+ end
21
+ end
@@ -0,0 +1,9 @@
1
+ module Zenodo
2
+ module Downloader
3
+ class NotAPublication < Error
4
+ def initialize message = 'not a publication (zenodo-dl archives papers, not datasets or software)'
5
+ super
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ module Zenodo
2
+ module Downloader
3
+ class NotAvailable < Error
4
+ def initialize message = 'not open access on Zenodo, or has no files'
5
+ super
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ module Zenodo
2
+ module Downloader
3
+ class PaperNotFound < Error
4
+ def initialize message = 'no such record on Zenodo'
5
+ super
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,25 @@
1
+ module Zenodo
2
+ module Downloader
3
+ # The paper's folder, shared by all its versions, so it is keyed on the concept ID
4
+ class Path
5
+ def initialize metadata
6
+ @metadata = metadata
7
+ end
8
+
9
+ def to_s
10
+ [date_dir, @metadata.resource_type, "#{@metadata.concept_id}-#{slug}"].join '/'
11
+ end
12
+
13
+ private
14
+
15
+ # 2017-09-04 becomes 2017/09/04
16
+ def date_dir
17
+ @metadata.published.to_s.split('-').join '/'
18
+ end
19
+
20
+ def slug
21
+ DL::Core::Slug.new(@metadata.title).to_s
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,71 @@
1
+ require 'json'
2
+
3
+ module Zenodo
4
+ module Downloader
5
+ # Parses a Zenodo record (https://zenodo.org/api/records/<id>)
6
+ class RecordParser
7
+ RecordFile = Data.define :name, :size, :md5, :url
8
+
9
+ def initialize json
10
+ @record = JSON.parse json
11
+ end
12
+
13
+ def metadata
14
+ Metadata.new(
15
+ zenodo_id: @record.fetch('id').to_s,
16
+ concept_id: @record['conceptrecid'].to_s,
17
+ version: version,
18
+ doi: @record['doi'],
19
+ zenodo_url: "https://zenodo.org/records/#{@record.fetch('id')}",
20
+ title: fields['title'],
21
+ authors: authors,
22
+ description: fields['description'],
23
+ published: fields['publication_date'],
24
+ resource_type: fields.dig('resource_type', 'subtype') || fields.dig('resource_type', 'type'),
25
+ journal: fields.dig('journal', 'title'),
26
+ keywords: Array(fields['keywords']),
27
+ license: fields.dig('license', 'id'),
28
+ access_right: fields['access_right']
29
+ )
30
+ end
31
+
32
+ def files
33
+ Array(@record['files']).map do |file|
34
+ RecordFile.new(
35
+ name: file.fetch('key'),
36
+ size: file['size'],
37
+ md5: file['checksum'].to_s.delete_prefix('md5:'),
38
+ url: file.dig('links', 'self')
39
+ )
40
+ end
41
+ end
42
+
43
+ # zenodo-dl archives papers. Datasets and software can be many gigabytes.
44
+ def publication?
45
+ fields.dig('resource_type', 'type') == 'publication'
46
+ end
47
+
48
+ def downloadable?
49
+ fields['access_right'] == 'open' && files.any?
50
+ end
51
+
52
+ private
53
+
54
+ def fields
55
+ @record.fetch 'metadata', {}
56
+ end
57
+
58
+ # Zenodo numbers versions from 0
59
+ def version
60
+ index = fields.dig 'relations', 'version', 0, 'index'
61
+ index.nil? ? 1 : index + 1
62
+ end
63
+
64
+ def authors
65
+ Array(fields['creators']).map do |creator|
66
+ DL::Core::Author.new name: creator['name'], affiliations: Array(creator['affiliation'])
67
+ end
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,5 @@
1
+ module Zenodo
2
+ module Downloader
3
+ VERSION = '0.1.0'.freeze
4
+ end
5
+ end
@@ -0,0 +1,23 @@
1
+ require 'dl/core'
2
+
3
+ require_relative 'downloader/error' # before the errors below that subclass Error
4
+ require_relative 'downloader/version' # before client: Client::USER_AGENT uses VERSION
5
+
6
+ require_relative 'downloader/archive'
7
+ require_relative 'downloader/bibtex'
8
+ require_relative 'downloader/checksum_mismatch' # after error
9
+ require_relative 'downloader/cli'
10
+ require_relative 'downloader/client' # after version
11
+ require_relative 'downloader/identifier' # after error
12
+ require_relative 'downloader/markdown_body'
13
+ require_relative 'downloader/metadata'
14
+ require_relative 'downloader/not_a_publication' # after error
15
+ require_relative 'downloader/not_available' # after error
16
+ require_relative 'downloader/paper_not_found' # after error
17
+ require_relative 'downloader/path'
18
+ require_relative 'downloader/record_parser'
19
+
20
+ module Zenodo
21
+ module Downloader
22
+ end
23
+ end
@@ -0,0 +1,5 @@
1
+ module Zenodo
2
+ module Downloader
3
+ VERSION: String
4
+ end
5
+ end
metadata ADDED
@@ -0,0 +1,85 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: zenodo-dl
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Shane Becker
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: dl-core
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '0.2'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '0.2'
26
+ description: |
27
+ Command line tool and Ruby library for archiving open-access Zenodo publications
28
+ with their files, Zenodo's own record metadata, and sidecar metadata, any version.
29
+ email:
30
+ - veganstraightedge@gmail.com
31
+ executables:
32
+ - zenodo-dl
33
+ extensions: []
34
+ extra_rdoc_files: []
35
+ files:
36
+ - CHANGELOG.md
37
+ - CODE_OF_CONDUCT.md
38
+ - LICENSE.md
39
+ - README.md
40
+ - exe/zenodo-dl
41
+ - lib/zenodo/downloader.rb
42
+ - lib/zenodo/downloader/archive.rb
43
+ - lib/zenodo/downloader/bibtex.rb
44
+ - lib/zenodo/downloader/checksum_mismatch.rb
45
+ - lib/zenodo/downloader/cli.rb
46
+ - lib/zenodo/downloader/client.rb
47
+ - lib/zenodo/downloader/error.rb
48
+ - lib/zenodo/downloader/identifier.rb
49
+ - lib/zenodo/downloader/markdown_body.rb
50
+ - lib/zenodo/downloader/metadata.rb
51
+ - lib/zenodo/downloader/not_a_publication.rb
52
+ - lib/zenodo/downloader/not_available.rb
53
+ - lib/zenodo/downloader/paper_not_found.rb
54
+ - lib/zenodo/downloader/path.rb
55
+ - lib/zenodo/downloader/record_parser.rb
56
+ - lib/zenodo/downloader/version.rb
57
+ - sig/zenodo/downloader.rbs
58
+ homepage: https://github.com/xoengineering/zenodo-dl
59
+ licenses:
60
+ - MIT
61
+ metadata:
62
+ allowed_push_host: https://rubygems.org
63
+ homepage_uri: https://github.com/xoengineering/zenodo-dl
64
+ source_code_uri: https://github.com/xoengineering/zenodo-dl
65
+ bug_tracker_uri: https://github.com/xoengineering/zenodo-dl/issues
66
+ changelog_uri: https://github.com/xoengineering/zenodo-dl/blob/main/CHANGELOG.md
67
+ rubygems_mfa_required: 'true'
68
+ rdoc_options: []
69
+ require_paths:
70
+ - lib
71
+ required_ruby_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: 4.0.10
76
+ required_rubygems_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ requirements: []
82
+ rubygems_version: 4.0.20
83
+ specification_version: 4
84
+ summary: Download publications and metadata from Zenodo for offline archives.
85
+ test_files: []