pubmed-client 0.1.0

An async Rust client for PubMed and PMC APIs for retrieving biomedical research articles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
use serde::{Deserialize, Serialize};

// Re-export common types
pub use crate::common::{Affiliation, Author};

/// Represents journal information
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct JournalInfo {
    /// Journal title
    pub title: String,
    /// Journal abbreviation
    pub abbreviation: Option<String>,
    /// ISSN (print)
    pub issn_print: Option<String>,
    /// ISSN (electronic)
    pub issn_electronic: Option<String>,
    /// Publisher name
    pub publisher: Option<String>,
    /// Volume
    pub volume: Option<String>,
    /// Issue
    pub issue: Option<String>,
}

/// Represents funding information
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FundingInfo {
    /// Funding source/agency
    pub source: String,
    /// Grant/award ID
    pub award_id: Option<String>,
    /// Funding statement
    pub statement: Option<String>,
}

/// Represents a figure in the article
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Figure {
    /// Figure ID
    pub id: String,
    /// Figure label (e.g., "Figure 1")
    pub label: Option<String>,
    /// Figure caption
    pub caption: String,
    /// Alt text description
    pub alt_text: Option<String>,
    /// Figure type (e.g., "figure", "scheme", "chart")
    pub fig_type: Option<String>,
    /// File path to the extracted figure image (when available)
    pub file_path: Option<String>,
    /// File name from the XML href attribute (when available)
    pub file_name: Option<String>,
}

/// Represents an extracted figure with both XML metadata and file path
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ExtractedFigure {
    /// Figure metadata from XML
    pub figure: Figure,
    /// Actual file path where the figure was extracted
    pub extracted_file_path: String,
    /// File size in bytes
    pub file_size: Option<u64>,
    /// Image dimensions (width, height) if available
    pub dimensions: Option<(u32, u32)>,
}

/// Represents a table in the article
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Table {
    /// Table ID
    pub id: String,
    /// Table label (e.g., "Table 1")
    pub label: Option<String>,
    /// Table caption
    pub caption: String,
    /// Table footnotes
    pub footnotes: Vec<String>,
}

/// Represents supplementary material in the article
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SupplementaryMaterial {
    /// Supplementary material ID
    pub id: String,
    /// Content type (e.g., "local-data")
    pub content_type: Option<String>,
    /// Title/caption of the supplementary material
    pub title: Option<String>,
    /// Description or additional caption
    pub description: Option<String>,
    /// File URL or path (from xlink:href)
    pub file_url: Option<String>,
    /// File extension/type inferred from URL
    pub file_type: Option<String>,
    /// Position attribute (e.g., "float")
    pub position: Option<String>,
}

impl SupplementaryMaterial {
    /// Create a new SupplementaryMaterial instance
    pub fn new(id: String) -> Self {
        Self {
            id,
            content_type: None,
            title: None,
            description: None,
            file_url: None,
            file_type: None,
            position: None,
        }
    }

    /// Check if this supplementary material is a tar file
    pub fn is_tar_file(&self) -> bool {
        if let Some(url) = &self.file_url {
            url.ends_with(".tar")
                || url.ends_with(".tar.gz")
                || url.ends_with(".tar.bz2")
                || url.ends_with(".tgz")
        } else {
            false
        }
    }

    /// Get the file extension from the URL
    pub fn get_file_extension(&self) -> Option<String> {
        if let Some(url) = &self.file_url {
            if let Some(filename) = url.split('/').next_back() {
                if let Some(dot_index) = filename.rfind('.') {
                    return Some(filename[dot_index + 1..].to_lowercase());
                }
            }
        }
        None
    }

    /// Check if this is an archive file (zip, tar, etc.)
    pub fn is_archive(&self) -> bool {
        if let Some(ext) = self.get_file_extension() {
            matches!(
                ext.as_str(),
                "zip" | "tar" | "gz" | "bz2" | "tgz" | "rar" | "7z"
            )
        } else {
            false
        }
    }
}

