wikibase_rest_api 0.1.16

A Rust client for the Wikibase REST 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
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
use crate::{
    statements_patch::StatementsPatch, EditMetadata, EntityId, FromJson, HeaderInfo, HttpGetEntity,
    HttpMisc, Patch, RestApi, RestApiError, RevisionMatch, Statement,
};
use derive_where::DeriveWhere;
use serde::ser::{Serialize, SerializeMap};
use serde_json::{json, Value};
use std::collections::HashMap;

#[derive(DeriveWhere, Debug, Clone, Default)]
#[derive_where(PartialEq)]
pub struct Statements {
    statements: HashMap<String, Vec<Statement>>, // property => Statements
    #[derive_where(skip)]
    header_info: HeaderInfo,
}

impl Statements {
    /// Creates a new `Statements` object from a JSON structure
    pub fn from_json(j: &Value) -> Result<Self, RestApiError> {
        Self::from_json_header_info(j, HeaderInfo::default())
    }

    /// Creates a new `Statements` object from a JSON structure with header info
    pub fn from_json_header_info(j: &Value, header_info: HeaderInfo) -> Result<Self, RestApiError> {
        let mut ret = Self::default();
        let statements_j = j
            .as_object()
            .ok_or_else(|| RestApiError::MissingOrInvalidField {
                field: "Statements".into(),
                j: j.to_owned(),
            })?;
        for (property, statements) in statements_j {
            let statements =
                statements
                    .as_array()
                    .ok_or_else(|| RestApiError::MissingOrInvalidField {
                        field: property.into(),
                        j: json!(statements),
                    })?;
            let statements = statements
                .iter()
                .map(Statement::from_json)
                .collect::<Result<Vec<Statement>, RestApiError>>()?;
            ret.statements.insert(property.to_owned(), statements);
        }
        ret.header_info = header_info;
        Ok(ret)
    }

    /// Returns the number of statements
    pub fn len(&self) -> usize {
        self.statements.iter().flat_map(|(_, v)| v).count()
    }

    /// Returns true if there are no statements
    pub fn is_empty(&self) -> bool {
        self.statements.is_empty()
    }

    /// Returns the Statements for a specific property
    pub fn property<S: Into<String>>(&self, property: S) -> Vec<&Statement> {
        self.statements
            .get(&property.into())
            .map_or_else(Vec::new, |v| v.iter().collect())
    }

    /// Returns the mutable Statements for a specific property
    pub fn property_mut<S: Into<String>>(&mut self, property: S) -> Vec<&mut Statement> {
        self.statements
            .get_mut(&property.into())
            .map_or_else(Vec::new, |v| v.iter_mut().collect())
    }

    pub fn insert(&mut self, statement: Statement) {
        let property = statement.property().to_owned();
        self.statements
            .entry(property.id().to_owned())
            .or_default()
            .push(statement);
    }

    pub const fn statements(&self) -> &HashMap<String, Vec<Statement>> {
        &self.statements
    }

    pub const fn statements_mut(&mut self) -> &mut HashMap<String, Vec<Statement>> {
        &mut self.statements
    }

    pub const fn header_info(&self) -> &HeaderInfo {
        &self.header_info
    }

    // Returns a list of all statements with an ID, as HashMap ID => &Statement
    fn get_id_statement_map(&self) -> HashMap<&str, &Statement> {
        self.statements
            .values()
            .flat_map(|v| v.iter())
            .filter_map(|statement| Some((statement.id()?.as_str(), statement)))
            .collect()
    }

    // Returns a list of all statements without IDs
    fn get_statements_without_id(&self) -> Vec<&Statement> {
        self.statements
            .values()
            .flat_map(|v| v.iter())
            .filter(|statement| statement.id().is_none())
            .collect()
    }

    pub fn patch(&self, other: &Self) -> Result<StatementsPatch, RestApiError> {
        // Statements without ID in other => fail
        if !other.get_statements_without_id().is_empty() {
            return Err(RestApiError::MissingId);
        }

        let mut patch = StatementsPatch::default();
        let from_statements_with_id = self.get_id_statement_map();
        let to_statements_with_id = other.get_id_statement_map();

        Self::patch_modify_remove(&mut patch, &from_statements_with_id, &to_statements_with_id)?;
        Self::patch_add_new(&mut patch, from_statements_with_id, to_statements_with_id);

        Ok(patch)
    }

