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
450
451
452
453
454
455
456
457
458
459
//! Version and editor information types.
//!
//! This module contains types related to article revisions (versions), including:
//! - [`Version`] - Complete revision metadata with credibility signals
//! - [`Editor`] - Editor information and user groups
//! - [`Scores`] - Quality scores (revert risk, reference risk, reference need)
//! - [`Protection`] - Page protection settings
//! - [`MaintenanceTags`] - Template counts for maintenance needs
//!
//! # Credibility Signals
//!
//! Several fields are marked as "Credibility Signals" in the API documentation.
//! These provide qualitative metadata to help make informed decisions about data handling:
//!
//! - **Revert Risk Score**: Predicts whether a revision may be reverted
//! - **Reference Risk Score**: Probability that references remain in the article
//! - **Reference Need Score**: Proportion of uncited sentences needing citations
//! - **Editor Information**: Edit count, user groups, registration date
//! - **Maintenance Tags**: Counts of citation needed, POV, clarification, update templates
//!
//! # Example
//!
//! ```
//! use wme_models::{Version, Editor};
//! use chrono::Utc;
//!
//! let version = Version {
//!     identifier: 1182847293,
//!     editor: Some(Editor {
//!         identifier: Some(12345),
//!         name: Some("ExampleUser".to_string()),
//!         is_bot: Some(false),
//!         is_anonymous: Some(false),
//!         date_started: Some(Utc::now()),
//!         edit_count: Some(1500),
//!         groups: Some(vec!["user".to_string(), "autoconfirmed".to_string()]),
//!         is_admin: Some(false),
//!         is_patroller: Some(false),
//!         has_advanced_rights: Some(false),
//!     }),
//!     comment: Some("Fixed typo".to_string()),
//!     tags: Some(vec!["mobile edit".to_string()]),
//!     has_tag_needs_citation: Some(false),
//!     is_minor_edit: Some(true),
//!     is_flagged_stable: Some(true),
//!     is_breaking_news: Some(false),
//!     noindex: Some(false),
//!     number_of_characters: Some(5000),
//!     size: Some(wme_models::ArticleSize {
//!         value: 15000,
//!         unit_text: "B".to_string(),
//!     }),
//!     maintenance_tags: None,
//!     scores: None,
//! };
//! ```

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

/// Version information for an article.
///
/// Represents a single revision of an article with comprehensive metadata
/// including editor information, credibility signals, and quality scores.
///
/// # Key Fields
///
/// - `identifier` - Unique revision ID (different from article ID)
/// - `editor` - Editor who made this revision
/// - `scores` - Quality predictions from LiftWing models
/// - `maintenance_tags` - Counts of maintenance templates
/// - `is_flagged_stable` - Community-approved revision flag
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Version {
    /// Revision identifier (unique for each edit)
    pub identifier: u64,
    /// Editor information
    pub editor: Option<Editor>,
    /// Edit comment
    pub comment: Option<String>,
    /// MediaWiki change tags
    pub tags: Option<Vec<String>>,
    /// Has "citation needed" tag
    pub has_tag_needs_citation: Option<bool>,
    /// Was this a minor edit
    pub is_minor_edit: Option<bool>,
    /// Community-approved revision
    pub is_flagged_stable: Option<bool>,
    /// Breaking news flag
    pub is_breaking_news: Option<bool>,
    /// Non-indexable to search engines
    pub noindex: Option<bool>,
    /// Character count from wikitext
    pub number_of_characters: Option<u64>,
    /// Article size
    pub size: Option<ArticleSize>,
    /// Maintenance template counts
    pub maintenance_tags: Option<MaintenanceTags>,
    /// Quality scores
    pub scores: Option<Scores>,
}

/// Previous version reference.
///
/// Lightweight reference to the revision prior to the current one.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct PreviousVersion {
    /// Revision identifier
    pub identifier: u64,
    /// Editor information
    pub editor: Option<Editor>,
    /// Number of characters in the previous revision
    #[serde(skip_serializing_if = "Option::is_none")]
    pub number_of_characters: Option<u64>,
}

impl<'de> Deserialize<'de> for PreviousVersion {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct RawPreviousVersion {
            identifier: Option<u64>,
            #[serde(default)]
            number_of_characters: Option<u64>,
        }

