wme-models 0.1.3

Type definitions for the Wikimedia Enterprise API
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
//! Article types for the Wikimedia Enterprise API.
//!
//! This module provides the core [`Article`] type used across all Enterprise APIs
//! (On-demand, Snapshot, and Realtime). The same schema is returned by all endpoints,
//! allowing you to process articles from any source without separate parsers.
//!
//! # Article Structure
//!
//! Articles contain comprehensive metadata about a Wikipedia page:
//! - **Identification**: `identifier`, `name`, `url`
//! - **Content**: `abstract_text`, `article_body` (HTML/wikitext)
//! - **Context**: `in_language`, `is_part_of`, `namespace`
//! - **Version**: `version` with editor info and credibility signals
//! - **Categorization**: `categories`, `templates`, `redirects`
//! - **Event metadata**: `event` (Realtime API only)
//!
//! # Handling Duplicates
//!
//! Snapshot and Realtime Batch files may contain duplicate articles (< 1%).
//! When processing, keep the article with the highest `version.identifier`:
//!
//! ```rust
//! use wme_models::Article;
//!
//! fn keep_latest(existing: &Article, incoming: &Article) -> bool {
//!     incoming.version.identifier > existing.version.identifier
//! }
//! ```
//!
//! # Visibility Events
//!
//! The Realtime API may return `visibility-change` events where content is hidden.
//! Check the `visibility` field to determine if text, editor, or comment is visible.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::content::ArticleBody;
use crate::metadata::{EventMetadata, Language};
use crate::reference::Reference;
use crate::structured::{Infobox, Section, Table};
use crate::version::{OptionalPreviousVersion, Protection, Version};
use crate::{
    Category, Image, License, Namespace, Redirect, Template, WikidataEntity, WikidataEntityUsage,
};

/// Visibility flags for articles (present on visibility-change events).
///
/// When the editing community flags a revision as containing potentially damaging
/// information, they change its visibility. The three booleans indicate whether
/// the article body, editor name, or edit comment may contain harmful data.
///
/// # Examples
///
/// ```
/// use wme_models::Visibility;
///
/// let visibility = Visibility {
///     text: true,
///     editor: false,
///     comment: false,
/// };
///
/// // When text=false, the article content is hidden
/// // When editor=false, the editor name is hidden
/// // When comment=false, the edit summary is hidden
/// ```
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Visibility {
    /// Is article text visible?
    pub text: bool,
    /// Is editor name visible?
    pub editor: bool,
    /// Is edit comment visible?
    pub comment: bool,
}

/// Project reference (simplified, used in article responses).
///
/// This is a lightweight reference to the project an article belongs to.
/// For full project metadata, see [`crate::metadata::ProjectInfo`].
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct ProjectRef {
    /// Project identifier (e.g., "enwiki")
    pub identifier: String,
    /// Project URL
    pub url: Option<String>,
}

