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
use crate::api::*;
use crate::AnnotationDataSet;
use crate::DataValue;
use crate::Selector;
use crate::TextResource;
use chrono::Local;

use nanoid::nanoid;
use std::borrow::Cow;

const CONTEXT_ANNO: &str = "http://www.w3.org/ns/anno.jsonld";
const NS_ANNO: &str = "http://www.w3.org/ns/anno/";

pub trait IRI<'store> {
    /// Return the identifier as an IRI, suitable to identify RDF resources
    /// This will apply some transformations if there are invalid characters in the ID
    /// A default prefix will be prepended if the identifier was not an IRI yet.
    fn iri(&self, default_prefix: &str) -> Option<Cow<'store, str>>;
}

impl<'store> IRI<'store> for ResultItem<'store, DataKey> {
    fn iri(&self, default_set_prefix: &str) -> Option<Cow<'store, str>> {
        Some(into_iri(
            self.id().expect("key must have an ID"),
            &self
                .set()
                .iri(default_set_prefix)
                .expect("set must have an ID"),
        ))
    }
}

impl<'store> IRI<'store> for ResultItem<'store, Annotation> {
    fn iri(&self, default_prefix: &str) -> Option<Cow<'store, str>> {
        self.id().map(|x| into_iri(x, default_prefix))
    }
}
impl<'store> IRI<'store> for ResultItem<'store, TextResource> {
    fn iri(&self, default_prefix: &str) -> Option<Cow<'store, str>> {
        self.id().map(|x| into_iri(x, default_prefix))
    }
}
impl<'store> IRI<'store> for ResultItem<'store, AnnotationDataSet> {
    fn iri(&self, default_prefix: &str) -> Option<Cow<'store, str>> {
        self.id().map(|x| into_iri(x, default_prefix))
    }
}

/// Tests if a character is valid or not in an IRI
fn invalid_in_iri(c: char) -> bool {
    c == ' ' || c == '\t' || c == '\n' || c == '"'
}

/// Tests whether a string is a valid IRI
pub fn is_iri(s: &str) -> bool {
    if let Some(pos) = s.find(":") {
        if s.find(invalid_in_iri).is_some() {
            return false;
        }
        let scheme = &s[..pos];
        match scheme {
            "http" | "https" | "urn" | "file" | "_" => true,
            _ => false,
        }
    } else {
        false
    }
}

/// Transforms a string into an IRI, by prepending the prefix if necessary
fn into_iri<'a>(s: &'a str, mut prefix: &str) -> Cow<'a, str> {
    if is_iri(s) {
        Cow::Borrowed(s)
    } else {
        if prefix.is_empty() {
            prefix = "_:";
        }
        let separator = prefix.chars().last();
        if separator == Some('/') || separator == Some('#') || separator == Some(':') {
            Cow::Owned(format!(
                "{}{}",
                prefix,
                s.replace(invalid_in_iri, "-").as_str()
            ))
        } else {
            Cow::Owned(format!(
                "{}/{}",
                prefix,
                s.replace(invalid_in_iri, "-").as_str()
            ))
        }
    }
}

fn value_to_json(value: &DataValue) -> String {
    match value {
        DataValue::String(s) => format!("\"{}\"", s.replace("\n", "\\n").replace("\"", "\\\"")),
        x => x.to_string(),
    }
}

pub struct WebAnnoConfig {
    /// IRI prefix for Annotation Identifiers. Will be prepended if the annotations public ID is not an IRI yet.
    pub default_annotation_iri: String,

    /// Generate a random annotation IRI if it does not exist yet? (non-deterministic!)
    pub generate_annotation_iri: bool,

    /// IRI prefix for Annotation Data Sets. Will be prepended if the annotation data set public ID is not an IRI yet.
    pub default_set_iri: String,

    /// IRI prefix for Text Resources. Will be prepended if the resource public ID is not an IRI yet.
    pub default_resource_iri: String,

    /// Extra JSON-LD context to export, these must be URLs to JSONLD files.
    pub extra_context: Vec<String>,