        let raw = RawPreviousVersion::deserialize(deserializer)?;

        match raw.identifier {
            Some(id) => Ok(PreviousVersion {
                identifier: id,
                editor: None,
                number_of_characters: raw.number_of_characters,
            }),
            None => Err(serde::de::Error::custom(
                "previous_version must have an identifier field",
            )),
        }
    }
}

/// Wrapper for optional previous_version that handles empty objects.
///
/// In the API, `previous_version` can be:
/// - Missing or null → None
/// - Empty object `{}` → None
/// - Object with identifier → Some(PreviousVersion)
#[derive(Debug, Clone, PartialEq, Default)]
pub struct OptionalPreviousVersion(pub Option<PreviousVersion>);

impl<'de> Deserialize<'de> for OptionalPreviousVersion {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct RawPreviousVersion {
            identifier: Option<u64>,
            #[serde(default)]
            number_of_characters: Option<u64>,
        }

        #[derive(Deserialize)]
        #[serde(untagged)]
        enum RawOptPreviousVersion {
            None,
            Some(RawPreviousVersion),
        }

        match RawOptPreviousVersion::deserialize(deserializer)? {
            RawOptPreviousVersion::None => Ok(OptionalPreviousVersion(None)),
            RawOptPreviousVersion::Some(raw) => match raw.identifier {
                Some(id) => Ok(OptionalPreviousVersion(Some(PreviousVersion {
                    identifier: id,
                    editor: None,
                    number_of_characters: raw.number_of_characters,
                }))),
                None => Ok(OptionalPreviousVersion(None)),
            },
        }
    }
}

impl Serialize for OptionalPreviousVersion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match &self.0 {
            Some(pv) => pv.serialize(serializer),
            None => serializer.serialize_none(),
        }
    }
}

/// Editor information.
///
/// Provides context about who made a revision. Anonymous editors (IP addresses)
/// have no identifier. Temporary accounts (since Dec 2025) have identifiers
/// but `is_anonymous` will be false.
///
/// # Editor Name Format
///
/// - **Registered users**: Username (e.g., "ExampleUser")
/// - **Anonymous (legacy)**: IP address (e.g., "192.168.1.1")
/// - **Temporary accounts**: `~YYYY-SERIAL` (e.g., "~2026-59431-3")
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Editor {
    /// Editor identifier (none for anonymous users)
    pub identifier: Option<u64>,
    /// Editor name or IP address
    pub name: Option<String>,
    /// Is a bot
    pub is_bot: Option<bool>,
    /// Is an anonymous (IP) editor
    pub is_anonymous: Option<bool>,
    /// User registration timestamp
    pub date_started: Option<DateTime<Utc>>,
    /// Total edit count
    pub edit_count: Option<u64>,
    /// User groups (e.g., "admin", "autoconfirmed")
    pub groups: Option<Vec<String>>,
    /// Is an admin
    pub is_admin: Option<bool>,
    /// Is a patroller
    pub is_patroller: Option<bool>,
    /// Has advanced rights
    pub has_advanced_rights: Option<bool>,
}

/// Article size information.
///
/// Size of the article in wikitext format.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct ArticleSize {
    /// Size value in bytes
    pub value: u64,
    /// Unit text (usually "B")
    pub unit_text: String,
}

/// Maintenance template counts.
///
/// Counts of occurrences of certain templates in the article body.
/// These indicate areas that may need editor attention.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct MaintenanceTags {
    /// Citation needed count
    pub citation_needed_count: Option<u64>,
    /// POV tag count
    pub pov_count: Option<u64>,
    /// Clarification needed count
    pub clarification_needed_count: Option<u64>,
    /// Update needed count
    pub update_count: Option<u64>,
}

/// Quality scores.
///
/// Scores calculated as part of Wikimedia's LiftWing project.
/// These provide credibility signals for revision quality.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Scores {
    /// Revert risk score (may revision be reverted?)
    pub revertrisk: Option<RevertRisk>,
    /// Reference risk score (will references remain?)
    pub referencerisk: Option<ReferenceRisk>,
    /// Reference need score (what needs citations?)
    pub referenceneed: Option<ReferenceNeed>,
}

