1use std::time::SystemTime;
11
12use serde::Deserialize;
13use serde_json::{Map, Value};
14
15use crate::error::{Error, Result};
16use crate::time::{format_date, format_utc_millis};
17use crate::version::PAYLOAD_VERSION;
18use crate::vocab::{
19 CompanyRole, EventDirection, EventType, Importance, IncludeBlock, OrderBy, SortOrder,
20 SourceType,
21};
22
23#[derive(Debug, Clone, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum DateInput {
30 Time(SystemTime),
32 Date {
34 year: i32,
36 month: u32,
38 day: u32,
40 },
41 Text(String),
43}
44
45impl DateInput {
46 pub fn date(year: i32, month: u32, day: u32) -> Self {
48 DateInput::Date { year, month, day }
49 }
50
51 fn to_wire(&self, key: &str) -> Result<String> {
52 match self {
53 DateInput::Time(t) => format_utc_millis(*t).ok_or_else(|| {
54 Error::validation(
55 format!("{key} is outside the years 0000 to 9999"),
56 Some(key),
57 )
58 }),
59 DateInput::Date { year, month, day } => format_date(*year, *month, *day)
60 .ok_or_else(|| Error::validation(format!("{key} is not a valid date"), Some(key))),
61 DateInput::Text(s) => Ok(s.clone()),
62 }
63 }
64}
65
66impl From<SystemTime> for DateInput {
67 fn from(value: SystemTime) -> Self {
68 DateInput::Time(value)
69 }
70}
71
72impl From<&str> for DateInput {
73 fn from(value: &str) -> Self {
74 DateInput::Text(value.to_owned())
75 }
76}
77
78impl From<String> for DateInput {
79 fn from(value: String) -> Self {
80 DateInput::Text(value)
81 }
82}
83
84impl<'de> Deserialize<'de> for DateInput {
85 fn deserialize<D: serde::Deserializer<'de>>(
86 deserializer: D,
87 ) -> std::result::Result<Self, D::Error> {
88 Ok(DateInput::Text(String::deserialize(deserializer)?))
89 }
90}
91
92fn strings<I, S>(values: I) -> Vec<String>
93where
94 I: IntoIterator<Item = S>,
95 S: Into<String>,
96{
97 values.into_iter().map(Into::into).collect()
98}
99
100fn vocab<T, I, S>(values: I) -> Vec<T>
101where
102 I: IntoIterator<Item = S>,
103 S: Into<T>,
104{
105 values.into_iter().map(Into::into).collect()
106}
107
108macro_rules! string_setters {
109 ($( $(#[$m:meta])* $name:ident ),* $(,)?) => {
110 $(
111 $(#[$m])*
112 pub fn $name(mut self, value: impl Into<String>) -> Self {
113 self.$name = Some(value.into());
114 self
115 }
116 )*
117 };
118}
119
120macro_rules! list_setters {
121 ($( $(#[$m:meta])* $name:ident ),* $(,)?) => {
122 $(
123 $(#[$m])*
124 pub fn $name<I, S>(mut self, values: I) -> Self
125 where
126 I: IntoIterator<Item = S>,
127 S: Into<String>,
128 {
129 self.$name = Some(strings(values));
130 self
131 }
132 )*
133 };
134}
135
136macro_rules! vocab_list_setters {
137 ($( $(#[$m:meta])* $name:ident : $ty:ty ),* $(,)?) => {
138 $(
139 $(#[$m])*
140 pub fn $name<I, S>(mut self, values: I) -> Self
141 where
142 I: IntoIterator<Item = S>,
143 S: Into<$ty>,
144 {
145 self.$name = Some(vocab(values));
146 self
147 }
148 )*
149 };
150}
151
152macro_rules! bool_setters {
153 ($( $(#[$m:meta])* $name:ident ),* $(,)?) => {
154 $(
155 $(#[$m])*
156 pub fn $name(mut self, value: bool) -> Self {
157 self.$name = Some(value);
158 self
159 }
160 )*
161 };
162}
163
164fn from_json_error(err: serde_json::Error, what: &str) -> Error {
165 let text = err.to_string();
166 if let Some(rest) = text.strip_prefix("unknown field `") {
167 let key = rest.split('`').next().unwrap_or_default();
168 return Error::validation(
169 format!(
170 "unknown {what} parameter \"{key}\"; the server would ignore it silently. \
171 See https://docs.finlight.me for the v3 parameters."
172 ),
173 Some(key),
174 );
175 }
176 Error::validation(format!("invalid {what} parameters: {text}"), None)
177}
178
179fn check_include(include: &Option<Vec<IncludeBlock>>) -> Result<Option<Vec<IncludeBlock>>> {
180 match include {
181 Some(list) if list.len() > 3 => Err(Error::validation(
182 "include takes at most 3 values",
183 Some("include"),
184 )),
185 Some(list) if list.is_empty() => Ok(None),
186 other => Ok(other.clone()),
187 }
188}
189
190fn put_str(map: &mut Map<String, Value>, key: &str, value: &Option<String>) {
191 if let Some(v) = value {
192 map.insert(key.to_owned(), Value::String(v.clone()));
193 }
194}
195
196fn put_list<T: AsRef<str>>(map: &mut Map<String, Value>, key: &str, value: &Option<Vec<T>>) {
197 if let Some(list) = value {
198 map.insert(
199 key.to_owned(),
200 Value::Array(
201 list.iter()
202 .map(|v| Value::String(v.as_ref().to_owned()))
203 .collect(),
204 ),
205 );
206 }
207}
208
209fn put_bool(map: &mut Map<String, Value>, key: &str, value: Option<bool>) {
210 if let Some(v) = value {
211 map.insert(key.to_owned(), Value::Bool(v));
212 }
213}
214
215#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
226#[serde(rename_all = "camelCase", deny_unknown_fields)]
227#[non_exhaustive]
228pub struct SearchParams {
229 pub query: Option<String>,
231 pub sources: Option<Vec<String>>,
233 pub opt_in_sources: Option<Vec<String>>,
235 pub exclude_sources: Option<Vec<String>>,
237 pub source_types: Option<Vec<SourceType>>,
239 pub exclude_source_types: Option<Vec<SourceType>>,
241 pub from: Option<DateInput>,
243 pub to: Option<DateInput>,
245 pub languages: Option<Vec<String>>,
247 pub tickers: Option<Vec<String>>,
249 pub countries: Option<Vec<String>>,
251 pub categories: Option<Vec<String>>,
253 pub has_content: Option<bool>,
255 pub roles: Option<Vec<CompanyRole>>,
257 pub min_relevance: Option<f64>,
259 pub event_types: Option<Vec<EventType>>,
261 pub event_directions: Option<Vec<EventDirection>>,
263 pub min_importance: Option<Importance>,
265 pub sectors: Option<Vec<String>>,
267 pub company_countries: Option<Vec<String>>,
269 pub exchanges: Option<Vec<String>>,
271 pub order_by: Option<OrderBy>,
273 pub order: Option<SortOrder>,
275 pub limit: Option<u32>,
277 pub cursor: Option<String>,
279 pub include: Option<Vec<IncludeBlock>>,
281}
282
283impl SearchParams {
284 pub fn new() -> Self {
286 Self::default()
287 }
288
289 pub fn from_json(json: &str) -> Result<Self> {
292 serde_json::from_str(json).map_err(|e| from_json_error(e, "search"))
293 }
294
295 string_setters! {
296 query,
298 cursor,
300 }
301
302 list_setters! {
303 sources,
305 opt_in_sources,
307 exclude_sources,
309 languages,
311 tickers,
313 countries,
315 categories,
317 sectors,
319 company_countries,
321 exchanges,
323 }
324
325 vocab_list_setters! {
326 source_types: SourceType,
328 exclude_source_types: SourceType,
330 roles: CompanyRole,
332 event_types: EventType,
334 event_directions: EventDirection,
336 include: IncludeBlock,
338 }
339
340 bool_setters! {
341 has_content,
343 }
344
345 pub fn from(mut self, value: impl Into<DateInput>) -> Self {
347 self.from = Some(value.into());
348 self
349 }
350
351 pub fn to(mut self, value: impl Into<DateInput>) -> Self {
353 self.to = Some(value.into());
354 self
355 }
356
357 pub fn min_relevance(mut self, value: f64) -> Self {
359 self.min_relevance = Some(value);
360 self
361 }
362
363 pub fn min_importance(mut self, value: impl Into<Importance>) -> Self {
365 self.min_importance = Some(value.into());
366 self
367 }
368
369 pub fn order_by(mut self, value: impl Into<OrderBy>) -> Self {
371 self.order_by = Some(value.into());
372 self
373 }
374
375 pub fn order(mut self, value: impl Into<SortOrder>) -> Self {
377 self.order = Some(value.into());
378 self
379 }
380
381 pub fn limit(mut self, value: u32) -> Self {
383 self.limit = Some(value);
384 self
385 }
386
387 pub(crate) fn to_body(&self) -> Result<Map<String, Value>> {
389 let mut m = Map::new();
390 put_str(&mut m, "query", &self.query);
391 put_list(&mut m, "sources", &self.sources);
392 put_list(&mut m, "optInSources", &self.opt_in_sources);
393 put_list(&mut m, "excludeSources", &self.exclude_sources);
394 put_list(&mut m, "sourceTypes", &self.source_types);
395 put_list(&mut m, "excludeSourceTypes", &self.exclude_source_types);
396 if let Some(from) = &self.from {
397 m.insert("from".into(), Value::String(from.to_wire("from")?));
398 }
399 if let Some(to) = &self.to {
400 m.insert("to".into(), Value::String(to.to_wire("to")?));
401 }
402 if let Some(languages) = &self.languages {
403 if languages.is_empty() {
404 return Err(Error::validation(
405 "languages must not be empty; leave it out for the server default",
406 Some("languages"),
407 ));
408 }
409 }
410 put_list(&mut m, "languages", &self.languages);
411 put_list(&mut m, "tickers", &self.tickers);
412 put_list(&mut m, "countries", &self.countries);
413 put_list(&mut m, "categories", &self.categories);
414 put_bool(&mut m, "hasContent", self.has_content);
415 put_list(&mut m, "roles", &self.roles);
416 if let Some(v) = self.min_relevance {
417 if !v.is_finite() || !(0.0..=1.0).contains(&v) {
418 return Err(Error::validation(
419 "minRelevance must be between 0 and 1",
420 Some("minRelevance"),
421 ));
422 }
423 let number = serde_json::Number::from_f64(v).ok_or_else(|| {
424 Error::validation("minRelevance must be a finite number", Some("minRelevance"))
425 })?;
426 m.insert("minRelevance".into(), Value::Number(number));
427 }
428 put_list(&mut m, "eventTypes", &self.event_types);
429 put_list(&mut m, "eventDirections", &self.event_directions);
430 if let Some(v) = &self.min_importance {
431 m.insert("minImportance".into(), Value::String(v.as_str().to_owned()));
432 }
433 put_list(&mut m, "sectors", &self.sectors);
434 put_list(&mut m, "companyCountries", &self.company_countries);
435 put_list(&mut m, "exchanges", &self.exchanges);
436 if let Some(v) = &self.order_by {
437 m.insert("orderBy".into(), Value::String(v.as_str().to_owned()));
438 }
439 if let Some(v) = &self.order {
440 m.insert("order".into(), Value::String(v.as_str().to_owned()));
441 }
442 if let Some(limit) = self.limit {
443 if !(1..=100).contains(&limit) {
444 return Err(Error::validation(
445 "limit must be between 1 and 100",
446 Some("limit"),
447 ));
448 }
449 m.insert("limit".into(), Value::from(limit));
450 }
451 if let Some(cursor) = &self.cursor {
452 if cursor.is_empty() {
453 return Err(Error::validation(
454 "cursor must not be empty",
455 Some("cursor"),
456 ));
457 }
458 m.insert("cursor".into(), Value::String(cursor.clone()));
459 }
460 put_list(&mut m, "include", &check_include(&self.include)?);
461 Ok(m)
462 }
463}
464
465#[derive(Debug, Clone, Default, PartialEq, Eq)]
467#[non_exhaustive]
468pub struct GetArticleOptions {
469 pub include: Option<Vec<IncludeBlock>>,
471}
472
473impl GetArticleOptions {
474 pub fn new() -> Self {
476 Self::default()
477 }
478
479 pub fn include<I, S>(mut self, values: I) -> Self
481 where
482 I: IntoIterator<Item = S>,
483 S: Into<IncludeBlock>,
484 {
485 self.include = Some(vocab(values));
486 self
487 }
488
489 pub(crate) fn include_query(&self) -> Result<Option<String>> {
490 Ok(check_include(&self.include)?.map(|list| {
491 list.iter()
492 .map(IncludeBlock::as_str)
493 .collect::<Vec<_>>()
494 .join(",")
495 }))
496 }
497}
498
499#[derive(Debug, Clone, PartialEq, Eq)]
501#[non_exhaustive]
502pub struct CompanySearchParams {
503 pub q: String,
505 pub mic: Option<String>,
507}
508
509impl CompanySearchParams {
510 pub fn new(q: impl Into<String>) -> Self {
512 CompanySearchParams {
513 q: q.into(),
514 mic: None,
515 }
516 }
517
518 pub fn mic(mut self, value: impl Into<String>) -> Self {
520 self.mic = Some(value.into());
521 self
522 }
523
524 pub(crate) fn to_query(&self) -> Result<Vec<(&'static str, String)>> {
525 let q_len = self.q.chars().count();
526 if self.q.trim().is_empty() {
528 return Err(Error::validation("q must not be empty", Some("q")));
529 }
530 if q_len > 200 {
531 return Err(Error::validation(
532 "q must be at most 200 characters",
533 Some("q"),
534 ));
535 }
536 let mut query = vec![("q", self.q.clone())];
537 if let Some(mic) = &self.mic {
538 let len = mic.chars().count();
539 if len == 0 {
540 return Err(Error::validation("mic must not be empty", Some("mic")));
541 }
542 if len > 32 {
543 return Err(Error::validation(
544 "mic must be at most 32 characters",
545 Some("mic"),
546 ));
547 }
548 query.push(("mic", mic.clone()));
549 }
550 Ok(query)
551 }
552}
553
554pub(crate) fn check_company_id(id: i64, name: &str) -> Result<i64> {
555 if !(1..=(1i64 << 53) - 1).contains(&id) {
556 return Err(Error::validation(
557 format!("{name} must be an integer from 1 to 2^53-1"),
558 Some(name),
559 ));
560 }
561 Ok(id)
562}
563
564pub(crate) fn company_ids_query(ids: &[i64]) -> Result<String> {
565 if ids.is_empty() || ids.len() > 10 {
566 return Err(Error::validation("ids takes 1 to 10 values", Some("ids")));
567 }
568 let mut out = Vec::with_capacity(ids.len());
569 for id in ids {
570 out.push(check_company_id(*id, "ids")?.to_string());
571 }
572 Ok(out.join(","))
573}
574
575#[derive(Debug, Clone, Default, PartialEq, Eq)]
577#[non_exhaustive]
578pub struct SearchAllOptions {
579 pub max_pages: Option<u32>,
581}
582
583impl SearchAllOptions {
584 pub fn new() -> Self {
586 Self::default()
587 }
588
589 pub fn max_pages(mut self, value: u32) -> Self {
591 self.max_pages = Some(value);
592 self
593 }
594}
595
596#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
601#[serde(rename_all = "camelCase", deny_unknown_fields)]
602#[non_exhaustive]
603pub struct StreamParams {
604 pub query: Option<String>,
606 pub sources: Option<Vec<String>>,
608 pub exclude_sources: Option<Vec<String>>,
610 pub opt_in_sources: Option<Vec<String>>,
612 pub language: Option<String>,
614 pub tickers: Option<Vec<String>>,
616 pub countries: Option<Vec<String>>,
618 pub categories: Option<Vec<String>>,
620 pub source_types: Option<Vec<SourceType>>,
622 pub exclude_source_types: Option<Vec<SourceType>>,
624 pub exclude_empty_content: Option<bool>,
626 pub include_updates: Option<bool>,
628 pub include: Option<Vec<IncludeBlock>>,
630}
631
632impl StreamParams {
633 pub fn new() -> Self {
635 Self::default()
636 }
637
638 pub fn from_json(json: &str) -> Result<Self> {
640 serde_json::from_str(json).map_err(|e| from_json_error(e, "stream"))
641 }
642
643 string_setters! {
644 query,
646 language,
648 }
649
650 list_setters! {
651 sources,
653 exclude_sources,
655 opt_in_sources,
657 tickers,
659 countries,
661 categories,
663 }
664
665 vocab_list_setters! {
666 source_types: SourceType,
668 exclude_source_types: SourceType,
670 include: IncludeBlock,
672 }
673
674 bool_setters! {
675 exclude_empty_content,
677 include_updates,
679 }
680
681 pub(crate) fn to_frame(&self) -> Result<Map<String, Value>> {
682 let mut m = Map::new();
683 m.insert("payloadVersion".into(), Value::from(PAYLOAD_VERSION));
684 put_list(&mut m, "include", &check_include(&self.include)?);
685 put_str(&mut m, "query", &self.query);
686 put_list(&mut m, "sources", &self.sources);
687 put_list(&mut m, "excludeSources", &self.exclude_sources);
688 put_list(&mut m, "optInSources", &self.opt_in_sources);
689 put_str(&mut m, "language", &self.language);
690 put_list(&mut m, "tickers", &self.tickers);
691 put_list(&mut m, "countries", &self.countries);
692 put_list(&mut m, "categories", &self.categories);
693 put_list(&mut m, "sourceTypes", &self.source_types);
694 put_list(&mut m, "excludeSourceTypes", &self.exclude_source_types);
695 put_bool(&mut m, "excludeEmptyContent", self.exclude_empty_content);
696 put_bool(&mut m, "includeUpdates", self.include_updates);
697 Ok(m)
698 }
699}
700
701#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
704#[serde(rename_all = "camelCase", deny_unknown_fields)]
705#[non_exhaustive]
706pub struct RawStreamParams {
707 pub query: Option<String>,
709 pub sources: Option<Vec<String>>,
711 pub exclude_sources: Option<Vec<String>>,
713 pub source_types: Option<Vec<SourceType>>,
715 pub exclude_source_types: Option<Vec<SourceType>>,
717 pub language: Option<String>,
719 pub include_updates: Option<bool>,
721}
722
723impl RawStreamParams {
724 pub fn new() -> Self {
726 Self::default()
727 }
728
729 pub fn from_json(json: &str) -> Result<Self> {
732 serde_json::from_str(json).map_err(|e| {
733 let err = from_json_error(e, "raw stream");
734 match &err {
735 Error::Validation(v) if v.param() == Some("include") => Error::validation(
736 "raw streams have no include: raw delivers the article skeleton only",
737 Some("include"),
738 ),
739 _ => err,
740 }
741 })
742 }
743
744 string_setters! {
745 query,
747 language,
749 }
750
751 list_setters! {
752 sources,
754 exclude_sources,
756 }
757
758 vocab_list_setters! {
759 source_types: SourceType,
761 exclude_source_types: SourceType,
763 }
764
765 bool_setters! {
766 include_updates,
768 }
769
770 pub(crate) fn to_frame(&self) -> Map<String, Value> {
771 let mut m = Map::new();
772 m.insert("payloadVersion".into(), Value::from(PAYLOAD_VERSION));
773 put_str(&mut m, "query", &self.query);
774 put_list(&mut m, "sources", &self.sources);
775 put_list(&mut m, "excludeSources", &self.exclude_sources);
776 put_list(&mut m, "sourceTypes", &self.source_types);
777 put_list(&mut m, "excludeSourceTypes", &self.exclude_source_types);
778 put_str(&mut m, "language", &self.language);
779 put_bool(&mut m, "includeUpdates", self.include_updates);
780 m
781 }
782}
783
784pub(crate) fn encode_component(value: &str) -> String {
786 let mut out = String::with_capacity(value.len());
787 for b in value.bytes() {
788 match b {
789 b'A'..=b'Z'
790 | b'a'..=b'z'
791 | b'0'..=b'9'
792 | b'-'
793 | b'_'
794 | b'.'
795 | b'!'
796 | b'~'
797 | b'*'
798 | b'\''
799 | b'('
800 | b')' => out.push(b as char),
801 _ => out.push_str(&format!("%{b:02X}")),
802 }
803 }
804 out
805}
806
807pub(crate) fn encode_query(pairs: &[(&str, String)]) -> String {
809 pairs
810 .iter()
811 .map(|(k, v)| format!("{}={}", encode_component(k), encode_component(v)))
812 .collect::<Vec<_>>()
813 .join("&")
814}