    /// Automatically add a 'generated' triple for each annotation, with the timestamp of serialisation
    pub auto_generated: bool,

    /// Automatically add a 'generator' triple for each annotation, with the software details
    pub auto_generator: bool,

    /// Automatically generate a JSON-LD context alias for all URIs in keys, maps URI prefixes to namespace prefixes
    pub context_namespaces: Vec<(String, String)>,
}

impl Default for WebAnnoConfig {
    fn default() -> Self {
        Self {
            default_annotation_iri: "_:".to_string(),
            generate_annotation_iri: false,
            default_set_iri: "_:".to_string(),
            default_resource_iri: "_:".to_string(),
            extra_context: Vec::new(),
            auto_generated: true,
            auto_generator: true,
            context_namespaces: Vec::new(),
        }
    }
}

impl WebAnnoConfig {
    pub fn with_namespace(mut self, prefix: String, uri: String) -> Self {
        self.context_namespaces.push((uri, prefix));
        self
    }

    pub fn uri_to_namespace<'a>(&self, s: &'a str) -> Cow<'a, str> {
        for (uri_prefix, ns_prefix) in self.context_namespaces.iter() {
            if s.starts_with(uri_prefix) {
                return Cow::Owned(format!("{}:{}", ns_prefix, &s[uri_prefix.len()..]));
            }
        }
        Cow::Borrowed(s)
    }

    /// Generates a JSON-LD string to use for @context
    pub fn serialize_context(&self) -> String {
        let mut out = String::new();
        if !self.extra_context.is_empty() {
            if !self.context_namespaces.is_empty() {
                out += &format!(
                    "[ \"{}\", {}, {{ {} }} ]",
                    CONTEXT_ANNO,
                    self.extra_context.join(", "),
                    self.serialize_context_namespaces(),
                );
            } else {
                out += &format!(
                    "[ \"{}\", {} ]",
                    CONTEXT_ANNO,
                    self.extra_context.join(", ")
                );
            }
        } else if !self.context_namespaces.is_empty() {
            out += &format!(
                "[ \"{}\", {{ {} }} ]",
                CONTEXT_ANNO,
                self.serialize_context_namespaces()
            );
        } else {
            out += &format!("\"{}\"", CONTEXT_ANNO);
        }
        out
    }

    fn serialize_context_namespaces(&self) -> String {
        let mut out = String::new();
        for (uri, namespace) in self.context_namespaces.iter() {
            out += &format!(
                "{}\"{}\": \"{}\"",
                if out.is_empty() { "" } else { ", " },
                namespace,
                uri,
            );
        }
        out
    }
}