/// Revert risk score.
///
/// Predicts whether a revision may be reverted based on edit patterns.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct RevertRisk {
    /// Revert risk prediction (true = likely to be reverted)
    pub prediction: Option<bool>,
    /// Revert risk probability details
    pub probability: Option<serde_json::Value>,
}

/// Reference risk score.
///
/// Probability of references remaining in the article based on
/// historical editorial activity on web domains used as references.
/// Serves as a proxy for "source reliability".
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct ReferenceRisk {
    /// Reference risk score (0.0 to 1.0)
    pub reference_risk_score: Option<f64>,
}

/// Reference need score.
///
/// Proportion of uncited sentences that need citations.
/// Available for these Wikipedia languages: fa, it, zh, ru, pt, es, ja, de, fr, en.
/// Only available for articles (Namespace 0).
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct ReferenceNeed {
    /// Reference need score (0.0 to 1.0)
    pub reference_need_score: Option<f64>,
}

/// Protection settings.
///
/// Community-specific protections and restrictions on the article.
/// Indicates which editor permissions are needed to edit or move the page.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Protection {
    /// Protection type (e.g., "edit", "move")
    #[serde(rename = "type")]
    pub protection_type: String,
    /// Protection level (e.g., "autoconfirmed", "sysop")
    pub level: String,
    /// Expiration timestamp (None for never-expiring)
    #[serde(deserialize_with = "deserialize_expiry")]
    pub expiry: Option<DateTime<Utc>>,
}

fn deserialize_expiry<'de, D>(deserializer: D) -> Result<Option<DateTime<Utc>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum RawExpiry {
        DateTime(DateTime<Utc>),
        Infinity(String),
        Null,
    }

    match RawExpiry::deserialize(deserializer)? {
        RawExpiry::DateTime(dt) => Ok(Some(dt)),
        RawExpiry::Infinity(s) if s == "infinity" => Ok(None),
        RawExpiry::Infinity(s) => Err(serde::de::Error::custom(format!(
            "invalid expiry value: {}",
            s
        ))),
        RawExpiry::Null => Ok(None),
    }
}

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

    #[test]
    fn test_version_creation() {
        let 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,
        };

        assert_eq!(version.identifier, 1182847293);
        assert!(version.is_flagged_stable.unwrap());
    }

    #[test]
    fn test_editor_groups() {
        let editor = Editor {
            identifier: Some(12345),
            name: Some("AdminUser".to_string()),
            is_bot: Some(false),
            is_anonymous: Some(false),
            date_started: Some(Utc::now()),
            edit_count: Some(5000),
            groups: Some(vec![
                "user".to_string(),
                "autoconfirmed".to_string(),
                "extendedconfirmed".to_string(),
            ]),
            is_admin: Some(true),
            is_patroller: Some(true),
            has_advanced_rights: Some(true),
        };

        let groups = editor.groups.as_ref().unwrap();
        assert!(groups.contains(&"user".to_string()));
        assert!(groups.contains(&"autoconfirmed".to_string()));
        assert!(editor.is_admin.unwrap());
    }

    #[test]
    fn test_maintenance_tags() {
        let tags = MaintenanceTags {
            citation_needed_count: Some(5),
            pov_count: Some(1),
            clarification_needed_count: Some(2),
            update_count: Some(10),
        };

        assert_eq!(tags.citation_needed_count, Some(5));
        assert_eq!(tags.pov_count, Some(1));
    }

    #[test]
    fn test_protection() {
        let protection = Protection {
            protection_type: "edit".to_string(),
            level: "autoconfirmed".to_string(),
            expiry: None, // Never expires
        };

        assert_eq!(protection.protection_type, "edit");
        assert_eq!(protection.level, "autoconfirmed");
        assert!(protection.expiry.is_none());
    }

    #[test]
    fn test_scores() {
        let scores = Scores {
            revertrisk: Some(RevertRisk {
                prediction: Some(false),
                probability: None,
            }),
            referencerisk: Some(ReferenceRisk {
                reference_risk_score: Some(0.15),
            }),
            referenceneed: Some(ReferenceNeed {
                reference_need_score: Some(0.25),
            }),
        };

        assert_eq!(scores.revertrisk.unwrap().prediction, Some(false));
        assert_eq!(
            scores.referencerisk.unwrap().reference_risk_score,
            Some(0.15)
        );
    }
}