1use crate::error::Result;
2use crate::query::facet::FacetCount;
3use crate::query::types::Type;
4use crate::query::*;
5use chrono::NaiveDate;
6use std::borrow::Cow;
7#[cfg(feature = "cli")]
8use structopt::StructOpt;
9
10#[derive(Debug, Clone)]
12pub enum WorksFilter {
13 HasFunder,
15 Funder(String),
17 Location(String),
20 Prefix(String),
22 Member(String),
24 FromIndexDate(NaiveDate),
26 UntilIndexDate(NaiveDate),
28 FromDepositDate(NaiveDate),
30 UntilDepositDate(NaiveDate),
32 FromUpdateDate(NaiveDate),
35 UntilUpdateDate(NaiveDate),
38 FromCreatedDate(NaiveDate),
40 UntilCreatedDate(NaiveDate),
42 FromPubDate(NaiveDate),
44 UntilPubDate(NaiveDate),
46 FromOnlinePubDate(NaiveDate),
48 UntilOnlinePubDate(NaiveDate),
50 FromPrintPubDate(NaiveDate),
52 UntilPrintPubDate(NaiveDate),
54 FromPostedDate(NaiveDate),
56 UntilPostedDate(NaiveDate),
58 FromAcceptedDate(NaiveDate),
60 UntilAcceptedDate(NaiveDate),
62 HasLicense,
64 LicenseUrl(String),
66 LicenseVersion(String),
68 LicenseDelay(i32),
70 HasFullText,
72 FullTextVersion(String),
74 FullTextType(String),
76 FullTextApplication(String),
78 HasReferences,
80 ReferenceVisibility(Visibility),
82 HasArchive,
84 Archive(String),
86 HasOrcid,
88 HasAuthenticatedOrcid,
90 Orcid(String),
92 Issn(String),
94 Isbn(String),
96 Type(Type),
99 Directory(String),
102 Doi(String),
104 Updates(String),
106 IsUpdate,
108 HasUpdatePolicy,
110 ContainerTitle(String),
112 CategoryName(String),
115 TypeName(String),
117 AwardNumber(String),
120 AwardFunder(String),
123 HasAssertion,
125 AssertionGroup(String),
127 Assertion(String),
129 HasAffiliation,
131 AlternativeId,
134 ArticleNumber,
136 HasAbstract,
138 HasClinicalTrialNumber,
140 ContentDomain(String),
142 HasContentDomain,
144 HasDomainRestriction,
146 HasRelation,
148 RelationType,
151 RelationObject,
153 RelationObjectType(String),
155}
156
157impl WorksFilter {
158 pub fn name(&self) -> &str {
160 match self {
161 WorksFilter::HasFunder => "has-funder",
162 WorksFilter::Funder(_) => "funder",
163 WorksFilter::Location(_) => "location",
164 WorksFilter::Prefix(_) => "prefix",
165 WorksFilter::Member(_) => "member",
166 WorksFilter::FromIndexDate(_) => "from-index-date",
167 WorksFilter::UntilIndexDate(_) => "until-index-date",
168 WorksFilter::FromDepositDate(_) => "from-deposit-date",
169 WorksFilter::UntilDepositDate(_) => "until-deposit-date",
170 WorksFilter::FromUpdateDate(_) => "from-update-date",
171 WorksFilter::UntilUpdateDate(_) => "until-update-date",
172 WorksFilter::FromCreatedDate(_) => "from-created-date",
173 WorksFilter::UntilCreatedDate(_) => "until-created-date",
174 WorksFilter::FromPubDate(_) => "from-pub-date",
175 WorksFilter::UntilPubDate(_) => "until-pub-date",
176 WorksFilter::FromOnlinePubDate(_) => "from-online-pub-date",
177 WorksFilter::UntilOnlinePubDate(_) => "until-online-pub-date",
178 WorksFilter::FromPrintPubDate(_) => "from-print-pub-date",
179 WorksFilter::UntilPrintPubDate(_) => "until-print-pub-date",
180 WorksFilter::FromPostedDate(_) => "from-posted-date",
181 WorksFilter::UntilPostedDate(_) => "until-posted-date",
182 WorksFilter::FromAcceptedDate(_) => "from-accepted-date",
183 WorksFilter::UntilAcceptedDate(_) => "until-accepted-date",
184 WorksFilter::HasLicense => "has-license",
185 WorksFilter::LicenseUrl(_) => "license.url",
186 WorksFilter::LicenseVersion(_) => "license.version",
187 WorksFilter::LicenseDelay(_) => "license.delay",
188 WorksFilter::HasFullText => "has-full-text",
189 WorksFilter::FullTextVersion(_) => "full-text.version",
190 WorksFilter::FullTextType(_) => "full-text.type",
191 WorksFilter::FullTextApplication(_) => "full-text.application",
192 WorksFilter::HasReferences => "has-references",
193 WorksFilter::ReferenceVisibility(_) => "reference-visibility",
194 WorksFilter::HasArchive => "has-archive",
195 WorksFilter::Archive(_) => "archive",
196 WorksFilter::HasOrcid => "has-orcid",
197 WorksFilter::HasAuthenticatedOrcid => "has-authenticated-orcid",
198 WorksFilter::Orcid(_) => "orcid",
199 WorksFilter::Issn(_) => "issn",
200 WorksFilter::Isbn(_) => "isbn",
201 WorksFilter::Type(_) => "type",
202 WorksFilter::Directory(_) => "directory",
203 WorksFilter::Doi(_) => "doi",
204 WorksFilter::Updates(_) => "updates",
205 WorksFilter::IsUpdate => "is-update",
206 WorksFilter::HasUpdatePolicy => "has-update-policy",
207 WorksFilter::ContainerTitle(_) => "container-title",
208 WorksFilter::CategoryName(_) => "category-name",
209 WorksFilter::TypeName(_) => "type-name",
210 WorksFilter::AwardNumber(_) => "award.number",
211 WorksFilter::AwardFunder(_) => "award.funder",
212 WorksFilter::HasAssertion => "has-assertion",
213 WorksFilter::AssertionGroup(_) => "assertion-group",
214 WorksFilter::Assertion(_) => "assertion",
215 WorksFilter::HasAffiliation => "has-affiliation",
216 WorksFilter::AlternativeId => "alternative-id",
217 WorksFilter::ArticleNumber => "article-number",
218 WorksFilter::HasAbstract => "has-abstract",
219 WorksFilter::HasClinicalTrialNumber => "has-clinical-trial-number",
220 WorksFilter::ContentDomain(_) => "content-domain",
221 WorksFilter::HasContentDomain => "has-content-domain",
222 WorksFilter::HasDomainRestriction => "has-domain-restriction",
223 WorksFilter::HasRelation => "has-relation",
224 WorksFilter::RelationType => "relation.type",
225 WorksFilter::RelationObject => "relation.object",
226 WorksFilter::RelationObjectType(_) => "relation.object-type",
227 }
228 }
229}
230
231impl ParamFragment for WorksFilter {
232 fn key(&self) -> Cow<'_, str> {
233 Cow::Borrowed(self.name())
234 }
235
236 fn value(&self) -> Option<Cow<'_, str>> {
237 match self {
238 WorksFilter::Funder(s)
239 | WorksFilter::Location(s)
240 | WorksFilter::Prefix(s)
241 | WorksFilter::Member(s)
242 | WorksFilter::LicenseUrl(s)
243 | WorksFilter::LicenseVersion(s)
244 | WorksFilter::FullTextVersion(s)
245 | WorksFilter::FullTextType(s)
246 | WorksFilter::FullTextApplication(s)
247 | WorksFilter::Archive(s)
248 | WorksFilter::Orcid(s)
249 | WorksFilter::Issn(s)
250 | WorksFilter::Isbn(s)
251 | WorksFilter::Directory(s)
252 | WorksFilter::Doi(s)
253 | WorksFilter::Updates(s)
254 | WorksFilter::ContainerTitle(s)
255 | WorksFilter::CategoryName(s)
256 | WorksFilter::AwardNumber(s)
257 | WorksFilter::TypeName(s)
258 | WorksFilter::AwardFunder(s)
259 | WorksFilter::AssertionGroup(s)
260 | WorksFilter::Assertion(s)
261 | WorksFilter::ContentDomain(s)
262 | WorksFilter::RelationObjectType(s) => Some(Cow::Borrowed(s.as_str())),
263 WorksFilter::ReferenceVisibility(vis) => Some(Cow::Borrowed(vis.as_str())),
264 WorksFilter::FromIndexDate(d)
265 | WorksFilter::UntilIndexDate(d)
266 | WorksFilter::FromDepositDate(d)
267 | WorksFilter::UntilDepositDate(d)
268 | WorksFilter::FromUpdateDate(d)
269 | WorksFilter::UntilUpdateDate(d)
270 | WorksFilter::FromCreatedDate(d)
271 | WorksFilter::UntilCreatedDate(d)
272 | WorksFilter::FromPubDate(d)
273 | WorksFilter::UntilPubDate(d)
274 | WorksFilter::FromOnlinePubDate(d)
275 | WorksFilter::UntilOnlinePubDate(d)
276 | WorksFilter::FromPrintPubDate(d)
277 | WorksFilter::UntilPrintPubDate(d)
278 | WorksFilter::FromPostedDate(d)
279 | WorksFilter::UntilPostedDate(d)
280 | WorksFilter::FromAcceptedDate(d)
281 | WorksFilter::UntilAcceptedDate(d) => {
282 Some(Cow::Owned(d.format("%Y-%m-%d").to_string()))
283 }
284 WorksFilter::Type(t) => Some(Cow::Borrowed(t.id())),
285 _ => Some(Cow::Borrowed("true")),
286 }
287 }
288}
289
290impl Filter for WorksFilter {}
291
292#[derive(Debug, Clone)]
294#[cfg_attr(feature = "cli", derive(StructOpt))]
295pub struct FieldQuery {
296 pub name: String,
298 pub value: String,
300}
301
302impl FieldQuery {
303 pub fn title(title: &str) -> Self {
305 Self {
306 name: "title".to_string(),
307 value: title.to_string(),
308 }
309 }
310
311 pub fn container_title(container_title: &str) -> Self {
313 Self {
314 name: "container-title".to_string(),
315 value: container_title.to_string(),
316 }
317 }
318 pub fn author(author: &str) -> Self {
320 Self {
321 name: "author".to_string(),
322 value: author.to_string(),
323 }
324 }
325 pub fn editor(editor: &str) -> Self {
327 Self {
328 name: "editor".to_string(),
329 value: editor.to_string(),
330 }
331 }
332 pub fn chair(chair: &str) -> Self {
334 Self {
335 name: "chair".to_string(),
336 value: chair.to_string(),
337 }
338 }
339 pub fn translator(translator: &str) -> Self {
341 Self {
342 name: "translator".to_string(),
343 value: translator.to_string(),
344 }
345 }
346 pub fn contributor(contributor: &str) -> Self {
348 Self {
349 name: "contributor".to_string(),
350 value: contributor.to_string(),
351 }
352 }
353 pub fn bibliographic(bibliographic: &str) -> Self {
356 Self {
357 name: "bibliographic".to_string(),
358 value: bibliographic.to_string(),
359 }
360 }
361 pub fn affiliation(affiliation: &str) -> Self {
363 Self {
364 name: "affiliation".to_string(),
365 value: affiliation.to_string(),
366 }
367 }
368}
369
370impl CrossrefQueryParam for FieldQuery {
371 fn param_key(&self) -> Cow<'_, str> {
372 Cow::Borrowed(&self.name)
373 }
374 fn param_value(&self) -> Option<Cow<'_, str>> {
375 Some(Cow::Owned(format_query(&self.value)))
376 }
377}
378
379#[derive(Debug, Clone)]
381pub enum WorkResultControl {
382 Standard(ResultControl),
384 Cursor {
386 token: Option<String>,
388 rows: Option<usize>,
390 },
391}
392
393impl WorkResultControl {
394 pub fn new_cursor() -> Self {
396 WorkResultControl::Cursor {
397 token: None,
398 rows: None,
399 }
400 }
401
402 pub fn cursor(token: &str) -> Self {
404 WorkResultControl::Cursor {
405 token: Some(token.to_string()),
406 rows: None,
407 }
408 }
409}
410
411impl Default for WorkResultControl {
412 fn default() -> Self {
413 WorkResultControl::new_cursor()
414 }
415}
416
417impl CrossrefQueryParam for WorkResultControl {
418 fn param_key(&self) -> Cow<'_, str> {
419 match self {
420 WorkResultControl::Standard(s) => s.param_key(),
421 WorkResultControl::Cursor { token, .. } => Cow::Owned(format!(
422 "cursor={}",
423 token.as_ref().map(String::as_str).unwrap_or("*")
424 )),
425 }
426 }
427
428 fn param_value(&self) -> Option<Cow<'_, str>> {
429 match self {
430 WorkResultControl::Standard(s) => s.param_value(),
431 WorkResultControl::Cursor { rows, .. } => {
432 rows.map(|r| Cow::Owned(format!("rows={}", r)))
433 }
434 }
435 }
436}
437#[derive(Debug, Clone)]
458pub enum Works {
459 Identifier(String),
461 Query(WorksQuery),
463 Agency(String),
465}
466
467impl Works {
468 pub fn doi(doi: &str) -> Self {
470 Works::Identifier(doi.to_string())
471 }
472 pub fn agency_for_doi(doi: &str) -> Self {
474 Works::Agency(doi.to_string())
475 }
476}
477
478impl CrossrefRoute for Works {
479 fn route(&self) -> Result<String> {
480 match self {
481 Works::Identifier(s) => Ok(format!("{}/{}", Component::Works.route()?, s)),
482 Works::Agency(s) => Ok(format!("{}/{}/agency", Component::Works.route()?, s)),
483 Works::Query(query) => query.route(),
484 }
485 }
486}
487
488impl CrossrefQuery for Works {
489 fn resource_component(self) -> ResourceComponent {
490 ResourceComponent::Works(self)
491 }
492}
493
494#[derive(Debug, Clone)]
496#[allow(missing_docs)]
497pub enum WorkListQuery {
498 Works(WorksQuery),
500 Combined {
502 primary_component: Component,
503 ident: WorksIdentQuery,
504 },
505}
506
507impl WorkListQuery {
508 pub fn query(&self) -> &WorksQuery {
510 match self {
511 WorkListQuery::Works(query) => query,
512 WorkListQuery::Combined { ident, .. } => &ident.query,
513 }
514 }
515
516 pub fn query_mut(&mut self) -> &mut WorksQuery {
518 match self {
519 WorkListQuery::Works(query) => query,
520 WorkListQuery::Combined { ident, .. } => &mut ident.query,
521 }
522 }
523}
524
525impl From<WorksQuery> for WorkListQuery {
526 fn from(query: WorksQuery) -> WorkListQuery {
527 WorkListQuery::Works(query)
528 }
529}
530
531impl<T: ToString> From<T> for WorkListQuery {
532 fn from(term: T) -> Self {
533 WorkListQuery::Works(WorksQuery::new(term))
534 }
535}
536
537impl CrossrefRoute for WorkListQuery {
538 fn route(&self) -> Result<String> {
539 match self {
540 WorkListQuery::Works(query) => query.route(),
541 WorkListQuery::Combined {
542 primary_component,
543 ident,
544 } => Ok(format!(
545 "{}/{}{}",
546 primary_component.route()?,
547 ident.id,
548 ident.query.route()?
549 )),
550 }
551 }
552}
553
554impl CrossrefQuery for WorkListQuery {
555 fn resource_component(self) -> ResourceComponent {
556 match self {
557 WorkListQuery::Works(query) => ResourceComponent::Works(Works::Query(query)),
558 WorkListQuery::Combined {
559 primary_component,
560 ident,
561 } => match primary_component {
562 Component::Funders => ResourceComponent::Funders(Funders::Works(ident)),
563 Component::Journals => ResourceComponent::Journals(Journals::Works(ident)),
564 Component::Members => ResourceComponent::Members(Members::Works(ident)),
565 Component::Prefixes => ResourceComponent::Prefixes(Prefixes::Works(ident)),
566 Component::Types => ResourceComponent::Types(Types::Works(ident)),
567 Component::Works => ResourceComponent::Works(Works::Query(ident.query)),
568 },
569 }
570 }
571}
572
573#[derive(Debug, Clone)]
593pub struct WorksIdentQuery {
594 pub id: String,
596 pub query: WorksQuery,
598}
599
600impl WorksIdentQuery {
601 pub fn new<T: Into<String>>(id: T, query: WorksQuery) -> Self {
603 WorksIdentQuery {
604 id: id.into(),
605 query,
606 }
607 }
608}
609
610pub trait WorksCombiner {
612 fn primary_component() -> Component;
614
615 fn ident_query(ident: WorksIdentQuery) -> Self;
617
618 fn combined_route(ident: &WorksIdentQuery) -> Result<String> {
620 Ok(format!(
621 "{}/{}{}",
622 Self::primary_component().route()?,
623 ident.id,
624 ident.query.route()?
625 ))
626 }
627
628 fn work_list_query(ident: WorksIdentQuery) -> WorkListQuery {
630 WorkListQuery::Combined {
631 primary_component: Self::primary_component(),
632 ident,
633 }
634 }
635}
636
637macro_rules! impl_combiner {
638 ($($name:ident,)*) => {
639 $(
640 impl WorksCombiner for $name {
641 fn primary_component() -> Component {
642 Component::$name
643 }
644
645 fn ident_query(ident: WorksIdentQuery) -> Self {
646 $name::Works(ident)
647 }
648 }
649 )+
650 };
651}
652
653impl_combiner!(Journals, Funders, Members, Prefixes, Types,);
654
655impl WorksQuery {
656 pub fn empty() -> Self {
658 WorksQuery::default()
659 }
660
661 pub fn random(len: usize) -> Self {
664 WorksQuery::default().sample(len)
665 }
666
667 pub fn new<T: ToString>(query: T) -> Self {
669 WorksQuery::empty().query(query)
670 }
671
672 pub fn sample(mut self, len: usize) -> Self {
674 self.sample = Some(len);
675 self
676 }
677
678 pub fn query<T: ToString>(mut self, query: T) -> Self {
680 self.free_form_queries.push(query.to_string());
681 self
682 }
683
684 pub fn queries<T: ToString>(mut self, queries: &[T]) -> Self {
695 self.free_form_queries
696 .extend(queries.iter().map(T::to_string));
697 self
698 }
699
700 pub fn field_query(mut self, query: FieldQuery) -> Self {
702 self.field_queries.push(query);
703 self
704 }
705
706 pub fn field_queries(mut self, queries: Vec<FieldQuery>) -> Self {
713 self.field_queries.extend(queries);
714 self
715 }
716
717 pub fn filter(mut self, filter: WorksFilter) -> Self {
719 self.filter.push(filter);
720 self
721 }
722
723 pub fn sort(mut self, sort: Sort) -> Self {
725 self.sort = Some(sort);
726 self
727 }
728
729 pub fn order(mut self, order: Order) -> Self {
731 self.order = Some(order);
732 self
733 }
734
735 pub fn facet(mut self, facet: FacetCount) -> Self {
737 self.facets.push(facet);
738 self
739 }
740
741 pub fn next_cursor(mut self, cursor: &str) -> Self {
743 let rows = match self.result_control {
744 Some(WorkResultControl::Standard(ResultControl::Rows(rows))) => Some(rows),
745 _ => None,
746 };
747 self.result_control = Some(WorkResultControl::Cursor {
748 token: Some(cursor.to_string()),
749 rows,
750 });
751 self
752 }
753
754 pub fn new_cursor(mut self) -> Self {
756 self.result_control = Some(WorkResultControl::new_cursor());
757 self
758 }
759 pub fn result_control(mut self, result_control: WorkResultControl) -> Self {
761 self.result_control = Some(result_control);
762 self
763 }
764
765 pub fn into_combined<W: WorksCombiner>(self, id: &str) -> W {
775 W::ident_query(self.into_ident(id))
776 }
777
778 pub fn into_ident(self, id: &str) -> WorksIdentQuery {
780 WorksIdentQuery::new(id, self)
781 }
782
783 pub fn into_combined_query<W: WorksCombiner>(self, id: &str) -> WorkListQuery {
797 W::work_list_query(self.into_ident(id))
798 }
799}
800
801#[derive(Debug, Clone, Default)]
814pub struct WorksQuery {
815 pub free_form_queries: Vec<String>,
817 pub field_queries: Vec<FieldQuery>,
819 pub filter: Vec<WorksFilter>,
821 pub sort: Option<Sort>,
823 pub order: Option<Order>,
825 pub facets: Vec<FacetCount>,
827 pub result_control: Option<WorkResultControl>,
829 pub sample: Option<usize>,
832}
833
834impl CrossrefRoute for WorksQuery {
835 fn route(&self) -> Result<String> {
836 let mut params = Vec::new();
837
838 if let Some(sample) = self.sample {
839 return Ok(format!("sample={}", sample));
840 }
841
842 if !self.free_form_queries.is_empty() {
843 params.push(Cow::Owned(format!(
844 "query={}",
845 format_queries(&self.free_form_queries)
846 )));
847 }
848 if !self.field_queries.is_empty() {
849 params.extend(self.field_queries.iter().map(CrossrefQueryParam::param))
850 }
851 if !self.filter.is_empty() {
852 params.push(self.filter.param());
853 }
854 if !self.facets.is_empty() {
855 params.push(self.facets.param());
856 }
857 if let Some(sort) = &self.sort {
858 params.push(sort.param());
859 }
860 if let Some(order) = &self.order {
861 params.push(order.param());
862 }
863 if let Some(rc) = &self.result_control {
864 params.push(rc.param());
865 }
866
867 Ok(format!(
868 "{}?{}",
869 Component::Works.route()?,
870 params.join("&")
871 ))
872 }
873}
874
875impl CrossrefParams for WorksQuery {
876 type Filter = WorksFilter;
877
878 fn query_terms(&self) -> &[String] {
879 &self.free_form_queries
880 }
881 fn filters(&self) -> &[Self::Filter] {
882 &self.filter
883 }
884 fn sort(&self) -> Option<&Sort> {
885 self.sort.as_ref()
886 }
887 fn order(&self) -> Option<&Order> {
888 self.order.as_ref()
889 }
890 fn facets(&self) -> &[FacetCount] {
891 &self.facets
892 }
893 fn result_control(&self) -> Option<&ResultControl> {
894 if let Some(WorkResultControl::Standard(ref std)) = self.result_control {
895 Some(std)
896 } else {
897 None
898 }
899 }
900}
901
902#[cfg(test)]
903mod tests {
904 use super::*;
905
906 #[test]
907 fn serialize_works_ident() {
908 let works = Works::doi("10.1037/0003-066X.59.1.29");
909
910 assert_eq!("/works/10.1037/0003-066X.59.1.29", &works.route().unwrap())
911 }
912
913 #[test]
914 fn filter_names_have_no_whitespace() {
915 let filters = vec![
917 WorksFilter::HasFunder,
918 WorksFilter::HasLicense,
919 WorksFilter::HasFullText,
920 WorksFilter::HasReferences,
921 WorksFilter::HasArchive,
922 WorksFilter::HasOrcid,
923 WorksFilter::HasAuthenticatedOrcid,
924 WorksFilter::IsUpdate,
925 WorksFilter::HasUpdatePolicy,
926 WorksFilter::HasAssertion,
927 WorksFilter::HasAffiliation,
928 WorksFilter::AlternativeId,
929 WorksFilter::ArticleNumber,
930 WorksFilter::HasAbstract,
931 WorksFilter::HasClinicalTrialNumber,
932 WorksFilter::HasContentDomain,
933 WorksFilter::HasDomainRestriction,
934 WorksFilter::HasRelation,
935 WorksFilter::RelationType,
936 WorksFilter::RelationObject,
937 ];
938 for f in &filters {
939 let name = f.name();
940 assert_eq!(
941 name,
942 name.trim(),
943 "Filter name {:?} contains leading/trailing whitespace",
944 name
945 );
946 }
947 }
948}