    fn patch_modify_remove(
        patch: &mut StatementsPatch,
        from_statements_with_id: &HashMap<&str, &Statement>,
        to_statements_with_id: &HashMap<&str, &Statement>,
    ) -> Result<(), RestApiError> {
        for (statement_id, from_statement) in from_statements_with_id {
            match to_statements_with_id.get(statement_id) {
                Some(to_statement) => {
                    // Modify statement
                    let statement_patch = from_statement.patch(to_statement)?;
                    patch.patch_mut().extend(statement_patch.patch().to_owned());
                }
                None => {
                    // Remove statement
                    let statement_path = format!("/statements/{statement_id}"); // TODO check
                    patch.remove(statement_path);
                }
            }
        }
        Ok(())
    }

    fn patch_add_new(
        patch: &mut StatementsPatch,
        from_statements_with_id: HashMap<&str, &Statement>,
        to_statements_with_id: HashMap<&str, &Statement>,
    ) {
        // Add new statements
        for (statement_id, to_statement) in &to_statements_with_id {
            if !from_statements_with_id.contains_key(statement_id) {
                // Add new statement
                let add_path = format!("/statements/{statement_id}"); // TODO check
                let value = json!(to_statement);
                patch.add(add_path, value);
            }
        }
    }
}

// GET
impl HttpGetEntity for Statements {
    async fn get_match(
        id: &EntityId,
        api: &RestApi,
        rm: RevisionMatch,
    ) -> Result<Self, RestApiError> {
        let path = Self::get_rest_api_path(id)?;
        let (j, header_info) = Self::get_match_internal(api, &path, rm).await?;
        Self::from_json_header_info(&j, header_info)
    }
}

impl Statements {
    /// Returns statements for a specific property, filtering server-side.
    pub async fn get_for_property(
        id: &EntityId,
        property_id: &str,
        api: &RestApi,
    ) -> Result<Self, RestApiError> {
        Self::get_for_property_match(id, property_id, api, RevisionMatch::default()).await
    }

    /// Returns statements for a specific property, with revision matching.
    pub async fn get_for_property_match(
        id: &EntityId,
        property_id: &str,
        api: &RestApi,
        rm: RevisionMatch,
    ) -> Result<Self, RestApiError> {
        let path = Self::get_rest_api_path(id)?;
        let mut params = HashMap::new();
        params.insert("property".to_string(), property_id.to_string());
        let mut request = api
            .wikibase_request_builder(&path, params, reqwest::Method::GET)
            .await?
            .build()?;
        rm.modify_headers(request.headers_mut())?;
        let (j, header_info) = Self::api_execute(api, request).await?;
        Self::from_json_header_info(&j, header_info)
    }
}

// POST
impl Statements {
    /// Posts a new statement to an entity
    pub async fn post(
        &self,
        id: &EntityId,
        statement: Statement,
        api: &mut RestApi,
    ) -> Result<Statement, RestApiError> {
        self.post_meta(id, statement, api, EditMetadata::default())
            .await
    }

    /// Posts a new statement to an entity with metadata
    pub async fn post_meta(
        &self,
        id: &EntityId,
        mut statement: Statement,
        api: &mut RestApi,
        em: EditMetadata,
    ) -> Result<Statement, RestApiError> {
        statement.set_id(None);
        let j0 = json!({"statement": statement});
        let request = self
            .generate_json_request(id, reqwest::Method::POST, j0, api, &em)
            .await?;
        let response = api.execute(request).await?;
        let (j, _statement_id) = self.filter_response_error(response).await?;
        // TODO add to self.statements?
        Statement::from_json(&j)
    }
}

impl HttpMisc for Statements {
    fn get_rest_api_path(id: &EntityId) -> Result<String, RestApiError> {
        Ok(format!(
            "/entities/{group}/{id}/statements",
            group = id.group()?
        ))
    }
}