/// Represents a full-text article from PMC
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PmcFullText {
    /// PMC ID (e.g., "PMC1234567")
    pub pmcid: String,
    /// PubMed ID (if available)
    pub pmid: Option<String>,
    /// Article title
    pub title: String,
    /// List of authors with detailed information
    pub authors: Vec<Author>,
    /// Journal information
    pub journal: JournalInfo,
    /// Publication date
    pub pub_date: String,
    /// DOI (Digital Object Identifier)
    pub doi: Option<String>,
    /// Article sections with content
    pub sections: Vec<ArticleSection>,
    /// List of references
    pub references: Vec<Reference>,
    /// Article type (if available)
    pub article_type: Option<String>,
    /// Keywords
    pub keywords: Vec<String>,
    /// Funding information
    pub funding: Vec<FundingInfo>,
    /// Conflict of interest statement
    pub conflict_of_interest: Option<String>,
    /// Acknowledgments
    pub acknowledgments: Option<String>,
    /// Data availability statement
    pub data_availability: Option<String>,
    /// Supplementary materials
    pub supplementary_materials: Vec<SupplementaryMaterial>,
}

/// Represents a section of an article
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ArticleSection {
    /// Type of section (e.g., "abstract", "introduction", "methods")
    pub section_type: String,
    /// Section title (if available)
    pub title: Option<String>,
    /// Section content
    pub content: String,
    /// Nested subsections
    pub subsections: Vec<ArticleSection>,
    /// Section ID (if available)
    pub id: Option<String>,
    /// Figures in this section
    pub figures: Vec<Figure>,
    /// Tables in this section
    pub tables: Vec<Table>,
}

/// Represents a reference citation
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Reference {
    /// Reference identifier
    pub id: String,
    /// Reference title
    pub title: Option<String>,
    /// List of authors with detailed information
    pub authors: Vec<Author>,
    /// Journal name
    pub journal: Option<String>,
    /// Publication year
    pub year: Option<String>,
    /// Volume
    pub volume: Option<String>,
    /// Issue
    pub issue: Option<String>,
    /// Page range
    pub pages: Option<String>,
    /// PubMed ID (if available)
    pub pmid: Option<String>,
    /// DOI (if available)
    pub doi: Option<String>,
    /// Reference type (e.g., "journal", "book", "web")
    pub ref_type: Option<String>,
}

impl PmcFullText {
    /// Create a new PmcFullText instance
    pub fn new(pmcid: String) -> Self {
        Self {
            pmcid,
            pmid: None,
            title: String::new(),
            authors: Vec::new(),
            journal: JournalInfo {
                title: String::new(),
                abbreviation: None,
                issn_print: None,
                issn_electronic: None,
                publisher: None,
                volume: None,
                issue: None,
            },
            pub_date: String::new(),
            doi: None,
            sections: Vec::new(),
            references: Vec::new(),
            article_type: None,
            keywords: Vec::new(),
            funding: Vec::new(),
            conflict_of_interest: None,
            acknowledgments: None,
            data_availability: None,
            supplementary_materials: Vec::new(),
        }
    }

    /// Check if the article has full text content
    pub fn has_content(&self) -> bool {
        !self.sections.is_empty() || !self.title.is_empty()
    }

    /// Get the total number of sections (including subsections)
    pub fn total_sections(&self) -> usize {
        fn count_sections(sections: &[ArticleSection]) -> usize {
            sections.iter().fold(0, |acc, section| {
                acc + 1 + count_sections(&section.subsections)
            })
        }
        count_sections(&self.sections)
    }

    /// Get all section content as a single string
    pub fn get_full_text(&self) -> String {
        fn collect_content(sections: &[ArticleSection]) -> String {
            sections
                .iter()
                .map(|section| {
                    let mut content = section.content.clone();
                    if !section.subsections.is_empty() {
                        content.push('\n');
                        content.push_str(&collect_content(&section.subsections));
                    }
                    content
                })
                .collect::<Vec<_>>()
                .join("\n\n")
        }
        collect_content(&self.sections)
    }

