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
// from_json.rs
//
// Copyright © 2018
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

extern crate serde_json;

use {
    Coordinate,
    DataValue,
    DataValueType,
    Entity,
    EntityType,
    EntityValue,
    LocaleString,
    MonoLingualText,
    QuantityValue,
    Reference,
    SearchResults,
    SearchResultEntity,
    SearchQuery,
    SiteLink,
    Snak,
    SnakType,
    Statement,
    StatementRank,
    TimeValue,
    Value,
    WikibaseError
};
use std;

/// Deserializes a Wikibase entity from JSON
///
/// Takes a serde JSON value and deserializes the complete data into a Rust
/// native data structure.
pub fn entity_from_json(json: &serde_json::Value)
    -> Result<Entity, WikibaseError> {
    let id = match &json["id"].as_str() {
        &Some(value) => value.to_string(),
        &None => return Err(WikibaseError::Serialization("ID missing".to_string()))
    };

    match &json.get("missing") {
        &Some(_) => {
            return Ok(
                Entity::new(id, vec![], vec![], vec![], vec![], None, true)
            )
        }
        &None => {}
    };

    let descriptions = locale_strings_from_json(&json, "descriptions")?;
    let aliases = locale_string_array_from_json(&json, "aliases")?;
    let labels = locale_strings_from_json(&json, "labels")?;
    let statements = statements_from_json(&json)?;
    let sitelinks = sitelinks_from_json(&json)?;

    Ok(Entity::new(
        id,
        labels,
        descriptions,
        aliases,
        statements,
        sitelinks,
        false))
}

/// Search result entity from JSON
///
/// Takes a serde JSON value of search results and deserializes it. Returns a
/// vector of results or an error.
pub fn search_result_entities_from_json(
    json: &serde_json::Value,
    query: &SearchQuery
    ) -> Result<SearchResults, WikibaseError> {
    let results_json = match &json["search"].as_array() {
        &Some(value) => value,
        &None => return Err(WikibaseError::Serialization("No search results".to_string()))
    };
    let mut results = vec![];

    for result in results_json {
        results.push(search_result_entity_from_json(&result, &query)?);
    }

    Ok(SearchResults::new(results))
}

/// Creates a search result entity from JSON
///
/// The locale of the texts is the same as the `uselang` parameter in the
/// request URL.
fn search_result_entity_from_json(
    result_json: &serde_json::Value,
    query: &SearchQuery
    ) -> Result<SearchResultEntity, WikibaseError> {
    let id = match result_json["id"].as_str() {
        Some(value) => value,
        None => return Err(WikibaseError::Serialization("Search result ID".to_string()))
    };
    let label_text = match result_json["label"].as_str() {
        Some(value) => value,
        None => return Err(WikibaseError::Serialization("Search result label".to_string()))
    };
    let label = LocaleString::new("en", label_text);
    let description = match result_json["description"].as_str() {
        Some(value) => Some(LocaleString::new("en", value)),
        None => None
    };
    let aliases = aliases_from_json(result_json, &query)?;
    let entity_type = EntityType::new_from_id(id)?;

    Ok(SearchResultEntity::new(id, entity_type, label, description, aliases))
}

/// Alias from JSON
///
/// Takes a serde JSON value and deserializes the aliases into a vector of
/// LocaleStrings.
fn aliases_from_json(
    json_value: &serde_json::Value,
    query: &SearchQuery
    ) -> Result<Vec<LocaleString>, WikibaseError> {
    let aliases_array = match json_value.get("aliases") {
        Some(value) => {
            match value.as_array() {
                Some(value_array) => value_array,
                None => return Err(WikibaseError::Serialization("Aliases array".to_string()))
            }
        },
        None => return Ok(vec![])
    };

    let mut aliases = vec![];

    for alias in aliases_array.iter() {
        match alias.as_str() {
            Some(value) => aliases.push(
                LocaleString::new(query.search_lang(), &value)),
            None => return Err(WikibaseError::Serialization("Aliases string".to_string()))
        };
    }

    Ok(aliases)
}

/// Serializes a numeric value to a f64 option
///
/// Takes a value of the following structure:
/// {"key": "4"}
pub fn float_from_json(value: &serde_json::Map<std::string::String,
    serde_json::Value>, key: &str) -> Option<f64> {
    let single_value = match value.get(key) {
        Some(value) => value,
        None => return None
    };

    let value_string = match single_value.as_str() {
        Some(value) => value,
        None => return None,
    };

    match value_string.parse() {
        Ok(value) => Some(value),
        Err(_) => None
    }
}