impl<'store> ResultItem<'store, Annotation> {
    /// Outputs the annotation as a W3C Web Annotation, the JSON output will be on a single line without pretty formatting.
    pub fn to_webannotation(&self, config: &WebAnnoConfig) -> String {
        if let Selector::AnnotationDataSelector(..) | Selector::DataKeySelector(..) =
            self.as_ref().target()
        {
            //these can not be serialized
            return String::new();
        }
        let mut ann_out = String::with_capacity(1024);
        ann_out += "{ \"@context\": ";
        ann_out += &config.serialize_context();
        ann_out += ",";
        if let Some(iri) = self.iri(&config.default_annotation_iri) {
            ann_out += &format!("  \"id\": \"{}\",", iri);
        } else if config.generate_annotation_iri {
            let id = nanoid!();
            ann_out += &format!(
                " \"id\": \"{}\",",
                into_iri(&id, &config.default_annotation_iri)
            )
        }
        ann_out += " \"type\": \"Annotation\",";

        let mut body_out = String::with_capacity(512);
        let mut suppress_default_body_type = false;
        let mut suppress_body_id = false;
        let mut suppress_auto_generated = false;
        let mut suppress_auto_generator = false;

        let mut outputted_to_main = false;
        //gather annotation properties (outside of body)
        for data in self.data() {
            let key = data.key();
            let key_id = key.id().expect("keys must have an ID");
            match data.set().id() {
                Some(CONTEXT_ANNO) | Some(NS_ANNO) => match key_id {
                    "generated" => {
                        if outputted_to_main {
                            ann_out.push(',');
                        }
                        suppress_auto_generated = true;
                        outputted_to_main = true;
                        ann_out += &output_predicate_datavalue(key_id, data.value(), config);
                    }
                    "generator" => {
                        if outputted_to_main {
                            ann_out.push(',');
                        }
                        suppress_auto_generator = true;
                        outputted_to_main = true;
                        ann_out += &output_predicate_datavalue(key_id, data.value(), config);
                    }
                    "motivation" | "created" | "creator" => {
                        if outputted_to_main {
                            ann_out.push(',');
                        }
                        outputted_to_main = true;
                        ann_out += &output_predicate_datavalue(key_id, data.value(), config);
                    }
                    key_id => {
                        //other predicates -> go into body
                        if key_id == "type" {
                            suppress_default_body_type = true; //no need for the default because we provided one explicitly
                        } else if key_id == "id" {
                            suppress_body_id = true;
                        }
                        if !body_out.is_empty() {
                            body_out.push(',');
                        }
                        body_out += &output_predicate_datavalue(key_id, data.value(), config);
                    }
                },
                Some(_set_id) => {
                    //different set, go into body
                    let predicate = key.iri(&config.default_set_iri).expect("set must have ID");
                    if !body_out.is_empty() {
                        body_out.push(',');
                    }
                    body_out += &output_predicate_datavalue(&predicate, data.value(), config);
                }
                None => unreachable!("all sets should have a public identifier"),
            }
        }

        if config.auto_generated && !suppress_auto_generated {
            ann_out += &format!(" \"generated\": \"{}\",", Local::now().to_rfc3339());
        }
        if config.auto_generator && !suppress_auto_generator {
            ann_out += "  \"generator\": { \"id\": \"https://github.com/annotation/stam-rust\", \"type\": \"Software\", \"name\": \"STAM Library\"  },";
        }

        if !body_out.is_empty() {
            ann_out += " \"body\": {";
            if !suppress_default_body_type {
                ann_out += " \"type\": \"Dataset\",";
            }
            if !suppress_body_id {
                if let Some(iri) = self.iri(&config.default_annotation_iri) {
                    ann_out += &format!(" \"id\": \"{}/body\",", iri);
                } else if config.generate_annotation_iri {
                    let id = nanoid!();
                    ann_out += &format!(
                        " \"id\": \"{}\",",
                        into_iri(&id, &config.default_annotation_iri)
                    )
                }
            }
            ann_out += &body_out;
            ann_out += "},";
        }

        ann_out += &format!(
            " \"target\": {}",
            &output_selector(self.as_ref().target(), self.store(), config, false)
        );

        ann_out += "}";
        ann_out
    }
}

fn output_predicate_datavalue(
    predicate: &str,
    datavalue: &DataValue,
    config: &WebAnnoConfig,
) -> String {
    let value_is_iri = if let DataValue::String(s) = datavalue {
        is_iri(s)
    } else {
        false
    };
    if value_is_iri {
        // Any String value that is a valid IRI *SHOULD* be interpreted as such
        // in conversion from/to RDF.
        format!(
            "\"{}\": {{ \"id\": \"{}\" }}",
            config.uri_to_namespace(predicate),
            datavalue
        )
    } else {
        format!(
            "\"{}\": {}",
            config.uri_to_namespace(predicate),
            &value_to_json(datavalue)
        )
    }
}

