Module: Commonmeta::Utils
- Included in:
- CLI, MetadataUtils
- Defined in:
- lib/commonmeta/utils.rb
Constant Summary collapse
- NORMALIZED_LICENSES =
{ "https://creativecommons.org/licenses/by/1.0" => "https://creativecommons.org/licenses/by/1.0/legalcode", "https://creativecommons.org/licenses/by/2.0" => "https://creativecommons.org/licenses/by/2.0/legalcode", "https://creativecommons.org/licenses/by/2.5" => "https://creativecommons.org/licenses/by/2.5/legalcode", "https://creativecommons.org/licenses/by/3.0" => "https://creativecommons.org/licenses/by/3.0/legalcode", "https://creativecommons.org/licenses/by/3.0/us" => "https://creativecommons.org/licenses/by/3.0/legalcode", "https://creativecommons.org/licenses/by/4.0" => "https://creativecommons.org/licenses/by/4.0/legalcode", "https://creativecommons.org/licenses/by-nc/1.0" => "https://creativecommons.org/licenses/by-nc/1.0/legalcode", "https://creativecommons.org/licenses/by-nc/2.0" => "https://creativecommons.org/licenses/by-nc/2.0/legalcode", "https://creativecommons.org/licenses/by-nc/2.5" => "https://creativecommons.org/licenses/by-nc/2.5/legalcode", "https://creativecommons.org/licenses/by-nc/3.0" => "https://creativecommons.org/licenses/by-nc/3.0/legalcode", "https://creativecommons.org/licenses/by-nc/4.0" => "https://creativecommons.org/licenses/by-nc/4.0/legalcode", "https://creativecommons.org/licenses/by-nd-nc/1.0" => "https://creativecommons.org/licenses/by-nd-nc/1.0/legalcode", "https://creativecommons.org/licenses/by-nd-nc/2.0" => "https://creativecommons.org/licenses/by-nd-nc/2.0/legalcode", "https://creativecommons.org/licenses/by-nd-nc/2.5" => "https://creativecommons.org/licenses/by-nd-nc/2.5/legalcode", "https://creativecommons.org/licenses/by-nd-nc/3.0" => "https://creativecommons.org/licenses/by-nd-nc/3.0/legalcode", "https://creativecommons.org/licenses/by-nd-nc/4.0" => "https://creativecommons.org/licenses/by-nd-nc/4.0/legalcode", "https://creativecommons.org/licenses/by-nc-sa/1.0" => "https://creativecommons.org/licenses/by-nc-sa/1.0/legalcode", "https://creativecommons.org/licenses/by-nc-sa/2.0" => "https://creativecommons.org/licenses/by-nc-sa/2.0/legalcode", "https://creativecommons.org/licenses/by-nc-sa/2.5" => "https://creativecommons.org/licenses/by-nc-sa/2.5/legalcode", "https://creativecommons.org/licenses/by-nc-sa/3.0" => "https://creativecommons.org/licenses/by-nc-sa/3.0/legalcode", "https://creativecommons.org/licenses/by-nc-sa/4.0" => "https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode", "https://creativecommons.org/licenses/by-nd/1.0" => "https://creativecommons.org/licenses/by-nd/1.0/legalcode", "https://creativecommons.org/licenses/by-nd/2.0" => "https://creativecommons.org/licenses/by-nd/2.0/legalcode", "https://creativecommons.org/licenses/by-nd/2.5" => "https://creativecommons.org/licenses/by-nd/2.5/legalcode", "https://creativecommons.org/licenses/by-nd/3.0" => "https://creativecommons.org/licenses/by-nd/3.0/legalcode", "https://creativecommons.org/licenses/by-nd/4.0" => "https://creativecommons.org/licenses/by-nd/2.0/legalcode", "https://creativecommons.org/licenses/by-sa/1.0" => "https://creativecommons.org/licenses/by-sa/1.0/legalcode", "https://creativecommons.org/licenses/by-sa/2.0" => "https://creativecommons.org/licenses/by-sa/2.0/legalcode", "https://creativecommons.org/licenses/by-sa/2.5" => "https://creativecommons.org/licenses/by-sa/2.5/legalcode", "https://creativecommons.org/licenses/by-sa/3.0" => "https://creativecommons.org/licenses/by-sa/3.0/legalcode", "https://creativecommons.org/licenses/by-sa/4.0" => "https://creativecommons.org/licenses/by-sa/4.0/legalcode", "https://creativecommons.org/licenses/by-nc-nd/1.0" => "https://creativecommons.org/licenses/by-nc-nd/1.0/legalcode", "https://creativecommons.org/licenses/by-nc-nd/2.0" => "https://creativecommons.org/licenses/by-nc-nd/2.0/legalcode", "https://creativecommons.org/licenses/by-nc-nd/2.5" => "https://creativecommons.org/licenses/by-nc-nd/2.5/legalcode", "https://creativecommons.org/licenses/by-nc-nd/3.0" => "https://creativecommons.org/licenses/by-nc-nd/3.0/legalcode", "https://creativecommons.org/licenses/by-nc-nd/4.0" => "https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode", "https://creativecommons.org/licenses/publicdomain" => "https://creativecommons.org/licenses/publicdomain/", "https://creativecommons.org/publicdomain/zero/1.0" => "https://creativecommons.org/publicdomain/zero/1.0/legalcode", }
- BIB_TO_CM_TRANSLATIONS =
{ "article" => "JournalArticle", "book" => "Book", "booklet" => "Book", "inbook" => "BookChapter", "inproceedings" => "ProceedingsArticle", "manual" => "Report", "mastersthesis" => "Dissertation", "misc" => "Other", "phdthesis" => "Dissertation", "proceedings" => "Proceedings", "techreport" => "Report", "unpublished" => "Manuscript", }
- CM_TO_BIB_TRANSLATIONS =
{ "Article" => "article", "Book" => "book", "BookChapter" => "inbook", "Dissertation" => "phdthesis", "JournalArticle" => "article", "Manuscript" => "unpublished", "Other" => "misc", "Proceedings" => "proceedings", "ProceedingsArticle" => "inproceedings", "Report" => "techreport", }
- CSL_TO_CM_TRANSLATIONS =
{ "article" => "Article", "article-journal" => "JournalArticle", "article-magazine" => "Article", "article-newspaper" => "Article", "bill" => "LegalDocument", "book" => "Book", "broadcast" => "Audiovisual", "chapter" => "BookChapter", "classic" => "Book", "collection" => "Collection", "dataset" => "Dataset", "document" => "Document", "entry" => "Entry", "entry-dictionary" => "Entry", "entry-encyclopedia" => "Entry", "event" => "Event", "figure" => "Figure", "graphic" => "Image", "hearing" => "LegalDocument", "interview" => "Document", "legal_case" => "LegalDocument", "legislation" => "LegalDocument", "manuscript" => "Manuscript", "map" => "Map", "motion_picture" => "Audiovisual", "musical_score" => "Document", "pamphlet" => "Document", "paper-conference" => "ProceedingsArticle", "patent" => "Patent", "performance" => "Performance", "periodical" => "Journal", "personal_communication" => "PersonalCommunication", "post" => "Post", "post-weblog" => "Article", "regulation" => "LegalDocument", "report" => "Report", "review" => "Review", "review-book" => "Review", "software" => "Software", "song" => "Audiovisual", "speech" => "Speech", "standard" => "Standard", "thesis" => "Dissertation", "treaty" => "LegalDocument", "webpage" => "WebPage", }
- CM_TO_CSL_TRANSLATIONS =
{ "Article" => "article", "JournalArticle" => "article-journal", "Book" => "book", "BookChapter" => "chapter", "Collection" => "collection", "Dataset" => "dataset", "Document" => "document", "Entry" => "entry", "Event" => "event", "Figure" => "figure", "Image" => "graphic", "LegalDocument" => "legal_case", "Manuscript" => "manuscript", "Map" => "map", "Audiovisual" => "motion_picture", "Patent" => "patent", "Performance" => "performance", "Journal" => "periodical", "PersonalCommunication" => "personal_communication", "Post" => "post", "Report" => "report", "Review" => "review", "Software" => "software", "Speech" => "speech", "Standard" => "standard", "Dissertation" => "thesis", "WebPage" => "webpage", }
- CR_TO_CM_TRANSLATIONS =
source: http://api.crossref.org/types
{ "BookChapter" => "BookChapter", "BookPart" => "BookPart", "BookSection" => "BookSection", "BookSeries" => "BookSeries", "BookSet" => "BookSet", "BookTrack" => "BookTrack", "Book" => "Book", "Component" => "Component", "Database" => "Database", "Dataset" => "Dataset", "Dissertation" => "Dissertation", "EditedBook" => "EditedBook", "Grant" => "Grant", "JournalArticle" => "JournalArticle", "JournalIssue" => "JournalIssue", "JournalVolume" => "JournalVolume", "Journal" => "Journal", "Monograph" => "Book", "Other" => "Other", "PeerReview" => "PeerReview", "PostedContent" => "Article", "ProceedingsArticle" => "ProceedingsArticle", "ProceedingsSeries" => "ProceedingsSeries", "Proceedings" => "Proceedings", "ReferenceBook" => "ReferenceBook", "ReferenceEntry" => "Entry", "ReportComponent" => "ReportComponent", "ReportSeries" => "ReportSeries", "Report" => "Report", "Standard" => "Standard", }
- CM_TO_CR_TRANSLATIONS =
{ "Article" => "PostedContent", "BookChapter" => "BookChapter", "BookSeries" => "BookSeries", "Book" => "Book", "Component" => "Component", "Dataset" => "Dataset", "Dissertation" => "Dissertation", "Grant" => "Grant", "JournalArticle" => "JournalArticle", "JournalIssue" => "JournalIssue", "JournalVolume" => "JournalVolume", "Journal" => "Journal", "ProceedingsArticle" => "ProceedingsArticle", "ProceedingsSeries" => "ProceedingsSeries", "Proceedings" => "Proceedings", "ReportComponent" => "ReportComponent", "ReportSeries" => "ReportSeries", "Report" => "Report", "PeerReview" => "PeerReview", "Other" => "Other", }
- DC_TO_CM_TRANSLATIONS =
{ "Audiovisual" => "Audiovisual", "BlogPosting" => "Article", "Book" => "Book", "BookChapter" => "BookChapter", "Collection" => "Collection", "ComputationalNotebook" => "ComputationalNotebook", "ConferencePaper" => "ProceedingsArticle", "ConferenceProceeding" => "Proceedings", "DataPaper" => "JournalArticle", "Dataset" => "Dataset", "Dissertation" => "Dissertation", "Event" => "Event", "Image" => "Image", "InteractiveResource" => "InteractiveResource", "Journal" => "Journal", "JournalArticle" => "JournalArticle", "Model" => "Model", "OutputManagementPlan" => "OutputManagementPlan", "PeerReview" => "PeerReview", "PhysicalObject" => "PhysicalObject", "Poster" => "Speech", "Preprint" => "Article", "Report" => "Report", "Service" => "Service", "Software" => "Software", "Sound" => "Sound", "Standard" => "Standard", "Text" => "Document", "Thesis" => "Dissertation", "Workflow" => "Workflow", "Other" => "Other", }
- CM_TO_DC_TRANSLATIONS =
{ "Article" => "Preprint", "Audiovisual" => "Audiovisual", "Book" => "Book", "BookChapter" => "BookChapter", "Collection" => "Collection", "Dataset" => "Dataset", "Dissertation" => "Dissertation", "Document" => "Text", "Entry" => "Text", "Event" => "Event", "Figure" => "Image", "Image" => "Image", "JournalArticle" => "JournalArticle", "LegalDocument" => "Text", "Manuscript" => "Text", "Map" => "Image", "Patent" => "Text", "Performance" => "Audiovisual", "PersonalCommunication" => "Text", "Post" => "Text", "ProceedingsArticle" => "ConferencePaper", "Proceedings" => "ConferenceProceeding", "Report" => "Report", "PeerReview" => "PeerReview", "Software" => "Software", "Sound" => "Sound", "Standard" => "Standard", "WebPage" => "Text", }
- RIS_TO_CM_TRANSLATIONS =
{ "ABST" => "Text", "ADVS" => "Text", "AGGR" => "Text", "ANCIENT" => "Text", "ART" => "Text", "BILL" => "Text", "BLOG" => "Text", "BOOK" => "Book", "CASE" => "Text", "CHAP" => "BookChapter", "CHART" => "Text", "CLSWK" => "Text", "CTLG" => "Collection", "COMP" => "Software", "DATA" => "Dataset", "DBASE" => "Database", "DICT" => "Dictionary", "EBOOK" => "Book", "ECHAP" => "BookChapter", "EDBOOK" => "Book", "EJOUR" => "JournalArticle", "ELEC" => "Text", "ENCYC" => "Encyclopedia", "EQUA" => "Equation", "FIGURE" => "Image", "GEN" => "CreativeWork", "GOVDOC" => "GovernmentDocument", "GRANT" => "Grant", "HEAR" => "Hearing", "ICOMM" => "Text", "INPR" => "Text", "JFULL" => "JournalArticle", "JOUR" => "JournalArticle", "LEGAL" => "LegalRuleOrRegulation", "MANSCPT" => "Text", "MAP" => "Map", "MGZN" => "MagazineArticle", "MPCT" => "Audiovisual", "MULTI" => "Audiovisual", "MUSIC" => "MusicScore", "NEWS" => "NewspaperArticle", "PAMP" => "Pamphlet", "PAT" => "Patent", "PCOMM" => "PersonalCommunication", "RPRT" => "Report", "SER" => "SerialPublication", "SLIDE" => "Slide", "SOUND" => "SoundRecording", "STAND" => "Standard", "THES" => "Dissertation", "UNBILL" => "UnenactedBill", "UNPB" => "UnpublishedWork", "VIDEO" => "Audiovisual", "WEB" => "WebPage", }
- CM_TO_RIS_TRANSLATIONS =
{ "Article" => "JOUR", "Audiovisual" => "VIDEO", "Book" => "BOOK", "BookChapter" => "CHAP", "Collection" => "CTLG", "Dataset" => "DATA", "Dissertation" => "THES", "Document" => "GEN", "Entry" => "DICT", "Event" => "GEN", "Figure" => "FIGURE", "Image" => "FIGURE", "JournalArticle" => "JOUR", "LegalDocument" => "GEN", "Manuscript" => "GEN", "Map" => "MAP", "Patent" => "PAT", "Performance" => "GEN", "PersonalCommunication" => "PCOMM", "Post" => "GEN", "ProceedingsArticle" => "CPAPER", "Proceedings" => "CONF", "Report" => "RPRT", "Review" => "GEN", "Software" => "COMP", "Sound" => "SOUND", "Standard" => "STAND", "WebPage" => "WEB", }
- SO_TO_CM_TRANSLATIONS =
{ "Article" => "Article", "BlogPosting" => "Article", "Book" => "Book", "BookChapter" => "BookChapter", "CreativeWork" => "Other", "Dataset" => "Dataset", "Dissertation" => "Dissertation", "NewsArticle" => "Article", "Legislation" => "LegalDocument", "ScholarlyArticle" => "JournalArticle", "SoftwareSourceCode" => "Software", }
- CM_TO_SO_TRANSLATIONS =
{ "Article" => "Article", "Audiovisual" => "CreativeWork", "Book" => "Book", "BookChapter" => "BookChapter", "Collection" => "CreativeWork", "Dataset" => "Dataset", "Dissertation" => "Dissertation", "Document" => "CreativeWork", "Entry" => "CreativeWork", "Event" => "CreativeWork", "Figure" => "CreativeWork", "Image" => "CreativeWork", "JournalArticle" => "ScholarlyArticle", "LegalDocument" => "Legislation", "Software" => "SoftwareSourceCode", }
- CM_TO_JATS_TRANSLATIONS =
{ "Proceedings" => "working-paper", "ReferenceBook" => "book", "JournalIssue" => "journal", "ProceedingsArticle" => "working-paper", "Other" => nil, "Dissertation" => nil, "Dataset" => "data", "Document" => "journal", "EditedBook" => "book", "JournalArticle" => "journal", "Journal" => "journal", "Report" => "report", "BookSeries" => "book", "ReportSeries" => "report", "BookTrack" => "book", "Standard" => "standard", "BookSection" => "chapter", "BookPart" => "chapter", "Book" => "book", "BookChapter" => "chapter", "StandardSeries" => "standard", "Monograph" => "book", "Component" => nil, "ReferenceEntry" => nil, "JournalVolume" => "journal", "BookSet" => "book", "Article" => "journal", "Software" => "software", }
- UNKNOWN_INFORMATION =
{ ":unac" => "temporarily inaccessible", ":unal" => "unallowed, suppressed intentionally", ":unap" => "not applicable, makes no sense", ":unas" => "value unassigned (e.g., Untitled)", ":unav" => "value unavailable, possibly unknown", ":unkn" => "known to be unknown (e.g., Anonymous, Inconnue)", ":none" => "never had a value, never will", ":null" => "explicitly and meaningfully empty", ":tba" => "to be assigned or announced later", ":etal" => "too numerous to list (et alia)", }
Instance Method Summary collapse
- #decode_container_id(id) ⇒ Object
- #decode_doi(doi, options = {}) ⇒ Object
- #encode_container_id ⇒ Object
- #encode_doi(prefix, options = {}) ⇒ Object
- #encode_doi_for_uuid(uuid, options = {}) ⇒ Object
- #find_from_format(id: nil, string: nil, ext: nil, filename: nil) ⇒ Object
- #find_from_format_by_ext(string, options = {}) ⇒ Object
- #find_from_format_by_filename(filename) ⇒ Object
- #find_from_format_by_id(id) ⇒ Object
- #find_from_format_by_string(string) ⇒ Object
- #from_csl(element) ⇒ Object
- #from_datacite(element) ⇒ Object
- #from_json_feed(element) ⇒ Object
- #from_schema_org(element) ⇒ Object
- #generate_ghost_token(admin_api_key) ⇒ Object
- #get_contributor(contributor, contributor_type) ⇒ Object
- #get_date(dates, date_type) ⇒ Object
- #get_date_from_date_parts(date_as_parts) ⇒ Object
- #get_date_from_parts(year, month = nil, day = nil) ⇒ Object
- #get_date_parts(iso8601_time) ⇒ Object
- #get_date_parts_from_parts(year, month = nil, day = nil) ⇒ Object
-
#get_dates_from_date(date) ⇒ Object
convert commonmeta dates to DataCite format.
-
#get_datetime_from_iso8601(iso8601_time) ⇒ Object
parsing of incomplete iso8601 timestamps such as 2015-04 is broken in standard library, so we use the edtf gem return nil if invalid iso8601 timestamp.
-
#get_datetime_from_time(time) ⇒ Object
iso8601 datetime without hyphens and colons, used by Crossref return nil if invalid.
- #get_identifier(identifiers, identifier_type) ⇒ Object
- #get_identifier_type(identifier_type) ⇒ Object
- #get_iso8601_date(iso8601_time) ⇒ Object
- #get_link(links, link_type) ⇒ Object
- #get_series_information(str) ⇒ Object
- #get_year_month(iso8601_time) ⇒ Object
- #get_year_month_day(iso8601_time) ⇒ Object
- #github_as_cff_url(url) ⇒ Object
- #github_as_codemeta_url(url) ⇒ Object
- #github_as_owner_url(url) ⇒ Object
- #github_as_release_url(url) ⇒ Object
- #github_as_repo_url(url) ⇒ Object
- #github_from_url(url) ⇒ Object
- #github_owner_from_url(url) ⇒ Object
- #github_release_from_url(url) ⇒ Object
- #github_repo_from_url(url) ⇒ Object
- #hsh_to_fos(hsh) ⇒ Object
- #hsh_to_spdx(hsh) ⇒ Object
- #json_feed_by_blog_url(blog_id) ⇒ Object
- #json_feed_item_by_uuid_url(uuid) ⇒ Object
- #json_feed_not_indexed_url(date_indexed) ⇒ Object
- #json_feed_unregistered_url ⇒ Object
- #jsonlint(json) ⇒ Object
- #map_hash_keys(element: nil, mapping: nil) ⇒ Object
- #name_to_fos(name) ⇒ Object
- #name_to_spdx(name) ⇒ Object
- #normalize_cc_url(id) ⇒ Object
- #normalize_id(id, options = {}) ⇒ Object
-
#normalize_issn(input, options = {}) ⇒ Object
pick electronic issn if there are multiple format issn as xxxx-xxxx.
-
#normalize_licenses(licenses) ⇒ Object
find Creative Commons or OSI license in licenses array, normalize url and name.
- #normalize_orcid(orcid) ⇒ Object
- #normalize_ror(ror) ⇒ Object
- #normalize_url(id, options = {}) ⇒ Object
- #orcid_as_url(orcid) ⇒ Object
- #orcid_from_url(url) ⇒ Object
- #parse_attributes(element, options = {}) ⇒ Object
- #rogue_scholar_api_url(id, _options = {}) ⇒ Object
- #sanitize(text, options = {}) ⇒ Object
- #spdx_to_hsh(hsh) ⇒ Object
-
#strip_milliseconds(iso8601_time) ⇒ Object
strip milliseconds if there is a time, as it interferes with edtc parsing keep dates unchanged.
- #to_csl(element) ⇒ Object
- #to_datacite(element, options = {}) ⇒ Object
- #to_identifier(identifier) ⇒ Object
- #to_ris(element) ⇒ Object
- #to_schema_org(element) ⇒ Object
- #to_schema_org_citation(reference) ⇒ Object
- #to_schema_org_container(element, options = {}) ⇒ Object
- #to_schema_org_funder(funding_references) ⇒ Object
- #to_schema_org_identifiers(element, _options = {}) ⇒ Object
- #to_schema_org_relation(related_identifiers: nil, relation_type: nil) ⇒ Object
- #to_schema_org_spatial_coverage(geo_location) ⇒ Object
- #update_ghost_post_via_api(uuid) ⇒ Object
- #validate_email(str) ⇒ Object
- #validate_orcid(orcid) ⇒ Object
- #validate_orcid_scheme(orcid_scheme) ⇒ Object
- #validate_ror(ror) ⇒ Object
- #validate_url(str) ⇒ Object
Instance Method Details
#decode_container_id(id) ⇒ Object
1436 1437 1438 |
# File 'lib/commonmeta/utils.rb', line 1436 def decode_container_id(id) Base32::URL.decode(id) end |
#decode_doi(doi, options = {}) ⇒ Object
1420 1421 1422 1423 1424 1425 1426 1427 |
# File 'lib/commonmeta/utils.rb', line 1420 def decode_doi(doi, = {}) suffix = doi.split("/", 5).last if [:uuid] Base32::URL.decode_uuid(suffix) else Base32::URL.decode(suffix) end end |
#encode_container_id ⇒ Object
1429 1430 1431 1432 1433 1434 |
# File 'lib/commonmeta/utils.rb', line 1429 def encode_container_id # suffix has 5 digits plus two checksum digits. With base32 there are # 32 possible digits, so 5 digits gives 32^5 possible combinations random_int = SecureRandom.random_number(32 ** 4..(32 ** 5) - 1) Base32::URL.encode(random_int, checksum: true) end |
#encode_doi(prefix, options = {}) ⇒ Object
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 |
# File 'lib/commonmeta/utils.rb', line 1386 def encode_doi(prefix, = {}) return nil unless prefix.present? # DOI suffix is a generated from a random number, encoded in base32 # suffix has 8 digits plus two checksum digits. With base32 there are # 32 possible digits, so 8 digits gives 32^8 possible combinations if [:uuid] str = Base32::URL.encode_uuid([:uuid], split: 7, checksum: true) return nil unless str.present? else random_int = SecureRandom.random_number(32 ** 7..(32 ** 8) - 1) suffix = Base32::URL.encode(random_int, checksum: true) str = "#{suffix[0, 5]}-#{suffix[5, 10]}" end "https://doi.org/#{prefix}/#{str}" end |
#encode_doi_for_uuid(uuid, options = {}) ⇒ Object
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 |
# File 'lib/commonmeta/utils.rb', line 1403 def encode_doi_for_uuid(uuid, = {}) # look up prefix for rogue scholar blog associated with uuid # returns nil if unknown uuid or doi registration is not enabled for blog json_feed_by_uuid(uuid) # DOI suffix is a generated from a random number, encoded in base32 # suffix has 8 digits plus two checksum digits. With base32 there are # 32 possible digits, so 8 digits gives 32^8 possible combinations if [:uuid] str = Base32::URL.encode_uuid([:uuid], split: 7, checksum: true) else random_int = SecureRandom.random_number(32 ** 7..(32 ** 8) - 1) suffix = Base32::URL.encode(random_int, checksum: true) str = "#{suffix[0, 5]}-#{suffix[5, 10]}" end "https://doi.org/#{prefix}/#{str}" end |
#find_from_format(id: nil, string: nil, ext: nil, filename: nil) ⇒ Object
441 442 443 444 445 446 447 448 449 450 451 452 453 |
# File 'lib/commonmeta/utils.rb', line 441 def find_from_format(id: nil, string: nil, ext: nil, filename: nil) if id.present? find_from_format_by_id(id) elsif string.present? && ext.present? find_from_format_by_ext(string, ext: ext) elsif string.present? find_from_format_by_string(string) elsif filename.present? find_from_format_by_filename(filename) else "datacite" end end |
#find_from_format_by_ext(string, options = {}) ⇒ Object
486 487 488 489 490 491 492 493 494 495 |
# File 'lib/commonmeta/utils.rb', line 486 def find_from_format_by_ext(string, = {}) case [:ext] when ".bib" "bibtex" when ".ris" "ris" when ".xml", ".json" find_from_format_by_string(string) end end |
#find_from_format_by_filename(filename) ⇒ Object
478 479 480 481 482 483 484 |
# File 'lib/commonmeta/utils.rb', line 478 def find_from_format_by_filename(filename) if filename == "package.json" "npm" elsif filename == "CITATION.cff" "cff" end end |
#find_from_format_by_id(id) ⇒ Object
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 |
# File 'lib/commonmeta/utils.rb', line 455 def find_from_format_by_id(id) id = normalize_id(id) if %r{\A(?:(http|https):/(/)?(dx\.)?(doi\.org|handle\.stage\.datacite\.org)/)?(doi:)?(10\.\d{4,5}/.+)\z}.match?(id) ra = get_doi_ra(id) %w[DataCite Crossref mEDRA KISTI JaLC OP].include?(ra) ? ra.downcase : nil elsif %r{\A(?:(http|https):/(/)?orcid\.org/)?(\d{4}-\d{4}-\d{4}-\d{3}[0-9X]+)\z}.match?(id) "orcid" elsif %r{\A(http|https):/(/)?github\.com/(.+)/package.json\z}.match?(id) "npm" elsif %r{\A(http|https):/(/)?github\.com/(.+)/codemeta.json\z}.match?(id) "codemeta" elsif %r{\A(http|https):/(/)?github\.com/(.+)/CITATION.cff\z}.match?(id) "cff" elsif %r{\A(http|https):/(/)?github\.com/(.+)\z}.match?(id) "cff" elsif %r{\A(http|https):/(/)?rogue-scholar\.org/api/posts/(.+)\z}.match?(id) "json_feed_item" else "schema_org" end end |
#find_from_format_by_string(string) ⇒ Object
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 |
# File 'lib/commonmeta/utils.rb', line 497 def find_from_format_by_string(string) begin # try to parse as JSON hsh = MultiJson.load(string).to_h if hsh.dig("@context") && URI.parse(hsh.dig("@context")).host == "schema.org" return "schema_org" elsif hsh.dig("schemaVersion").to_s.start_with?("http://datacite.org/schema/kernel") return "datacite" elsif hsh.dig("source") == "Crossref" return "crossref" elsif hsh.dig("issued", "date-parts").present? return "csl" elsif URI.parse(hsh.dig("@context")).to_s == "https://raw.githubusercontent.com/codemeta/codemeta/master/codemeta.jsonld" return "codemeta" end rescue MultiJson::ParseError end begin # try to parse as XML hsh = Hash.from_xml(string) return "crossref_xml" if hsh.to_h.dig("crossref_result").present? rescue Nokogiri::XML::SyntaxError end begin # try to parse as YAML hsh = YAML.load(string, permitted_classes: [Date]) return "cff" if hsh.is_a?(Hash) && hsh.fetch("cff-version", nil).present? rescue Psych::SyntaxError end if string.start_with?("TY - ") "ris" elsif BibTeX.parse(string).first "bibtex" end end |
#from_csl(element) ⇒ Object
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 |
# File 'lib/commonmeta/utils.rb', line 911 def from_csl(element) Array.wrap(element).map do |a| if a["literal"].present? a["type"] = "Organization" a["name"] = a["literal"] elsif a["name"].present? a["type"] = "Organization" elsif a["given"].present? || a["family"].present? a["type"] = "Person" end a["givenName"] = a["given"] a["familyName"] = a["family"] a.except("given", "family", "literal").compact end.unwrap end |
#from_datacite(element) ⇒ Object
722 723 724 725 726 |
# File 'lib/commonmeta/utils.rb', line 722 def from_datacite(element) mapping = { "nameType" => "type", "creatorName" => "name" } map_hash_keys(element: element, mapping: mapping) end |
#from_json_feed(element) ⇒ Object
905 906 907 908 909 |
# File 'lib/commonmeta/utils.rb', line 905 def from_json_feed(element) mapping = { "url" => "id" } map_hash_keys(element: element, mapping: mapping) end |
#from_schema_org(element) ⇒ Object
865 866 867 868 869 |
# File 'lib/commonmeta/utils.rb', line 865 def from_schema_org(element) mapping = { "@type" => "type", "@id" => "id" } map_hash_keys(element: element, mapping: mapping) end |
#generate_ghost_token(admin_api_key) ⇒ Object
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 |
# File 'lib/commonmeta/utils.rb', line 1456 def generate_ghost_token(admin_api_key) # from https://ghost.org/docs/admin-api/ # Split the key into ID and SECRET id, secret = admin_api_key.split(":") # Prepare header and payload iat = Time.now.to_i header = { alg: "HS256", typ: "JWT", kid: id } payload = { iat: iat, exp: iat + 5 * 60, aud: "/admin/", } # Create the token (including decoding secret) JWT.encode payload, [secret].pack("H*"), "HS256", header end |
#get_contributor(contributor, contributor_type) ⇒ Object
1145 1146 1147 |
# File 'lib/commonmeta/utils.rb', line 1145 def get_contributor(contributor, contributor_type) contributor.select { |c| c["contributorType"] == contributor_type } end |
#get_date(dates, date_type) ⇒ Object
1117 1118 1119 1120 |
# File 'lib/commonmeta/utils.rb', line 1117 def get_date(dates, date_type) dd = Array.wrap(dates).find { |d| d["dateType"] == date_type } || {} dd.fetch("date", nil) end |
#get_date_from_date_parts(date_as_parts) ⇒ Object
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 |
# File 'lib/commonmeta/utils.rb', line 1034 def get_date_from_date_parts(date_as_parts) date_parts = date_as_parts.fetch("date-parts", []).first return nil if date_parts == [nil] year = date_parts[0] month = date_parts[1] day = date_parts[2] get_date_from_parts(year, month, day) rescue NoMethodError # if date_parts is nil nil end |
#get_date_from_parts(year, month = nil, day = nil) ⇒ Object
1046 1047 1048 1049 1050 |
# File 'lib/commonmeta/utils.rb', line 1046 def get_date_from_parts(year, month = nil, day = nil) [year.to_s.rjust(4, "0"), month.to_s.rjust(2, "0"), day.to_s.rjust(2, "0")].reject do |part| part == "00" end.join("-") end |
#get_date_parts(iso8601_time) ⇒ Object
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 |
# File 'lib/commonmeta/utils.rb', line 1023 def get_date_parts(iso8601_time) return { "date-parts" => [[]] } if iso8601_time.nil? year = iso8601_time[0..3].to_i month = iso8601_time[5..6].to_i day = iso8601_time[8..9].to_i { "date-parts" => [[year, month, day].reject { |part| part == 0 }] } rescue TypeError nil end |
#get_date_parts_from_parts(year, month = nil, day = nil) ⇒ Object
1052 1053 1054 |
# File 'lib/commonmeta/utils.rb', line 1052 def get_date_parts_from_parts(year, month = nil, day = nil) { "date-parts" => [[year.to_i, month.to_i, day.to_i].reject { |part| part == 0 }] } end |
#get_dates_from_date(date) ⇒ Object
convert commonmeta dates to DataCite format
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 |
# File 'lib/commonmeta/utils.rb', line 1132 def get_dates_from_date(date) return nil if date.nil? mapping = { "published" => "issued" } date = map_hash_keys(element: date, mapping: mapping) date.map do |k, v| { "date" => v, "dateType" => k.capitalize } end end |
#get_datetime_from_iso8601(iso8601_time) ⇒ Object
parsing of incomplete iso8601 timestamps such as 2015-04 is broken in standard library, so we use the edtf gem return nil if invalid iso8601 timestamp
1091 1092 1093 1094 1095 |
# File 'lib/commonmeta/utils.rb', line 1091 def get_datetime_from_iso8601(iso8601_time) Date.edtf(iso8601_time).to_time.utc rescue StandardError nil end |
#get_datetime_from_time(time) ⇒ Object
iso8601 datetime without hyphens and colons, used by Crossref return nil if invalid
1111 1112 1113 1114 1115 |
# File 'lib/commonmeta/utils.rb', line 1111 def get_datetime_from_time(time) DateTime.strptime(time.to_s, "%Y%m%d%H%M%S").strftime("%Y-%m-%dT%H:%M:%SZ") rescue ArgumentError nil end |
#get_identifier(identifiers, identifier_type) ⇒ Object
1149 1150 1151 1152 |
# File 'lib/commonmeta/utils.rb', line 1149 def get_identifier(identifiers, identifier_type) id = Array.wrap(identifiers).find { |i| i["identifierType"] == identifier_type } || {} id.fetch("identifier", nil) end |
#get_identifier_type(identifier_type) ⇒ Object
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 |
# File 'lib/commonmeta/utils.rb', line 1154 def get_identifier_type(identifier_type) return nil unless identifier_type.present? identifierTypes = { "ark" => "ARK", "arxiv" => "arXiv", "bibcode" => "bibcode", "doi" => "DOI", "ean13" => "EAN13", "eissn" => "EISSN", "handle" => "Handle", "igsn" => "IGSN", "isbn" => "ISBN", "issn" => "ISSN", "istc" => "ISTC", "lissn" => "LISSN", "lsid" => "LSID", "pmid" => "PMID", "purl" => "PURL", "upc" => "UPC", "url" => "URL", "urn" => "URN", "md5" => "md5", "minid" => "minid", "dataguid" => "dataguid", } identifierTypes[identifier_type.downcase] || identifier_type end |
#get_iso8601_date(iso8601_time) ⇒ Object
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 |
# File 'lib/commonmeta/utils.rb', line 1056 def get_iso8601_date(iso8601_time) return nil if iso8601_time.nil? || iso8601_time.length < 4 case iso8601_time.length when 4 iso8601_time[0..3] when 7 iso8601_time[0..6] else iso8601_time[0..9] end end |
#get_link(links, link_type) ⇒ Object
1122 1123 1124 1125 |
# File 'lib/commonmeta/utils.rb', line 1122 def get_link(links, link_type) ll = Array.wrap(links).find { |d| d["rel"] == link_type } || {} ll.fetch("href", nil) end |
#get_series_information(str) ⇒ Object
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 |
# File 'lib/commonmeta/utils.rb', line 1184 def get_series_information(str) return {} unless str.present? str = str.split(",").map(&:strip) title = str.first volume_issue = str.length > 2 ? str[1].rpartition(/\(([^)]+)\)/) : nil volume = volume_issue.present? ? volume_issue[0].presence || volume_issue[2].presence : nil issue = volume_issue.present? ? volume_issue[1][1...-1].presence : nil pages = str.length > 1 ? str.last : nil first_page = pages.present? ? pages.split("-").map(&:strip)[0] : nil last_page = pages.present? ? pages.split("-").map(&:strip)[1] : nil { "title" => title, "volume" => volume, "issue" => issue, "firstPage" => first_page, "lastPage" => last_page, }.compact end |
#get_year_month(iso8601_time) ⇒ Object
1069 1070 1071 1072 1073 1074 1075 1076 |
# File 'lib/commonmeta/utils.rb', line 1069 def get_year_month(iso8601_time) return [] if iso8601_time.nil? year = iso8601_time[0..3] month = iso8601_time[5..6] [year.to_i, month.to_i].reject { |part| part == 0 } end |
#get_year_month_day(iso8601_time) ⇒ Object
1078 1079 1080 1081 1082 1083 1084 1085 1086 |
# File 'lib/commonmeta/utils.rb', line 1078 def get_year_month_day(iso8601_time) return [] if iso8601_time.nil? year = iso8601_time[0..3] month = iso8601_time[5..6] day = iso8601_time[8..9] [year.to_i, month.to_i, day.to_i].reject { |part| part == 0 } end |
#github_as_cff_url(url) ⇒ Object
1013 1014 1015 1016 1017 1018 1019 1020 1021 |
# File 'lib/commonmeta/utils.rb', line 1013 def github_as_cff_url(url) github_hash = github_from_url(url) if github_hash[:path].to_s.end_with?("CITATION.cff") "https://raw.githubusercontent.com/#{github_hash[:owner]}/#{github_hash[:repo]}/#{github_hash[:release]}/#{github_hash[:path]}" elsif github_hash[:owner].present? "https://raw.githubusercontent.com/#{github_hash[:owner]}/#{github_hash[:repo]}/main/CITATION.cff" end end |
#github_as_codemeta_url(url) ⇒ Object
1003 1004 1005 1006 1007 1008 1009 1010 1011 |
# File 'lib/commonmeta/utils.rb', line 1003 def (url) github_hash = github_from_url(url) if github_hash[:path].to_s.end_with?("codemeta.json") "https://raw.githubusercontent.com/#{github_hash[:owner]}/#{github_hash[:repo]}/#{github_hash[:release]}/#{github_hash[:path]}" elsif github_hash[:owner].present? "https://raw.githubusercontent.com/#{github_hash[:owner]}/#{github_hash[:repo]}/master/codemeta.json" end end |
#github_as_owner_url(url) ⇒ Object
984 985 986 987 |
# File 'lib/commonmeta/utils.rb', line 984 def github_as_owner_url(url) github_hash = github_from_url(url) "https://github.com/#{github_hash[:owner]}" if github_hash[:owner].present? end |
#github_as_release_url(url) ⇒ Object
996 997 998 999 1000 1001 |
# File 'lib/commonmeta/utils.rb', line 996 def github_as_release_url(url) github_hash = github_from_url(url) return unless github_hash[:release].present? "https://github.com/#{github_hash[:owner]}/#{github_hash[:repo]}/tree/#{github_hash[:release]}" end |
#github_as_repo_url(url) ⇒ Object
989 990 991 992 993 994 |
# File 'lib/commonmeta/utils.rb', line 989 def github_as_repo_url(url) github_hash = github_from_url(url) return unless github_hash[:repo].present? "https://github.com/#{github_hash[:owner]}/#{github_hash[:repo]}" end |
#github_from_url(url) ⇒ Object
963 964 965 966 967 968 969 970 |
# File 'lib/commonmeta/utils.rb', line 963 def github_from_url(url) return {} unless %r{\Ahttps://github\.com/(.+)(?:/)?(.+)?(?:/tree/)?(.*)\z}.match?(url) words = URI.parse(url).path[1..-1].split("/") path = words.length > 3 ? words[4...words.length].join("/") : nil { owner: words[0], repo: words[1], release: words[3], path: path }.compact end |
#github_owner_from_url(url) ⇒ Object
980 981 982 |
# File 'lib/commonmeta/utils.rb', line 980 def github_owner_from_url(url) github_from_url(url).fetch(:owner, nil) end |
#github_release_from_url(url) ⇒ Object
976 977 978 |
# File 'lib/commonmeta/utils.rb', line 976 def github_release_from_url(url) github_from_url(url).fetch(:release, nil) end |
#github_repo_from_url(url) ⇒ Object
972 973 974 |
# File 'lib/commonmeta/utils.rb', line 972 def github_repo_from_url(url) github_from_url(url).fetch(:repo, nil) end |
#hsh_to_fos(hsh) ⇒ Object
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 |
# File 'lib/commonmeta/utils.rb', line 1313 def hsh_to_fos(hsh) # first find subject in Fields of Science (OECD) fos = JSON.load(File.read(File.("../../resources/oecd/fos-mappings.json", __dir__))).fetch("fosFields") subject = fos.find do |l| l["fosLabel"] == hsh["__content__"] || "FOS: " + l["fosLabel"] == hsh["__content__"] || l["fosLabel"] == hsh["subject"] end if subject return [{ "subject" => sanitize(hsh["__content__"] || hsh["subject"]), "subjectScheme" => hsh["subjectScheme"], "schemeUri" => hsh["schemeURI"] || hsh["schemeUri"], "valueUri" => hsh["valueURI"] || hsh["valueUri"], "classificationCode" => hsh["classificationCode"], "lang" => hsh["lang"], }.compact, { "subject" => "FOS: " + subject["fosLabel"], "subjectScheme" => "Fields of Science and Technology (FOS)", "schemeUri" => "http://www.oecd.org/science/inno/38235147.pdf", }.compact] end # if not found, look in Fields of Research (Australian and New Zealand Standard Research Classification) # and map to Fields of Science. Add an extra entry for the latter fores = JSON.load(File.read(File.("../../resources/oecd/for-mappings.json", __dir__))) for_fields = fores.fetch("forFields") for_disciplines = fores.fetch("forDisciplines") # try to extract forId if hsh["subjectScheme"] == "FOR" for_id = hsh["__content__"].to_s.split(" ").first || hsh["subject"].to_s.split(" ").first for_id = for_id.rjust(6, "0") subject = for_fields.find { |l| l["forId"] == for_id } || for_disciplines.find { |l| l["forId"] == for_id[0..3] } else subject = for_fields.find do |l| l["forLabel"] == hsh["__content__"] || l["forLabel"] == hsh["subject"] end || for_disciplines.find do |l| l["forLabel"] == hsh["__content__"] || l["forLabel"] == hsh["subject"] end end if subject [{ "subject" => sanitize(hsh["__content__"] || hsh["subject"]), "subjectScheme" => hsh["subjectScheme"], "classificationCode" => hsh["classificationCode"], "schemeUri" => hsh["schemeURI"] || hsh["schemeUri"], "valueUri" => hsh["valueURI"] || hsh["valueUri"], "lang" => hsh["lang"], }.compact, { "subject" => "FOS: " + subject["fosLabel"], "subjectScheme" => "Fields of Science and Technology (FOS)", "schemeUri" => "http://www.oecd.org/science/inno/38235147.pdf", }] else [{ "subject" => sanitize(hsh["__content__"] || hsh["subject"]), "subjectScheme" => hsh["subjectScheme"], "classificationCode" => hsh["classificationCode"], "schemeUri" => hsh["schemeURI"] || hsh["schemeUri"], "valueUri" => hsh["valueURI"] || hsh["valueUri"], "lang" => hsh["lang"], }.compact] end end |
#hsh_to_spdx(hsh) ⇒ Object
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 |
# File 'lib/commonmeta/utils.rb', line 1229 def hsh_to_spdx(hsh) spdx = JSON.load(File.read(File.("../../resources/spdx/licenses.json", __dir__))).fetch("licenses") hsh["rightsUri"] = hsh.delete("rightsURI") if hsh["rightsUri"].blank? license = spdx.find do |l| l["licenseId"].casecmp?(hsh["rightsIdentifier"]) || l["seeAlso"].first == normalize_cc_url(hsh["rightsUri"]) || l["name"] == hsh["rights"] || l["seeAlso"].first == normalize_cc_url(hsh["rights"]) end if license { "id" => license["licenseId"], "url" => license["seeAlso"].first }.compact else { "id" => hsh["rightsIdentifier"].present? ? hsh["rightsIdentifier"].downcase : nil, "url" => hsh["rightsURI"] || hsh["rightsUri"], }.compact end end |
#json_feed_by_blog_url(blog_id) ⇒ Object
1448 1449 1450 |
# File 'lib/commonmeta/utils.rb', line 1448 def json_feed_by_blog_url(blog_id) "https://rogue-scholar.org/api/blogs/#{blog_id}" end |
#json_feed_item_by_uuid_url(uuid) ⇒ Object
1452 1453 1454 |
# File 'lib/commonmeta/utils.rb', line 1452 def json_feed_item_by_uuid_url(uuid) "https://rogue-scholar.org/api/posts/#{uuid}" end |
#json_feed_not_indexed_url(date_indexed) ⇒ Object
1440 1441 1442 |
# File 'lib/commonmeta/utils.rb', line 1440 def json_feed_not_indexed_url(date_indexed) "https://rogue-scholar.org/api/posts/not_indexed/#{date_indexed}" end |
#json_feed_unregistered_url ⇒ Object
1444 1445 1446 |
# File 'lib/commonmeta/utils.rb', line 1444 def json_feed_unregistered_url "https://rogue-scholar.org/api/posts/unregistered" end |
#jsonlint(json) ⇒ Object
1206 1207 1208 1209 1210 1211 1212 1213 |
# File 'lib/commonmeta/utils.rb', line 1206 def jsonlint(json) return ["No JSON provided"] unless json.present? error_array = [] linter = JsonLint::Linter.new linter.send(:check_data, json, error_array) error_array end |
#map_hash_keys(element: nil, mapping: nil) ⇒ Object
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 |
# File 'lib/commonmeta/utils.rb', line 871 def map_hash_keys(element: nil, mapping: nil) Array.wrap(element).map do |a| a.map { |k, v| [mapping.fetch(k, k), v] }.reduce({}) do |hsh, (k, v)| if k == "affiliation" && v.is_a?(Array) hsh[k] = v.map do |affiliation| if affiliation.is_a?(Hash) affiliation.merge("@type" => "Organization") else affiliation end end hsh elsif k == "type" && v.is_a?(String) hsh[k] = v.capitalize hsh elsif v.is_a?(Hash) hsh[k] = to_schema_org(v) hsh else hsh[k] = v hsh end end end.unwrap end |
#name_to_fos(name) ⇒ Object
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 |
# File 'lib/commonmeta/utils.rb', line 1268 def name_to_fos(name) # make sure name is capitalized name = name.capitalize # first find subject in Fields of Science (OECD) fos = JSON.load(File.read(File.("../../resources/oecd/fos-mappings.json", __dir__))).fetch("fosFields") subject = fos.find { |l| l["fosLabel"] == name || "FOS: " + l["fosLabel"] == name } if subject return [{ "subject" => sanitize(name), }, { "subject" => "FOS: " + subject["fosLabel"], "subjectScheme" => "Fields of Science and Technology (FOS)", "schemeUri" => "http://www.oecd.org/science/inno/38235147.pdf", }] end # if not found, look in Fields of Research (Australian and New Zealand Standard Research Classification) # and map to Fields of Science. Add an extra entry for the latter fores = JSON.load(File.read(File.("../../resources/oecd/for-mappings.json", __dir__))) for_fields = fores.fetch("forFields") for_disciplines = fores.fetch("forDisciplines") subject = for_fields.find { |l| l["forLabel"] == name } || for_disciplines.find { |l| l["forLabel"] == name } if subject [{ "subject" => sanitize(name), }, { "subject" => "FOS: " + subject["fosLabel"], "subjectScheme" => "Fields of Science and Technology (FOS)", "schemeUri" => "http://www.oecd.org/science/inno/38235147.pdf", }] else [{ "subject" => sanitize(name) }] end end |
#name_to_spdx(name) ⇒ Object
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 |
# File 'lib/commonmeta/utils.rb', line 1215 def name_to_spdx(name) spdx = JSON.load(File.read(File.("../../resources/spdx/licenses.json", __dir__))).fetch("licenses") license = spdx.find do |l| l["name"] == name || l["licenseId"] == name || l["seeAlso"].first == normalize_cc_url(name) end if license { "id" => license["licenseId"], "url" => license["seeAlso"].first }.compact else { "rights" => name } end end |
#normalize_cc_url(id) ⇒ Object
629 630 631 632 |
# File 'lib/commonmeta/utils.rb', line 629 def normalize_cc_url(id) id = normalize_url(id, https: true) NORMALIZED_LICENSES.fetch(id, id) end |
#normalize_id(id, options = {}) ⇒ Object
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 |
# File 'lib/commonmeta/utils.rb', line 584 def normalize_id(id, = {}) return nil unless id.present? # check for valid DOI doi = normalize_doi(id, ) return doi if doi.present? # check for valid HTTP uri uri = Addressable::URI.parse(id) return nil unless uri && uri.host && %w[http https].include?(uri.scheme) # clean up URL PostRank::URI.clean(id) rescue Addressable::URI::InvalidURIError nil end |
#normalize_issn(input, options = {}) ⇒ Object
pick electronic issn if there are multiple format issn as xxxx-xxxx
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 |
# File 'lib/commonmeta/utils.rb', line 652 def normalize_issn(input, = {}) content = [:content] || "__content__" issn = if input.blank? nil elsif input.is_a?(String) && [:content].nil? input elsif input.is_a?(Hash) input.fetch(content, nil) elsif input.is_a?(Array) a = input.find { |a| a["media_type"] == "electronic" } || input.first a.fetch(content, nil) end case issn.to_s.length when 9 issn when 8 issn[0..3] + "-" + issn[4..7] end end |
#normalize_licenses(licenses) ⇒ Object
find Creative Commons or OSI license in licenses array, normalize url and name
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 |
# File 'lib/commonmeta/utils.rb', line 675 def normalize_licenses(licenses) standard_licenses = Array.wrap(licenses).map do |l| URI.parse(l["url"]) end.select { |li| li.host && li.host[/(creativecommons.org|opensource.org)$/] } return licenses unless standard_licenses.present? # use HTTPS uri.scheme = "https" # use host name without subdomain uri.host = Array(/(creativecommons.org|opensource.org)/.match uri.host).last # normalize URLs if uri.host == "creativecommons.org" uri.path = uri.path.split("/")[0..-2].join("/") if uri.path.split("/").last == "legalcode" uri.path << "/" unless uri.path.end_with?("/") else uri.path = uri.path.gsub(/(-license|\.php|\.html)/, "") uri.path = uri.path.sub(/(mit|afl|apl|osl|gpl|ecl)/) { |match| match.upcase } uri.path = uri.path.sub(/(artistic|apache)/) { |match| match.titleize } uri.path = uri.path.sub(/([^0-9-]+)(-)?([1-9])?(\.)?([0-9])?$/) do m = Regexp.last_match text = m[1] if m[3].present? version = [m[3], m[5].presence || "0"].join(".") [text, version].join("-") else text end end end uri.to_s rescue URI::InvalidURIError nil end |
#normalize_orcid(orcid) ⇒ Object
634 635 636 637 638 639 640 |
# File 'lib/commonmeta/utils.rb', line 634 def normalize_orcid(orcid) orcid = validate_orcid(orcid) return nil unless orcid.present? # turn ORCID ID into URL "https://orcid.org/" + Addressable::URI.encode(orcid) end |
#normalize_ror(ror) ⇒ Object
642 643 644 645 646 647 648 |
# File 'lib/commonmeta/utils.rb', line 642 def normalize_ror(ror) ror = validate_ror(ror) return nil unless ror.present? # turn ROR ID into URL "https://ror.org/" + Addressable::URI.encode(ror) end |
#normalize_url(id, options = {}) ⇒ Object
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
# File 'lib/commonmeta/utils.rb', line 601 def normalize_url(id, = {}) return nil unless id.present? # handle info URIs return id if id.to_s.start_with?("info") # check for valid HTTP uri uri = Addressable::URI.parse(id) return nil unless uri && uri.host && %w[http https ftp].include?(uri.scheme) # optionally turn into https URL uri.scheme = "https" if [:https] # clean up URL uri.path = PostRank::URI.clean(uri.path) # optionally remove query and fragment if [:remove_query_string] uri.query = nil uri.fragment = nil end uri.to_s rescue Addressable::URI::InvalidURIError nil end |
#orcid_as_url(orcid) ⇒ Object
537 538 539 |
# File 'lib/commonmeta/utils.rb', line 537 def orcid_as_url(orcid) "https://orcid.org/#{orcid}" if orcid.present? end |
#orcid_from_url(url) ⇒ Object
533 534 535 |
# File 'lib/commonmeta/utils.rb', line 533 def orcid_from_url(url) Array(%r{\A:(http|https)://orcid\.org/(.+)}.match(url)).last end |
#parse_attributes(element, options = {}) ⇒ Object
571 572 573 574 575 576 577 578 579 580 581 582 |
# File 'lib/commonmeta/utils.rb', line 571 def parse_attributes(element, = {}) content = [:content] || "__content__" if element.is_a?(String) && [:content].nil? CGI.unescapeHTML(element) elsif element.is_a?(Hash) element.fetch(CGI.unescapeHTML(content), nil) elsif element.is_a?(Array) a = element.map { |e| e.is_a?(Hash) ? e.fetch(CGI.unescapeHTML(content), nil) : e }.uniq a = [:first] ? a.first : a.unwrap end end |
#rogue_scholar_api_url(id, _options = {}) ⇒ Object
1127 1128 1129 |
# File 'lib/commonmeta/utils.rb', line 1127 def rogue_scholar_api_url(id, = {}) "https://rogue-scholar.org/api/posts/#{id}" end |
#sanitize(text, options = {}) ⇒ Object
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 |
# File 'lib/commonmeta/utils.rb', line 947 def sanitize(text, = {}) [:tags] ||= Set.new(%w[strong em b i code pre sub sup br]) content = [:content] || "__content__" custom_scrubber = Commonmeta::WhitelistScrubber.new() if text.is_a?(String) # remove excessive internal whitespace with squish Loofah.scrub_fragment(text, custom_scrubber).to_s.squish elsif text.is_a?(Hash) sanitize(text.fetch(content, nil)) elsif text.is_a?(Array) a = text.map { |e| e.is_a?(Hash) ? sanitize(e.fetch(content, nil)) : sanitize(e) }.uniq a = [:first] ? a.first : a.unwrap end end |
#spdx_to_hsh(hsh) ⇒ Object
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 |
# File 'lib/commonmeta/utils.rb', line 1247 def spdx_to_hsh(hsh) return nil unless hsh.present? && hsh.is_a?(Hash) spdx = JSON.load(File.read(File.("../../resources/spdx/licenses.json", __dir__))).fetch("licenses") license = spdx.find { |l| l["licenseId"].casecmp?(hsh["id"]) } if license [{ "rightsIdentifier" => license["licenseId"].downcase, "rightsUri" => license["seeAlso"].first, "rights" => license["name"], "rightsIdentifierScheme" => "SPDX", "schemeUri" => "https://spdx.org/licenses/", }.compact] else [{ "rightsIdentifier" => hsh["id"], "rightsURI" => hsh["url"] }.compact] end end |
#strip_milliseconds(iso8601_time) ⇒ Object
strip milliseconds if there is a time, as it interferes with edtc parsing keep dates unchanged
1099 1100 1101 1102 1103 1104 1105 1106 1107 |
# File 'lib/commonmeta/utils.rb', line 1099 def strip_milliseconds(iso8601_time) return iso8601_time.split(" ").first if iso8601_time.to_s.include? " " return iso8601_time.split(".").first + "Z" if iso8601_time.to_s.include? "." return iso8601_time.split("+").first + "Z" if iso8601_time.to_s.include? "+" iso8601_time end |
#to_csl(element) ⇒ Object
927 928 929 930 931 932 933 934 935 |
# File 'lib/commonmeta/utils.rb', line 927 def to_csl(element) Array.wrap(element).map do |a| a["family"] = a["familyName"] a["given"] = a["givenName"] a["literal"] = a["name"] unless a["familyName"].present? a.except("nameType", "type", "@type", "id", "@id", "name", "familyName", "givenName", "affiliation", "contributorType").compact end.presence end |
#to_datacite(element, options = {}) ⇒ Object
713 714 715 716 717 718 719 720 |
# File 'lib/commonmeta/utils.rb', line 713 def to_datacite(element, = {}) a = Array.wrap(element).map do |e| e.each_with_object({}) do |(k, v), h| h[k.dasherize] = v end end [:first] ? a.unwrap : a.presence end |
#to_identifier(identifier) ⇒ Object
897 898 899 900 901 902 903 |
# File 'lib/commonmeta/utils.rb', line 897 def to_identifier(identifier) { "@type" => "PropertyValue", "propertyID" => identifier["relatedIdentifierType"], "value" => identifier["relatedIdentifier"], } end |
#to_ris(element) ⇒ Object
937 938 939 940 941 942 943 944 945 |
# File 'lib/commonmeta/utils.rb', line 937 def to_ris(element) Array.wrap(element).map do |a| if a["familyName"].present? [a["familyName"], a["givenName"]].join(", ") else a["name"] end end.unwrap end |
#to_schema_org(element) ⇒ Object
728 729 730 731 732 |
# File 'lib/commonmeta/utils.rb', line 728 def to_schema_org(element) mapping = { "type" => "@type", "id" => "@id", "title" => "name" } map_hash_keys(element: element, mapping: mapping) end |
#to_schema_org_citation(reference) ⇒ Object
791 792 793 794 795 796 797 798 799 800 |
# File 'lib/commonmeta/utils.rb', line 791 def to_schema_org_citation(reference) return nil unless reference.present? { "@type" => "CreativeWork", "@id" => reference["doi"] ? normalize_id(reference["doi"]) : nil, "name" => reference["title"], "datePublished" => reference["publicationYear"], }.compact end |
#to_schema_org_container(element, options = {}) ⇒ Object
734 735 736 737 738 739 740 741 742 743 |
# File 'lib/commonmeta/utils.rb', line 734 def to_schema_org_container(element, = {}) return nil unless element.is_a?(Hash) || (element.nil? && [:container_title].present?) issn = element["identifier"] if element["identifierType"] == "ISSN" id = issn.blank? ? element["identifier"] : nil name = [:container_title] || element["title"] type = id || name ? [:type] || element["type"] : nil { "@id" => id, "@type" => type, "name" => name, "issn" => issn }.compact end |
#to_schema_org_funder(funding_references) ⇒ Object
779 780 781 782 783 784 785 786 787 788 789 |
# File 'lib/commonmeta/utils.rb', line 779 def to_schema_org_funder(funding_references) return nil unless funding_references.present? Array.wrap(funding_references).map do |fr| { "@id" => fr["funderIdentifier"], "@type" => "Organization", "name" => fr["funderName"], }.compact end.unwrap end |
#to_schema_org_identifiers(element, _options = {}) ⇒ Object
745 746 747 748 749 750 751 752 753 |
# File 'lib/commonmeta/utils.rb', line 745 def to_schema_org_identifiers(element, = {}) Array.wrap(element).map do |ai| { "@type" => "PropertyValue", "propertyID" => ai["alternateIdentifierType"], "value" => ai["alternateIdentifier"], } end.unwrap end |
#to_schema_org_relation(related_identifiers: nil, relation_type: nil) ⇒ Object
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 |
# File 'lib/commonmeta/utils.rb', line 755 def to_schema_org_relation(related_identifiers: nil, relation_type: nil) return nil unless .present? && relation_type.present? relation_type = if relation_type == "References" %w[References Cites Documents] else [relation_type] end Array.wrap().select do |ri| relation_type.include?(ri["relationType"]) end.map do |r| if r["relatedIdentifierType"] == "ISSN" && r["relationType"] == "IsPartOf" { "@type" => "Periodical", "issn" => r["relatedIdentifier"] }.compact else { "@id" => normalize_id(r["relatedIdentifier"]), "@type" => DC_TO_SO_TRANSLATIONS[r["resourceTypeGeneral"]] || "CreativeWork", }.compact end end.unwrap end |
#to_schema_org_spatial_coverage(geo_location) ⇒ Object
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 |
# File 'lib/commonmeta/utils.rb', line 802 def to_schema_org_spatial_coverage(geo_location) return nil unless geo_location.present? Array.wrap(geo_location).each_with_object([]) do |gl, sum| if gl.fetch("geoLocationPoint", nil) sum << { "@type" => "Place", "geo" => { "@type" => "GeoCoordinates", "address" => gl["geoLocationPlace"], "latitude" => gl.dig("geoLocationPoint", "pointLatitude"), "longitude" => gl.dig("geoLocationPoint", "pointLongitude"), }, }.compact end if gl.fetch("geoLocationBox", nil) sum << { "@type" => "Place", "geo" => { "@type" => "GeoShape", "address" => gl["geoLocationPlace"], "box" => [gl.dig("geoLocationBox", "southBoundLatitude"), gl.dig("geoLocationBox", "westBoundLongitude"), gl.dig("geoLocationBox", "northBoundLatitude"), gl.dig("geoLocationBox", "eastBoundLongitude")].compact.join(" ").presence, }.compact, }.compact end if gl.fetch("geoLocationPolygon", nil) sum << { "@type" => "Place", "geo" => { "@type" => "GeoShape", "address" => gl["geoLocationPlace"], "polygon" => Array.wrap(gl.dig("geoLocationPolygon")).map do |glp| Array.wrap(glp).map do |glpp| [glpp.dig("polygonPoint", "pointLongitude"), glpp.dig("polygonPoint", "pointLatitude")].compact end.compact end.compact.presence, }, } end next unless gl.fetch("geoLocationPlace", nil) && !gl.fetch("geoLocationPoint", nil) && !gl.fetch("geoLocationBox", nil) && !gl.fetch( "geoLocationPolygon", nil ) sum << { "@type" => "Place", "geo" => { "@type" => "GeoCoordinates", "address" => gl["geoLocationPlace"], }, }.compact end.unwrap end |
#update_ghost_post_via_api(uuid) ⇒ Object
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 |
# File 'lib/commonmeta/utils.rb', line 1476 def update_ghost_post_via_api(uuid) api_key = ENV["API_KEY"] api_url = ENV["API_URL"] return nil unless uuid.present? && api_key.present? && api_url.present? # generate short lived jwt for ghost admin api ghost_jwt = generate_ghost_token(api_key) # get post url and doi from Rogue Scholar API url = json_feed_item_by_uuid_url(uuid) response = HTTP.get(url) return nil unless response.status.success? post = JSON.parse(response.body.to_s) url = post.to_h.dig("url") doi = validate_doi(post.to_h.dig("id")) doi = doi_as_url(doi) return nil unless url.present? && doi.present? # get id and updated_at from ghost api slug = url.chomp("/").split("/").last ghost_url = "#{api_url}/ghost/api/admin/posts/slug/#{slug}/" response = HTTP.auth("Ghost #{ghost_jwt}").get(ghost_url) return nil unless response.status.success? ghost_post = JSON.parse(response.body.to_s).dig("posts").first id = ghost_post.dig("id") updated_at = ghost_post.dig("updated_at") return nil unless id.present? && updated_at.present? # update post canonical_url with new doi ghost_url = "#{api_url}/ghost/api/admin/posts/#{id}/" response = HTTP.auth("Ghost #{ghost_jwt}").headers('Content-Type' => "application/json", 'Accept-Version' => 'v5').put(ghost_url, :json => { 'posts' => [{ 'canonical_url' => doi, 'updated_at' => updated_at }] }) "#{response.status} DOI #{doi} added to post #{uuid}" end |
#validate_email(str) ⇒ Object
565 566 567 568 569 |
# File 'lib/commonmeta/utils.rb', line 565 def validate_email(str) email_regex = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i parsed_emails = str.scan(email_regex) parsed_emails.first end |
#validate_orcid(orcid) ⇒ Object
541 542 543 544 |
# File 'lib/commonmeta/utils.rb', line 541 def validate_orcid(orcid) orcid = Array(%r{\A(?:(?:http|https)://(?:(?:www|sandbox)?\.)?orcid\.org/)?(\d{4}[[:space:]-]\d{4}[[:space:]-]\d{4}[[:space:]-]\d{3}[0-9X]+)\z}.match(orcid)).last orcid.gsub(/[[:space:]]/, "-") if orcid.present? end |
#validate_orcid_scheme(orcid_scheme) ⇒ Object
551 552 553 |
# File 'lib/commonmeta/utils.rb', line 551 def validate_orcid_scheme(orcid_scheme) Array(%r{\A(http|https)://(www\.)?(orcid\.org)}.match(orcid_scheme)).last end |
#validate_ror(ror) ⇒ Object
546 547 548 549 |
# File 'lib/commonmeta/utils.rb', line 546 def validate_ror(ror) ror = Array(%r{\A(?:(?:http|https)://ror\.org/)?([0-9a-z]{7}\d{2})\z}.match(ror)).last ror.gsub(/[[:space:]]/, "-") if ror.present? end |
#validate_url(str) ⇒ Object
555 556 557 558 559 560 561 562 563 |
# File 'lib/commonmeta/utils.rb', line 555 def validate_url(str) if %r{\A(?:(http|https)://(dx\.)?doi.org/)?(doi:)?(10\.\d{4,5}/.+)\z}.match?(str) "DOI" elsif %r{\A(http|https)://}.match?(str) "URL" elsif /\A(ISSN|eISSN) (\d{4}-\d{3}[0-9X]+)\z/.match?(str) "ISSN" end end |