/// Serializes a Wikidata claim
///
/// Takes a json object and returns a result.
///
/// # Errors
///
/// An error is returned when the json can't be interpreted as an object,
/// or the main snak is missing.
pub fn statement_from_json(json_claim: &serde_json::Value)
    -> Result<Statement, WikibaseError> {
    let claim_object = match &json_claim.as_object() {
        &Some(value) => value,
        &None => return Err(WikibaseError::Serialization("Statement".to_string()))
    };

    let claim_type = match claim_object["type"].as_str() {
        Some(value) => value,
        None => return Err(WikibaseError::Serialization("Statement type error".to_string()))
    };

    let rank_string = match claim_object["rank"].as_str() {
        Some(value) => value,
        None => return Err(WikibaseError::Serialization("Statement rank error".to_string()))
    };

    let rank = match rank_string {
        "deprecated" => StatementRank::Deprecated,
        "normal" => StatementRank::Normal,
        "preferred" => StatementRank::Preferred,
        _ => return Err(WikibaseError::Serialization("Statement rank error".to_string()))
    };

    let main_snak = match &claim_object["mainsnak"].as_object() {
        &Some(snak_json) => {
            snak_from_json(snak_json)?
        }
        &None => return Err(WikibaseError::Serialization("Main snak".to_string()))
    };

    let qualifiers = match &claim_object.get("qualifiers") {
        // Qualifiers are an object with property keys that contain
        // an array of snaks. {"P817": [], ...}
        &Some(qualifiers) => snaks_object_from_json(&qualifiers)?,
        &None => vec![]
    };

    let references = match &claim_object.get("references") {
        &Some(references_array_json) => reference_array_from_json(&references_array_json)?,
        &None => vec![]
    };

    Ok(Statement::new(claim_type, rank, main_snak, qualifiers, references))
}

/// Serializes a locale string
///
/// A locale string is a JSON object:
/// {"language": "de", "value": "Label"}
///
/// Returns a LocaleString inside of an option:
/// LocaleString {language: "de", value: "Label"}
fn locale_string_from_json(string_object: &serde_json::Value)
    -> Result<LocaleString, WikibaseError> {
    let language = match string_object["language"].as_str() {
        Some(value) => value,
        None => return Err(WikibaseError::Serialization("Can't deserialize language in locale string".to_string()))
    };

    match string_object["value"].as_str() {
        Some(value) => Ok(LocaleString::new(language, value)),
        None => Err(WikibaseError::Serialization("Can't deserialize value in locale string".to_string()))
    }
}

/// Serializes an array of locale strings (e.g. aliases)
///
/// # JSON structure:
///
/// {"aliases": {"en", [{"language": "en", "value": "Alias 1"},
/// {"language": "en", "value": "Alias 2"}, ... ]}}
fn locale_string_array_from_json(item: &serde_json::Value, key: &str)
    -> Result<Vec<LocaleString>, WikibaseError> {
    let mut aliases = vec![];

    let lang_object = match &item[key].as_object() {
        &Some(value) => value,
        &None => return Err(WikibaseError::Serialization("Locale object".to_string()))
    };

    for (language, string_array_json) in lang_object.iter() {
        let string_array = match string_array_json.as_array() {
            Some(value) => value,
            None => return Err(WikibaseError::Serialization("Locale array".to_string()))
        };

        for item_json in string_array.iter() {
            match item_json["value"].as_str() {
                Some(value) => aliases.push(LocaleString::new(language.to_string(), value.to_string())),
                None => return Err(WikibaseError::Serialization("Locale value".to_string()))
            }
        }
    }

    Ok(aliases)
}

/// Serialize single locale strings from JSON
///
/// Takes a serde-JSON value and returns a vector of locale strings inside
/// of a result.
fn locale_strings_from_json(item: &serde_json::Value, key: &str)
    -> Result<Vec<LocaleString>, WikibaseError> {
    let mut labels = vec![];

    let label_object = match &item.get(key) {
        &Some(value) => {
            match value.as_object() {
                Some(object) => object,
                None => return Err(WikibaseError::Serialization("Locale string object not valid".to_string()))
            }
        }
        &None => return Err(WikibaseError::Serialization(format!("Key \"{}\" not found in object", key)))
    };

    for (_, string_object) in label_object.iter() {
        labels.push(locale_string_from_json(string_object)?);
    }

    Ok(labels)
}