impl Serialize for Statements {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut s = serializer.serialize_map(Some(self.statements.len()))?;
        for (property, statements) in &self.statements {
            s.serialize_entry(property, statements)?;
        }
        s.end()
    }
}

#[cfg(test)]
mod tests {
    use crate::statement_value::StatementValue;
    use http::{HeaderMap, HeaderValue};
    use wiremock::matchers::{bearer_token, body_partial_json, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use super::*;

    #[tokio::test]
    #[cfg_attr(miri, ignore)]
    async fn test_statements_get() {
        let v = std::fs::read_to_string("test_data/Q42.json").unwrap();
        let v: Value = serde_json::from_str(&v).unwrap();

        let mock_path = "/w/rest.php/wikibase/v1/entities/items/Q42/statements";
        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path(mock_path))
            .respond_with(ResponseTemplate::new(200).set_body_json(&v["statements"]))
            .mount(&mock_server)
            .await;
        let api = RestApi::builder(&(mock_server.uri() + "/w/rest.php"))
            .unwrap()
            .build();

        let statements = Statements::get(&EntityId::item("Q42"), &api).await.unwrap();
        assert!(!statements.property("P31").is_empty());
    }

    #[tokio::test]
    #[cfg_attr(miri, ignore)]
    async fn test_statements_post() {
        // #lizard forgives the complexity
        let id = EntityId::item("Q42");
        let v = std::fs::read_to_string("test_data/test_statements_post.json").unwrap();
        let v: Value = serde_json::from_str(&v).unwrap();
        let mock_path = "/w/rest.php/wikibase/v1/entities/items/Q42/statements";
        let mock_server = MockServer::start().await;
        let token = "FAKE_TOKEN";
        Mock::given(method("GET"))
            .and(path(mock_path))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(json!({}))
                    .insert_header("ETag", "123"),
            )
            .mount(&mock_server)
            .await;
        Mock::given(body_partial_json(
            json!({"statement": {"value":{"content":"Q5"}}}),
        ))
        .and(method("POST"))
        .and(path(mock_path))
        .and(bearer_token(token))
        .respond_with(ResponseTemplate::new(200).set_body_json(&v))
        .mount(&mock_server)
        .await;
        let mut api = RestApi::builder(&(mock_server.uri() + "/w/rest.php"))
            .unwrap()
            .with_access_token(token)
            .build();

        // Get and check existing statements
        let statements = Statements::get(&id, &api).await.unwrap();
        assert!(statements.property("P31").is_empty());

        // Create new statement
        let mut statement = Statement::default();
        statement.set_property("P31".into());
        statement.set_value(StatementValue::new_string("Q5"));