    /// Get all tar files from supplementary materials
    pub fn get_tar_files(&self) -> Vec<&SupplementaryMaterial> {
        self.supplementary_materials
            .iter()
            .filter(|material| material.is_tar_file())
            .collect()
    }

    /// Get all archive files from supplementary materials
    pub fn get_archive_files(&self) -> Vec<&SupplementaryMaterial> {
        self.supplementary_materials
            .iter()
            .filter(|material| material.is_archive())
            .collect()
    }

    /// Check if the article has supplementary materials
    pub fn has_supplementary_materials(&self) -> bool {
        !self.supplementary_materials.is_empty()
    }

    /// Get supplementary materials by content type
    pub fn get_supplementary_materials_by_type(
        &self,
        content_type: &str,
    ) -> Vec<&SupplementaryMaterial> {
        self.supplementary_materials
            .iter()
            .filter(|material| {
                material
                    .content_type
                    .as_ref()
                    .is_some_and(|ct| ct == content_type)
            })
            .collect()
    }
}

impl ArticleSection {
    /// Create a new ArticleSection instance
    pub fn new(section_type: String, content: String) -> Self {
        Self {
            section_type,
            title: None,
            content,
            subsections: Vec::new(),
            id: None,
            figures: Vec::new(),
            tables: Vec::new(),
        }
    }

    /// Create a new ArticleSection with title
    pub fn with_title(section_type: String, title: String, content: String) -> Self {
        Self {
            section_type,
            title: Some(title),
            content,
            subsections: Vec::new(),
            id: None,
            figures: Vec::new(),
            tables: Vec::new(),
        }
    }

    /// Create a new ArticleSection with ID
    pub fn with_id(section_type: String, content: String, id: String) -> Self {
        Self {
            section_type,
            title: None,
            content,
            subsections: Vec::new(),
            id: Some(id),
            figures: Vec::new(),
            tables: Vec::new(),
        }
    }

    /// Add a subsection
    pub fn add_subsection(&mut self, subsection: ArticleSection) {
        self.subsections.push(subsection);
    }

    /// Check if section has content
    pub fn has_content(&self) -> bool {
        !self.content.trim().is_empty() || !self.subsections.is_empty()
    }
}

impl Reference {
    /// Create a new Reference instance
    pub fn new(id: String) -> Self {
        Self {
            id,
            title: None,
            authors: Vec::new(),
            journal: None,
            year: None,
            volume: None,
            issue: None,
            pages: None,
            pmid: None,
            doi: None,
            ref_type: None,
        }
    }

    /// Create a basic reference with minimal information
    pub fn basic(id: String, title: Option<String>, journal: Option<String>) -> Self {
        Self {
            id,
            title,
            authors: Vec::new(),
            journal,
            year: None,
            volume: None,
            issue: None,
            pages: None,
            pmid: None,
            doi: None,
            ref_type: None,
        }
    }

    /// Format reference as citation string
    pub fn format_citation(&self) -> String {
        let mut parts = Vec::new();

        if !self.authors.is_empty() {
            let author_names: Vec<String> = self
                .authors
                .iter()
                .map(|author| author.full_name.clone())
                .filter(|name| !name.trim().is_empty())
                .collect();
            if !author_names.is_empty() {
                parts.push(author_names.join(", "));
            }
        }

        if let Some(title) = &self.title {
            if !title.trim().is_empty() {
                parts.push(title.clone());
            }
        }

        if let Some(journal) = &self.journal {
            if !journal.trim().is_empty() {
                let mut journal_part = journal.clone();
                if let Some(year) = &self.year {
                    if !year.trim().is_empty() && year != "n.d." {
                        journal_part.push_str(&format!(" ({year})"));
                    }
                }
                if let Some(volume) = &self.volume {
                    if !volume.trim().is_empty() {
                        journal_part.push_str(&format!(" {volume}"));
                        if let Some(issue) = &self.issue {
                            if !issue.trim().is_empty() {
                                journal_part.push_str(&format!("({issue})"));
                            }
                        }
                    }
                }
                if let Some(pages) = &self.pages {
                    if !pages.trim().is_empty() {
                        journal_part.push_str(&format!(": {pages}"));
                    }
                }
                parts.push(journal_part);
            }
        }

        // If no meaningful parts found, use the reference ID as fallback
        let result = parts.join(". ");
        if result.trim().is_empty() {
            let id = &self.id;
            format!("Reference {id}")
        } else {
            result
        }
    }
}