/// Serialize statements from JSON
///
/// Function that takes a json value (an object) and deserializes all statements.
/// The statements are stored under the "claims" key. The first array has
/// property IDs as keys, with all statements for that property as values.
fn statements_from_json(item: &serde_json::Value)
    -> Result<Vec<Statement>, WikibaseError> {
    let statements_array = match &item["claims"].as_object() {
        &Some(value) => value,
        &None => return Err(WikibaseError::Serialization("Key \"claims\" missing in json object".to_string()))
    };

    let mut statements = vec![];

    for (_, property_statements) in statements_array.iter() {
        let property_statements_array = match &property_statements.as_array() {
            &Some(value) => value,
            &None => return Err(WikibaseError::Serialization("Statement array".to_string()))
        };

        for property_statement in property_statements_array.iter() {
            statements.push(statement_from_json(&property_statement)?);
        }
    }

    Ok(statements)
}

/// Serializes a Wikibase Snake from JSON
///
/// Takes a serde-JSON map and returns a single Snak inside or an error
/// inside of a result.
fn snak_from_json(snak_json: &serde_json::Map<std::string::String,
    serde_json::Value>) -> Result<Snak, WikibaseError> {
    let datatype = match snak_json["datatype"].as_str() {
        Some(value) => value,
        None => return Err(WikibaseError::Serialization("Datatype".to_string()))
    };
    let property = snak_json["property"].as_str().unwrap_or_else(|| {""});
    let snak_type = snak_json["snaktype"].as_str().unwrap_or_else(|| {""});

    if snak_type == "somevalue" {
        let snak = Snak::new(datatype, property, SnakType::UnknownValue, None);
        return Ok(snak)
    }

    if snak_type == "novalue" {
        let snak = Snak::new(datatype, property, SnakType::NoValue, None);
        return Ok(snak)
    }

    let data_value = match snak_json["datavalue"].as_object() {
        Some(value) => value,
        None => return Err(WikibaseError::Serialization("Data value not found".to_string()))
    };

    let data_value_type = match data_value["type"].as_str() {
        Some(value) => {
            DataValueType::new_from_str(value)?
        }
        None => return Err(WikibaseError::Serialization("Not type in data value".to_string()))
    };

    match data_value_type {
        DataValueType::EntityId => {
            let value_object = match data_value["value"].as_object() {
                Some(value) => value,
                None => return Err(WikibaseError::Serialization("Error serializing value object".to_string()))
            };
            let entity_value = EntityValue::new_from_object(value_object)?;
            let statement_value = Value::Entity(entity_value);
            let data_value = DataValue::new(data_value_type, statement_value);
            Ok(Snak::new(datatype, property, SnakType::Value, Some(data_value)))
        }
        DataValueType::Quantity => {
            let value_object = match data_value["value"].as_object() {
                Some(value) => value,
                None => return Err(WikibaseError::Serialization("Error serializing value object".to_string()))
            };
            let quantity_value = QuantityValue::new_from_object(value_object)?;
            let statement_value = Value::Quantity(quantity_value);
            let data_value = DataValue::new(data_value_type, statement_value);
            Ok(Snak::new(datatype, property, SnakType::Value, Some(data_value)))
        }
        DataValueType::GlobeCoordinate => {
            let value_object = match data_value["value"].as_object() {
                Some(value) => value,
                None => return Err(WikibaseError::Serialization("Error serializing value object".to_string()))
            };
            let coordinate = Coordinate::new_from_json(value_object)?;
            let coordinate_statement = Value::Coordinate(coordinate);
            let data_value = DataValue::new(data_value_type, coordinate_statement);
            Ok(Snak::new(datatype, property, SnakType::Value, Some(data_value)))
        }
        DataValueType::Time => {
            let value_object = match data_value["value"].as_object() {
                Some(value) => value,
                None => return Err(WikibaseError::Serialization("Error serializing value object".to_string()))
            };
            let time_value_struct = TimeValue::new_from_object(value_object);
            let time_value = Value::Time(time_value_struct);
            let data_value = DataValue::new(data_value_type, time_value);
            Ok(Snak::new(datatype, property, SnakType::Value, Some(data_value)))
        }
        DataValueType::MonoLingualText => {
            let value_object = match data_value["value"].as_object() {
                Some(value) => value,
                None => return Err(WikibaseError::Serialization("Error serializing value object".to_string()))
            };
            let mono_lingual_text = MonoLingualText::new_from_json(value_object)?;
            let mono_lingual_text_value = Value::MonoLingual(mono_lingual_text);
            let data_value = DataValue::new(data_value_type, mono_lingual_text_value);
            Ok(Snak::new(datatype, property, SnakType::Value, Some(data_value)))
        }
        DataValueType::StringType => {
            let value_string = match data_value["value"].as_str() {
                Some(value) => value,
                None => return Err(WikibaseError::Serialization("Error serializing value string".to_string()))
            };
            let statement_value = Value::StringValue(value_string.to_string());
            let data_value = DataValue::new(data_value_type, statement_value);
            Ok(Snak::new(datatype, property, SnakType::Value, Some(data_value)))
        }
    }
}