/// Complete article from Enterprise API.
///
/// This is the primary data structure returned by all Enterprise APIs.
/// The same schema is used across On-demand, Snapshot, and Realtime endpoints.
///
/// # Example
///
/// ```
/// use wme_models::Article;
/// use serde_json;
///
/// let json = r#"{
///     "name": "Squirrel",
///     "identifier": 28492,
///     "url": "https://en.wikipedia.org/wiki/Squirrel",
///     "date_created": "2001-01-15T00:00:00Z",
///     "date_modified": "2024-01-15T12:00:00Z",
///     "in_language": {"identifier": "en", "name": "English"},
///     "is_part_of": {"identifier": "enwiki"},
///     "namespace": {"identifier": 0, "name": ""},
///     "license": [{"name": "CC BY-SA 4.0", "url": "https://creativecommons.org/licenses/by-sa/4.0/"}],
///     "version": {
///         "identifier": 1182847293,
///         "editor": {"identifier": 12345, "name": "SomeUser"}
///     }
/// }"#;
///
/// let article: Article = serde_json::from_str(json).unwrap();
/// assert_eq!(article.name, "Squirrel");
/// assert_eq!(article.identifier, 28492);
/// ```
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Article {
    /// Article ID (MediaWiki page ID)
    pub identifier: u64,
    /// Article name/title
    pub name: String,
    /// Article URL
    pub url: String,
    /// Article abstract/summary
    #[serde(rename = "abstract")]
    pub abstract_text: Option<String>,
    /// Short description (e.g., "Family of rodents")
    pub description: Option<String>,
    /// Last modification timestamp
    pub date_modified: DateTime<Utc>,
    /// Before-last modification timestamp
    pub date_previously_modified: Option<DateTime<Utc>>,
    /// Language information
    pub in_language: Language,
    /// Project this article belongs to (simplified reference)
    pub is_part_of: ProjectRef,
    /// Namespace information
    pub namespace: Option<Namespace>,
    /// Main Wikidata entity (primary topic)
    pub main_entity: Option<WikidataEntity>,
    /// Additional Wikidata entities used
    pub additional_entities: Option<Vec<WikidataEntityUsage>>,
    /// Categories this article belongs to
    pub categories: Option<Vec<Category>>,
    /// Templates used in this article
    pub templates: Option<Vec<Template>>,
    /// Redirects to this article (alternative names)
    pub redirects: Option<Vec<Redirect>>,
    /// Current version information with credibility signals
    pub version: Version,
    /// Previous version information
    #[serde(default)]
    pub previous_version: OptionalPreviousVersion,
    /// Number of editors watching this page
    pub watchers_count: Option<u64>,
    /// Protection settings (edit/move restrictions)
    pub protection: Option<Vec<Protection>>,
    /// Visibility flags (for visibility-change events)
    pub visibility: Option<Visibility>,
    /// Main image for the article
    pub image: Option<Image>,
    /// License(s) for this article (usually CC-BY-SA)
    pub license: Vec<License>,
    /// Article body content (HTML and wikitext)
    pub article_body: Option<ArticleBody>,
    /// Event metadata (present in Realtime API responses)
    pub event: Option<EventMetadata>,
    /// Has parts - structured content sections (when using fields filter)
    pub has_parts: Option<Vec<Section>>,
}

/// Structured Contents (BETA) - Article with parsed content.
///
/// This type extends [`Article`] with fully parsed content including infoboxes,
/// sections, and tables. Available through the Structured Contents BETA endpoint.
///
/// # Accessing Content
///
/// Use the convenience methods to access parsed content:
///
/// ```rust,ignore
/// use wme_models::StructuredArticle;
///
/// // Get infobox by name
/// if let Some(infobox) = article.infobox("Automatic taxobox") {
///     // Process infobox fields
/// }
///
/// // Get section by name
/// if let Some(section) = article.section("Taxonomy") {
///     // Process section content
/// }
/// ```
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct StructuredArticle {
    /// Base article fields (flattened)
    #[serde(flatten)]
    pub base: Article,
    /// Creation timestamp (first revision) - only in structured contents
    pub date_created: DateTime<Utc>,
    /// Parsed infoboxes
    pub infoboxes: Vec<Infobox>,
    /// Parsed sections
    pub sections: Vec<Section>,
    /// Tables (single object in structured contents)
    pub tables: Table,
    /// References/citations (single object in structured contents)
    pub references: Reference,
}

impl StructuredArticle {
    /// Get infobox by name.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use wme_models::StructuredArticle;
    ///
    /// if let Some(infobox) = article.infobox("Automatic taxobox") {
    ///     println!("Found infobox: {:?}", infobox.name);
    /// }
    /// ```
    pub fn infobox(&self, name: &str) -> Option<&Infobox> {
        self.infoboxes
            .iter()
            .find(|i| i.name.as_ref().map(|n| n == name).unwrap_or(false))
    }

    /// Get section by name.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use wme_models::StructuredArticle;
    ///
    /// if let Some(section) = article.section("References") {
    ///     println!("Section has {} parts", section.has_parts.as_ref().map(|p| p.len()).unwrap_or(0));
    /// }
    /// ```
    pub fn section(&self, name: &str) -> Option<&Section> {
        self.sections
            .iter()
            .find(|s| s.name.as_ref().map(|n| n == name).unwrap_or(false))
    }

    /// Get table by identifier.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use wme_models::StructuredArticle;
    ///
    /// if let Some(table) = article.table("demographics_table1") {
    ///     println!("Table has {} rows", table.rows.len());
    /// }
    /// ```
    pub fn table(&self, identifier: &str) -> Option<&Table> {
        if self.tables.identifier == identifier {
            Some(&self.tables)
        } else {
            None
        }
    }
}

impl std::ops::Deref for StructuredArticle {
    type Target = Article;