impl JournalInfo {
    /// Create a new JournalInfo instance
    pub fn new(title: String) -> Self {
        Self {
            title,
            abbreviation: None,
            issn_print: None,
            issn_electronic: None,
            publisher: None,
            volume: None,
            issue: None,
        }
    }
}

impl FundingInfo {
    /// Create a new FundingInfo instance
    pub fn new(source: String) -> Self {
        Self {
            source,
            award_id: None,
            statement: None,
        }
    }
}

impl Figure {
    /// Create a new Figure instance
    pub fn new(id: String, caption: String) -> Self {
        Self {
            id,
            label: None,
            caption,
            alt_text: None,
            fig_type: None,
            file_path: None,
            file_name: None,
        }
    }
}

impl Table {
    /// Create a new Table instance
    pub fn new(id: String, caption: String) -> Self {
        Self {
            id,
            label: None,
            caption,
            footnotes: Vec::new(),
        }
    }
}

/// Information about OA (Open Access) subset availability for a PMC article
///
/// The OA subset contains articles with programmatic access to full-text XML.
/// Not all PMC articles are in the OA subset - some publishers restrict programmatic access
/// even though the article may be viewable on the PMC website.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OaSubsetInfo {
    /// PMC ID (e.g., "PMC7906746")
    pub pmcid: String,
    /// Whether the article is in the OA subset
    pub is_oa_subset: bool,
    /// Citation string (if available)
    pub citation: Option<String>,
    /// License type (if available)
    pub license: Option<String>,
    /// Whether the article is retracted
    pub retracted: bool,
    /// Download link for tar.gz package (if available)
    pub download_link: Option<String>,
    /// Format of the download (e.g., "tgz", "pdf")
    pub download_format: Option<String>,
    /// Last updated timestamp for the download
    pub updated: Option<String>,
    /// Error code if not in OA subset
    pub error_code: Option<String>,
    /// Error message if not in OA subset
    pub error_message: Option<String>,
}

impl OaSubsetInfo {
    /// Create a new OaSubsetInfo for an article in the OA subset
    pub fn available(pmcid: String) -> Self {
        Self {
            pmcid,
            is_oa_subset: true,
            citation: None,
            license: None,
            retracted: false,
            download_link: None,
            download_format: None,
            updated: None,
            error_code: None,
            error_message: None,
        }
    }