fn output_selector(
    selector: &Selector,
    store: &AnnotationStore,
    config: &WebAnnoConfig,
    nested: bool,
) -> String {
    let mut ann_out = String::new();
    match selector {
        Selector::TextSelector(res_handle, tsel_handle, _)
        | Selector::AnnotationSelector(_, Some((res_handle, tsel_handle, _))) => {
            let resource = store.resource(*res_handle).expect("resource must exist");
            let textselection = resource
                .as_ref()
                .get(*tsel_handle)
                .expect("text selection must exist");
            ann_out += &format!(
                "{{ \"source\": \"{}\", \"selector\": {{ \"type\": \"TextPositionSelector\", \"start\": {}, \"end\": {} }} }}",
                into_iri(
                    resource.id().expect("resource must have ID"),
                    &config.default_resource_iri
                ),
                textselection.begin(),
                textselection.end(),
            );
        }
        Selector::AnnotationSelector(a_handle, None) => {
            let annotation = store.annotation(*a_handle).expect("annotation must exist");
            if let Some(iri) = annotation.iri(&config.default_annotation_iri) {
                ann_out += &format!("{{ \"id\": \"{}\", \"type\": \"Annotation\" }}", iri);
            } else {
                ann_out += "{ \"id\": null }";
                eprintln!("WARNING: Annotation points to an annotation that has no public ID! Unable to serialize to Web Annotatations");
            }
        }
        Selector::ResourceSelector(res_handle) => {
            let resource = store.resource(*res_handle).expect("resource must exist");
            ann_out += &format!(
                "{{ \"id\": \"{}\", \"type\": \"Text\" }}",
                into_iri(
                    resource.id().expect("resource must have ID"),
                    &config.default_resource_iri
                ),
            );
        }
        Selector::DataSetSelector(set_handle) => {
            let dataset = store.dataset(*set_handle).expect("resource must exist");
            ann_out += &format!(
                "{{ \"id\": \"{}\", \"type\": \"Dataset\" }}",
                into_iri(
                    dataset.id().expect("dataset must have ID"),
                    &config.default_resource_iri
                ),
            );
        }
        Selector::CompositeSelector(selectors) => {
            ann_out += "{ \"type\": \"http://www.w3.org/ns/oa#Composite\", \"items\": [";
            for (i, selector) in selectors.iter().enumerate() {
                ann_out += &format!("{}", &output_selector(selector, store, config, true));
                if i != selectors.len() - 1 {
                    ann_out += ",";
                }
            }
            ann_out += " ]}";
        }
        Selector::MultiSelector(selectors) => {
            ann_out += "{ \"type\": \"http://www.w3.org/ns/oa#Independents\", \"items\": [";
            for (i, selector) in selectors.iter().enumerate() {
                ann_out += &format!("{}", &output_selector(selector, store, config, true));
                if i != selectors.len() - 1 {
                    ann_out += ",";
                }
            }
            ann_out += " ]}";
        }
        Selector::DirectionalSelector(selectors) => {
            ann_out += "{ \"type\": \"http://www.w3.org/ns/oa#List\", \"items\": [";
            for (i, selector) in selectors.iter().enumerate() {
                ann_out += &format!("{}", &output_selector(selector, store, config, true));
                if i != selectors.len() - 1 {
                    ann_out += ",";
                }
            }
            ann_out += " ]}";
        }
        Selector::DataKeySelector(..) | Selector::AnnotationDataSelector(..) => {
            if nested {
                eprintln!("WARNING: DataKeySelector and AnnotationDataSelectors can not be serialized to Web Annotation, skipping!!");
            } else {
                unreachable!("DataKeySelector and AnnotationDataSelectors can not be serialized to Web Annotation (was tested earlier)");
            }
        }
        Selector::RangedTextSelector { .. } | Selector::RangedAnnotationSelector { .. } => {
            if nested {
                let subselectors: Vec<_> = selector.iter(store, false).collect();
                for (i, subselector) in subselectors.iter().enumerate() {
                    ann_out += &format!("{}", &output_selector(&subselector, store, config, false));
                    if i != subselectors.len() - 1 {
                        ann_out += ",";
                    }
                }
            } else {
                unreachable!(
                "Internal Ranged selectors can not be serialized directly, they can be serialized only when under a complex selector",
            );
            }
        }
    }
    ann_out
}