    fn deref(&self) -> &Self::Target {
        &self.base
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::version::{ArticleSize, Editor};
    use chrono::Utc;

    fn create_test_language() -> Language {
        Language {
            identifier: Some("en".to_string()),
            name: Some("English".to_string()),
            alternate_name: None,
            direction: Some("ltr".to_string()),
        }
    }

    fn create_test_namespace() -> Namespace {
        Namespace {
            identifier: 0,
            name: Some("".to_string()),
            description: Some("Main namespace".to_string()),
        }
    }

    fn create_test_project_ref() -> ProjectRef {
        ProjectRef {
            identifier: "enwiki".to_string(),
            url: Some("https://en.wikipedia.org".to_string()),
        }
    }

    fn create_test_version() -> Version {
        Version {
            identifier: 1182847293,
            editor: Some(Editor {
                identifier: Some(12345),
                name: Some("TestUser".to_string()),
                is_bot: Some(false),
                is_anonymous: Some(false),
                date_started: Some(Utc::now()),
                edit_count: Some(1000),
                groups: Some(vec!["user".to_string()]),
                is_admin: Some(false),
                is_patroller: Some(false),
                has_advanced_rights: Some(false),
            }),
            comment: Some("Test edit".to_string()),
            tags: Some(vec!["mobile edit".to_string()]),
            has_tag_needs_citation: Some(false),
            is_minor_edit: Some(false),
            is_flagged_stable: Some(true),
            is_breaking_news: Some(false),
            noindex: Some(false),
            number_of_characters: Some(5000),
            size: Some(ArticleSize {
                value: 15000,
                unit_text: "B".to_string(),
            }),
            maintenance_tags: None,
            scores: None,
        }
    }

    fn create_test_article() -> Article {
        Article {
            identifier: 28492,
            name: "Squirrel".to_string(),
            url: "https://en.wikipedia.org/wiki/Squirrel".to_string(),
            abstract_text: Some("Squirrels are members of the family Sciuridae...".to_string()),
            description: Some("Family of rodents".to_string()),
            date_modified: Utc::now(),
            date_previously_modified: None,
            in_language: create_test_language(),
            is_part_of: create_test_project_ref(),
            namespace: Some(create_test_namespace()),
            main_entity: None,
            additional_entities: None,
            categories: None,
            templates: None,
            redirects: None,
            version: create_test_version(),
            previous_version: OptionalPreviousVersion(None),
            watchers_count: Some(42),
            protection: None,
            visibility: None,
            image: None,
            license: vec![],
            article_body: None,
            event: None,
            has_parts: None,
        }
    }

    #[test]
    fn test_article_creation() {
        let article = create_test_article();
        assert_eq!(article.identifier, 28492);
        assert_eq!(article.name, "Squirrel");
        assert!(article.abstract_text.is_some());
    }

    #[test]
    fn test_project_ref_creation() {
        let project = ProjectRef {
            identifier: "enwiki".to_string(),
            url: Some("https://en.wikipedia.org".to_string()),
        };
        assert_eq!(project.identifier, "enwiki");
        assert!(project.url.is_some());
    }

    #[test]
    fn test_visibility_creation() {
        let visibility = Visibility {
            text: true,
            editor: false,
            comment: false,
        };
        assert!(visibility.text);
        assert!(!visibility.editor);
        assert!(!visibility.comment);
    }

    #[test]
    fn test_version_comparison_for_dedup() {
        let article1 = create_test_article();
        let article2 = Article {
            identifier: 28492,
            name: "Squirrel".to_string(),
            url: "https://en.wikipedia.org/wiki/Squirrel".to_string(),
            abstract_text: None,
            description: None,
            date_modified: Utc::now(),
            date_previously_modified: None,
            in_language: create_test_language(),
            is_part_of: create_test_project_ref(),
            namespace: Some(create_test_namespace()),
            main_entity: None,
            additional_entities: None,
            categories: None,
            templates: None,
            redirects: None,
            version: Version {
                identifier: 1182847294, // Higher version
                editor: create_test_version().editor,
                comment: None,
                tags: None,
                has_tag_needs_citation: None,
                is_minor_edit: None,
                is_flagged_stable: None,
                is_breaking_news: None,
                noindex: None,
                number_of_characters: None,
                size: None,
                maintenance_tags: None,
                scores: None,
            },
            previous_version: OptionalPreviousVersion(None),
            watchers_count: None,
            protection: None,
            visibility: None,
            image: None,
            license: vec![],
            article_body: None,
            event: None,
            has_parts: None,
        };

        // When deduplicating, keep the one with higher version.identifier
        assert!(article2.version.identifier > article1.version.identifier);
    }
}