/// Serializes an object of snaks from JSON
///
/// Wikibase uses this structure for qualfiers and the references.
///
/// # JSON Documentation
///
/// Serializes a json that looks like this:
///
/// `
/// {"qualifiers": {"P1": [Snak1, Snak2], ... ]}}
/// `
fn snaks_object_from_json(snaks_object_json: &serde_json::Value)
    -> Result<Vec<Snak>, WikibaseError> {
    let mut snaks = vec![];

    let snaks_object = match &snaks_object_json.as_object() {
        &Some(value) => value,
        &None => return Err(WikibaseError::Serialization("Can't deserialize snaks object".to_string()))
    };

    // Loop over the property keys e.g. {"P817": [], ...}
    for (_, property_snaks) in snaks_object.iter() {
        let snak_array = match &property_snaks.as_array() {
            &Some(value) => value,
            &None => return Err(WikibaseError::Serialization("Can't deserialize snak array".to_string()))
        };

        // Loop over the qualifiers of one property e.g. {"P817": [Snak-A, Snak-B, ...]}
        for snak_json in snak_array.iter() {
            let snak_object = match &snak_json.as_object() {
                &Some(value) => value,
                &None => return Err(WikibaseError::Serialization("Can't deserialize snak object".to_string()))
            };

            snaks.push(snak_from_json(snak_object)?);
        }
    }

    Ok(snaks)
}

/// Serializes the references of a claim
///
/// Takes a serde-JSON value an returns a vector of references or an error
/// inside of a result. The JSON looks like this:
/// {"references": ["0": {"snaks": {"P1": [Snak1, Snak2]}, ... }]}
fn reference_array_from_json(references_array_json: &serde_json::Value)
    -> Result<Vec<Reference>, WikibaseError> {
    let mut references = vec![];

    let reference_array = match &references_array_json.as_array() {
        &Some(value) => value,
        &None => return Err(WikibaseError::Serialization("Reference array".to_string()))
    };

    for references_object_json in reference_array.iter() {
        let reference_object = match &references_object_json.as_object() {
            &Some(value) => value,
            &None => return Err(WikibaseError::Serialization("Reference object".to_string()))
        };

        let snaks_array = match &reference_object.get("snaks") {
            &Some(value) => value,
            &None => return Err(WikibaseError::Serialization("Reference snak object".to_string()))
        };

        references.push(Reference::new(snaks_object_from_json(snaks_array)?));
    }

    Ok(references)
}

/// Serialize a vector of strings from JSON
///
/// Takes a serde-JSON value and returns a vector of Strings or an error
/// inside of a Result.
fn string_vector_from_json(json_values: &Vec<serde_json::Value>)
    -> Result<Vec<String>, WikibaseError> {
    let mut values = vec![];

    for json_value in json_values {
        let value = match json_value.as_str() {
            Some(value) => value,
            None => return Err(WikibaseError::Serialization("Error serializing string vector".to_string()))
        };

        values.push(value.to_string());
    }

    Ok(values)
}

/// Serialize sitelinks from JSON
///
/// Takes a serde-JSON value and returns a Result that contains either a
/// error or a Option. Properties for example don't contain sitelinks, so
/// the option will be None. If a Wikibase-item has sitelinks the Option
/// will contain a vector of Sitelinks.
fn sitelinks_from_json(item: &serde_json::Value)
    -> Result<Option<Vec<SiteLink>>, WikibaseError> {
    let sitelinks_array = match &item.get("sitelinks") {
        &Some(value) => {
            match value.as_object() {
                Some(value_object) => value_object,
                None => return Err(WikibaseError::Serialization("Key \"sitelinks\" missing in json object".to_string()))
            }
        }
        &None => return Ok(None)
    };

    let mut sitelinks = vec![];

    for (site_id, sitelink_object_json) in sitelinks_array.iter() {
        let sitelink_object = match &sitelink_object_json.as_object() {
            &Some(value) => value,
            &None => return Err(WikibaseError::Serialization("Error serializing sitelink object".to_string()))
        };

        let title = match &sitelink_object["title"].as_str() {
            &Some(value) => value,
            &None => return Err(WikibaseError::Serialization("Error serializing sitelink title".to_string()))
        };

        let badges = match &sitelink_object["badges"].as_array() {
            &Some(value) => {
                string_vector_from_json(value)?
            }
            &None => return Err(WikibaseError::Serialization("Error serializing badges array".to_string()))
        };

        let sitelink = SiteLink::new(site_id.to_string(), title.to_string(), badges);
        sitelinks.push(sitelink);
    }

    Ok(Some(sitelinks))
}