    /// Create a new OaSubsetInfo for an article NOT in the OA subset
    pub fn not_available(pmcid: String, error_code: String, error_message: String) -> Self {
        Self {
            pmcid,
            is_oa_subset: false,
            citation: None,
            license: None,
            retracted: false,
            download_link: None,
            download_format: None,
            updated: None,
            error_code: Some(error_code),
            error_message: Some(error_message),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pmc_full_text_creation() {
        let article = PmcFullText::new("PMC1234567".to_string());
        assert_eq!(article.pmcid, "PMC1234567");
        assert!(!article.has_content());
        assert_eq!(article.total_sections(), 0);
    }

    #[test]
    fn test_article_section_creation() {
        let mut section =
            ArticleSection::new("abstract".to_string(), "This is an abstract.".to_string());
        assert!(section.has_content());
        assert_eq!(section.subsections.len(), 0);

        let subsection = ArticleSection::new("method".to_string(), "Method details.".to_string());
        section.add_subsection(subsection);
        assert_eq!(section.subsections.len(), 1);
    }

    #[test]
    fn test_reference_formatting() {
        let mut reference = Reference::new("ref1".to_string());
        reference.authors = vec![
            Author::from_full_name("Smith, J.".to_string()),
            Author::from_full_name("Doe, A.".to_string()),
        ];
        reference.title = Some("Test Article".to_string());
        reference.journal = Some("Test Journal".to_string());
        reference.year = Some("2023".to_string());

        let citation = reference.format_citation();
        assert!(citation.contains("Smith, J., Doe, A."));
        assert!(citation.contains("Test Article"));
        assert!(citation.contains("Test Journal (2023)"));
    }

    #[test]
    fn test_full_text_content() {
        let mut article = PmcFullText::new("PMC1234567".to_string());

        let section1 = ArticleSection::new("abstract".to_string(), "Abstract content.".to_string());
        let section2 = ArticleSection::new(
            "introduction".to_string(),
            "Introduction content.".to_string(),
        );

        article.sections.push(section1);
        article.sections.push(section2);

        assert!(article.has_content());
        assert_eq!(article.total_sections(), 2);

        let full_text = article.get_full_text();
        assert!(full_text.contains("Abstract content."));
        assert!(full_text.contains("Introduction content."));
    }

    #[test]
    fn test_supplementary_material_creation() {
        let mut material = SupplementaryMaterial::new("supp1".to_string());
        material.file_url = Some("https://example.com/data.tar.gz".to_string());
        material.content_type = Some("local-data".to_string());
        material.title = Some("Supplementary Data".to_string());

        assert_eq!(material.id, "supp1");
        assert!(material.is_tar_file());
        assert!(material.is_archive());
        assert_eq!(material.get_file_extension(), Some("gz".to_string()));
    }

    #[test]
    fn test_tar_file_detection() {
        let mut material = SupplementaryMaterial::new("tar1".to_string());

        // Test various tar file extensions
        material.file_url = Some("data.tar".to_string());
        assert!(material.is_tar_file());

        material.file_url = Some("data.tar.gz".to_string());
        assert!(material.is_tar_file());

        material.file_url = Some("data.tar.bz2".to_string());
        assert!(material.is_tar_file());

        material.file_url = Some("data.tgz".to_string());
        assert!(material.is_tar_file());

        // Test non-tar files
        material.file_url = Some("data.zip".to_string());
        assert!(!material.is_tar_file());
        assert!(material.is_archive());

        material.file_url = Some("data.pdf".to_string());
        assert!(!material.is_tar_file());
        assert!(!material.is_archive());
    }

    #[test]
    fn test_pmc_full_text_with_supplementary_materials() {
        let mut article = PmcFullText::new("PMC1234567".to_string());

        let mut tar_material = SupplementaryMaterial::new("supp1".to_string());
        tar_material.file_url = Some("dataset.tar.gz".to_string());
        tar_material.content_type = Some("local-data".to_string());

        let mut zip_material = SupplementaryMaterial::new("supp2".to_string());
        zip_material.file_url = Some("figures.zip".to_string());
        zip_material.content_type = Some("local-data".to_string());

        article.supplementary_materials.push(tar_material);
        article.supplementary_materials.push(zip_material);

        assert!(article.has_supplementary_materials());
        assert_eq!(article.supplementary_materials.len(), 2);

        let tar_files = article.get_tar_files();
        assert_eq!(tar_files.len(), 1);
        assert_eq!(tar_files[0].id, "supp1");

        let archive_files = article.get_archive_files();
        assert_eq!(archive_files.len(), 2);

        let local_data_materials = article.get_supplementary_materials_by_type("local-data");
        assert_eq!(local_data_materials.len(), 2);
    }
}