        // POST new statement
        let statement = statements.post(&id, statement, &mut api).await.unwrap();
        assert_eq!(statement.value(), &StatementValue::new_string("Q5"));
    }

    #[tokio::test]
    #[cfg_attr(miri, ignore)]
    async fn test_eq() {
        // To ensure that statement lists with and without header info are equal
        let id = EntityId::item("Q42");
        let mock_path = "/w/rest.php/wikibase/v1/entities/items/Q42/statements";
        let mock_server = MockServer::start().await;
        let token = "FAKE_TOKEN";
        Mock::given(method("GET"))
            .and(path(mock_path))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(json!({}))
                    .insert_header("ETag", "123"),
            )
            .mount(&mock_server)
            .await;
        let api = RestApi::builder(&(mock_server.uri() + "/w/rest.php"))
            .unwrap()
            .with_access_token(token)
            .build();

        // Get empty statements but with revision ID
        let statements1 = Statements::get(&id, &api).await.unwrap();
        let statements2 = Statements::default();
        assert_eq!(statements1, statements2);
    }

    #[test]
    fn test_insert_and_len() {
        let mut statements = Statements::default();
        assert_eq!(statements.len(), 0);
        let mut statement = Statement::default();
        statement.set_property("P31".into());
        statements.insert(statement.clone());
        statements.insert(statement.clone());
        statement.set_property("P1".into());
        statements.insert(statement.clone());
        assert_eq!(statements.len(), 3);
    }

    #[test]
    fn test_statements_statements() {
        let mut statements = Statements::default();
        let mut statement = Statement::default();
        statement.set_property("P31".into());
        statements.insert(statement.clone());
        statement.set_property("P1".into());
        statements.insert(statement.clone());
        assert_eq!(statements.statements().len(), 2);
        statements.statements_mut().remove("P31");
        assert_eq!(statements.statements().len(), 1);
    }

    #[test]
    fn test_header_info() {
        let mut headers = HeaderMap::new();
        headers.insert("ETag", HeaderValue::from_str("1234567890").unwrap());
        headers.insert(
            "Last-Modified",
            HeaderValue::from_str("Wed, 21 Oct 2015 07:28:00 GMT").unwrap(),
        );
        let hi = HeaderInfo::from_header(&headers);
        let mut statements = Statements::default();
        assert_eq!(statements.header_info(), &HeaderInfo::default());
        statements.header_info = hi.to_owned();
        assert_eq!(statements.header_info(), &hi);
    }

    #[test]
    fn test_get_id_statement_map() {
        let mut statements = Statements::default();
        let mut statement = Statement::default();
        statement.set_id(Some("Q1".into()));
        statement.set_property("P31".into());
        statements.insert(statement.clone());
        statement.set_id(Some("Q2".into()));
        statement.set_property("P1".into());
        statements.insert(statement.clone());
        let id_statement_map = statements.get_id_statement_map();
        assert_eq!(id_statement_map.len(), 2);
        assert_eq!(id_statement_map.get("Q1").unwrap().property().id(), "P31");
        assert_eq!(id_statement_map.get("Q2").unwrap().property().id(), "P1");
    }

    #[test]
    fn test_get_statements_without_id() {
        let mut statements = Statements::default();
        let mut statement = Statement::default();
        statement.set_id(Some("Q1".into()));
        statement.set_property("P31".into());
        statements.insert(statement.clone());
        statement.set_id(None);
        statement.set_property("P1".into());
        statements.insert(statement.clone());
        let statements_without_id = statements.get_statements_without_id();
        assert_eq!(statements_without_id.len(), 1);
        assert_eq!(statements_without_id[0].property().id(), "P1");
    }

    #[tokio::test]
    #[cfg_attr(miri, ignore)]
    async fn test_statements_get_for_property() {
        let v = std::fs::read_to_string("test_data/Q42.json").unwrap();
        let v: Value = serde_json::from_str(&v).unwrap();
        let p31_statements = json!({"P31": v["statements"]["P31"]});

        let mock_server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path(
                "/w/rest.php/wikibase/v1/entities/items/Q42/statements",
            ))
            .and(wiremock::matchers::query_param("property", "P31"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&p31_statements))
            .mount(&mock_server)
            .await;
        let api = RestApi::builder(&(mock_server.uri() + "/w/rest.php"))
            .unwrap()
            .build();

        let id = EntityId::item("Q42");
        let stmts = Statements::get_for_property(&id, "P31", &api)
            .await
            .unwrap();
        assert!(!stmts.property("P31").is_empty());
        assert!(stmts.property("P21").is_empty());
    }

    #[test]
    fn test_patch() {
        let mut statements1 = Statements::default();
        let mut statement = Statement::default();
        statement.set_id(Some("Q1".into()));
        statement.set_property("P31".into());
        statements1.insert(statement.clone());
        statement.set_id(Some("Q2".into()));
        statement.set_property("P1".into());
        statements1.insert(statement.clone());

        let mut statements2 = Statements::default();
        statement.set_id(Some("Q1".into()));
        statement.set_property("P31".into());
        statements2.insert(statement.clone());
        statement.set_id(Some("Q3".into()));
        statement.set_property("P1".into());
        statements2.insert(statement.clone());

        let patch = statements1.patch(&statements2).unwrap();
        assert_eq!(patch.patch().len(), 2);
        assert_eq!(patch.patch()[0].op(), "remove");
        assert_eq!(patch.patch()[1].op(), "add");
    }
}