nostralink 0.2.4

Linked data library for nostr
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
//! RDF Result sets

use super::vars as Vars;
use crate::err::LDError;
use language::Language;
use nostr::{
    event::EventId, types::url::Error as RelayUrlError,
    types::url::ParseError as RelayUrlParseError, PublicKey, RelayUrl,
    Timestamp,
};
use oxigraph::model::{IriParseError, NamedNode};
use oxiri::Iri;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt;
use std::marker::PhantomData;
use std::time::SystemTime;
use url::Url;

// Extracts/converts values from a RdfResultRow
pub trait RowExtractor {
    fn event_id(&self) -> Result<EventId, nostr::event::Error> {
        Err(nostr::event::Error::InvalidId)
    }

    fn event_id_from_var(
        &self,
        _field: &str,
    ) -> Result<EventId, nostr::event::Error> {
        Err(nostr::event::Error::InvalidId)
    }

    fn public_key(&self) -> Result<PublicKey, nostr::key::Error> {
        Err(nostr::key::Error::InvalidPublicKey)
    }

    fn seen_at(&self) -> Option<Timestamp> {
        None
    }

    fn content_type(&self) -> Option<String> {
        None
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum RdfCellValue {
    Int(i32),
    UnsignedInt(u32),
    Float(f64),
    Text(String),
    Node(String),
    Blank(),
}

impl TryInto<i32> for RdfCellValue {
    type Error = ();

    fn try_into(self) -> Result<i32, Self::Error> {
        match self {
            RdfCellValue::Int(value) => Ok(value),
            _ => todo!(),
        }
    }
}

impl TryInto<u64> for RdfCellValue {
    type Error = &'static str;

    fn try_into(self) -> Result<u64, Self::Error> {
        match self {
            RdfCellValue::Int(value) => {
                let v: u64 = value as u64;
                Ok(v)
            }
            _ => todo!(),
        }
    }
}

impl TryInto<PublicKey> for RdfCellValue {
    type Error = nostr::key::Error;

    fn try_into(self) -> Result<PublicKey, Self::Error> {
        match self {
            RdfCellValue::Text(value) => Ok(PublicKey::parse(&value)?),
            _ => Err(Self::Error::InvalidPublicKey),
        }
    }
}

impl fmt::Display for RdfCellValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            RdfCellValue::Int(value) => {
                write!(f, "{}", value)
            }
            RdfCellValue::Float(value) => {
                write!(f, "{}", value)
            }
            RdfCellValue::Text(value) => {
                write!(f, "{}", value)
            }
            RdfCellValue::Node(value) => {
                write!(f, "{}", value)
            }
            _ => {
                write!(f, "NA")
            }
        }
    }
}

impl RdfCellValue {
    pub fn to_named_node(&self) -> Result<NamedNode, IriParseError> {
        match self {
            RdfCellValue::Node(value) => {
                Ok(NamedNode::from(Iri::parse(value.to_string())?))
            }
            RdfCellValue::Text(value) => {
                Ok(NamedNode::from(Iri::parse(value.to_string())?))
            }
            _ => todo!(),
        }
    }
    pub fn to_event_id(&self) -> Result<EventId, nostr::event::Error> {
        match self {
            RdfCellValue::Text(value) => Ok(EventId::parse(value)?),
            _ => Err(nostr::event::Error::InvalidId),
        }
    }
    pub fn to_public_key(&self) -> Result<PublicKey, nostr::key::Error> {
        match self {
            RdfCellValue::Text(value) => Ok(PublicKey::parse(value)?),
            _ => Err(nostr::key::Error::InvalidPublicKey),
        }
    }

    pub fn to_language(&self) -> Result<Language, Box<dyn std::error::Error>> {
        match self {
            RdfCellValue::Text(value) => {
                match Language::from_tag(value.as_str()) {
                    Some(lang) => Ok(lang),
                    None => Err(Box::from("No such language")),
                }
            }
            _ => Err(Box::from("Invalid cell")),
        }
    }
}

impl TryInto<i32> for RdfCell {
    type Error = ();

    fn try_into(self) -> Result<i32, Self::Error> {
        self.value.try_into()
    }
}

impl TryInto<u64> for RdfCell {
    type Error = &'static str;

    fn try_into(self) -> Result<u64, Self::Error> {
        self.value.try_into()
    }
}

impl TryInto<String> for &RdfCell {
    type Error = &'static str;

    fn try_into(self) -> Result<String, Self::Error> {
        Ok(format!("{}", self.value))
    }
}

impl TryInto<Timestamp> for &RdfCell {
    type Error = LDError;

    fn try_into(self) -> Result<Timestamp, Self::Error> {
        match self.value {
            RdfCellValue::Int(value) => Ok(Timestamp::from_secs(
                value
                    .try_into()
                    .map_err(|_| LDError::InvalidTimestampError)?,
            )),
            _ => Err(LDError::CellValueError),
        }
    }
}

impl TryInto<PublicKey> for &RdfCell {
    type Error = nostr::key::Error;

    fn try_into(self) -> Result<PublicKey, Self::Error> {
        match &self.value {
            RdfCellValue::Text(value) => Ok(PublicKey::parse(value)?),
            _ => Err(Self::Error::InvalidPublicKey),
        }
    }
}

impl TryInto<RelayUrl> for &RdfCell {
    type Error = RelayUrlError;

    fn try_into(self) -> Result<RelayUrl, Self::Error> {
        match &self.value {
            RdfCellValue::Text(value) => {
                let vals = value.to_string();
                Ok(RelayUrl::parse(vals.as_str())?)
            }
            _ => Err(RelayUrlError::Url(RelayUrlParseError::EmptyHost)),
        }
    }
}

impl RdfCell {
    pub fn new(name: String, value: RdfCellValue) -> Self {
        Self { name, value }
    }

    pub fn new_text(name: &str, s: String) -> Self {
        Self {
            name: name.to_string(),
            value: RdfCellValue::Text(s),
        }
    }

    pub fn to_string(&self) -> String {
        format!("{}", self.value)
    }

    pub fn to_int(&self) -> Option<i32> {
        match self.value {
            RdfCellValue::Int(value) => Some(value),
            _ => None,
        }
    }

    pub fn to_float(&self) -> Option<f64> {
        match self.value {
            RdfCellValue::Float(value) => Some(value),
            _ => None,
        }
    }

    pub fn to_unsigned_int(&self) -> Option<u32> {
        match self.value {
            RdfCellValue::Int(value) => Some(value as u32),
            RdfCellValue::UnsignedInt(value) => Some(value),
            _ => None,
        }
    }

    pub fn to_ts(&self) -> Result<Timestamp, LDError> {
        match self.value {
            RdfCellValue::Int(value) => Ok(Timestamp::from_secs(
                value
                    .try_into()
                    .map_err(|_| LDError::InvalidTimestampError)?,
            )),
            _ => Err(LDError::CellValueError),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RdfCell {
    pub name: String,
    pub value: RdfCellValue,
}

pub type RdfResultRow = HashMap<String, RdfCell>;

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TRdfResultRow<T>(pub HashMap<String, RdfCell>, pub PhantomData<T>)
where
    T: std::clone::Clone;

impl<T: std::clone::Clone> From<TRdfResultRow<T>> for RdfResultRow {
    fn from(row: TRdfResultRow<T>) -> Self {
        row.0
    }
}

pub const CONCAT_SEP: &str = ",";

impl<T: std::clone::Clone> TRdfResultRow<T> {
    // Commonly used SparQL variable names

    pub fn get(&self, key: &str) -> Option<&RdfCell> {
        self.0.get(key)
    }

    pub fn get_string(&self, key: &str) -> Option<String> {
        self.0.get(key).map(|cell| cell.to_string())
    }

    pub fn get_i32(&self, key: &str) -> Option<i32> {
        self.0.get(key).and_then(|cell| cell.to_int())
    }

    pub fn get_u32(&self, key: &str) -> Option<u32> {
        self.0.get(key).and_then(|cell| cell.to_unsigned_int())
    }

    pub fn get_float(&self, key: &str) -> Option<f64> {
        self.0.get(key).and_then(|cell| cell.to_float())
    }

    pub fn get_ts(&self, key: &str) -> Option<Timestamp> {
        self.0.get(key).and_then(|cell| cell.try_into().ok())
    }

    pub fn get_node(&self, key: &str) -> Option<NamedNode> {
        self.0
            .get(key)
            .and_then(|cell| cell.value.to_named_node().ok())
    }

    pub fn get_url(&self, key: &str) -> Option<Url> {
        self.0
            .get(key)
            .and_then(|cell| Url::parse(&cell.to_string()).ok())
    }

    /// Deconcat a key to a vec of strings
    pub fn deconcat(
        &self,
        key: &str,
        sep: Option<&str>,
        dedup: bool,
    ) -> Option<Vec<String>> {
        if let Some(cell) = self.0.get(key) {
            let mut values: Vec<String> = cell
                .to_string()
                .split(sep.unwrap_or(CONCAT_SEP))
                .map(str::to_string)
                .collect();

            if dedup {
                values.sort_unstable();
                values.dedup();
            }
            Some(values)
        } else {
            None
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RdfResultSet {
    pub when: SystemTime,
    pub column_headings: Vec<String>,
    pub rows: Vec<RdfResultRow>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TRdfResultSet<T: std::clone::Clone> {
    pub when: SystemTime,
    pub rows: Vec<TRdfResultRow<T>>,
}

impl<T: std::clone::Clone> From<RdfResultRow> for TRdfResultRow<T> {
    fn from(val: RdfResultRow) -> Self {
        TRdfResultRow::<T>(val, PhantomData)
    }
}

impl<T: std::clone::Clone> From<RdfResultSet> for TRdfResultSet<T> {
    fn from(val: RdfResultSet) -> Self {
        TRdfResultSet::<T> {
            when: val.when,
            rows: val.rows.iter().map(|r| r.clone().into()).collect(),
        }
    }
}

impl<T: std::clone::Clone> TRdfResultSet<T> {
    pub fn count(&self) -> usize {
        self.rows.len()
    }

    /// Returns the first row
    pub fn first(&self) -> Option<TRdfResultRow<T>> {
        if self.count() > 0 {
            return Some(self.rows[0].clone());
        }

        None
    }
}

impl RdfResultSet {
    pub fn count(&self) -> usize {
        self.rows.len()
    }

    /// Returns the first row
    pub fn first(&self) -> Option<RdfResultRow> {
        if self.count() > 0 {
            return Some(self.rows[0].clone());
        }

        None
    }
}

impl<T: std::clone::Clone> RowExtractor for TRdfResultRow<T> {
    fn event_id(&self) -> Result<EventId, nostr::event::Error> {
        self.event_id_from_var(Vars::RP_EVENT_ID)
            .or(self.event_id_from_var(Vars::EVENT_ID))
    }

    fn event_id_from_var(
        &self,
        var: &str,
    ) -> Result<EventId, nostr::event::Error> {
        match self.get(var) {
            Some(ev_id) => Ok(ev_id.value.to_event_id()?),
            None => Err(nostr::event::Error::InvalidId),
        }
    }

    fn public_key(&self) -> Result<PublicKey, nostr::key::Error> {
        match self.get(Vars::PUBK) {
            Some(pubk) => Ok(pubk.value.to_public_key()?),
            None => Err(nostr::key::Error::InvalidPublicKey),
        }
    }

    /// Returns the timestamp of the time this event was seen
    fn seen_at(&self) -> Option<Timestamp> {
        match self.get(Vars::EVENT_SEEN_AT) {
            Some(cell) => cell.try_into().ok(),
            None => None,
        }
    }

    fn content_type(&self) -> Option<String> {
        self.get(Vars::CONTENT_TYPE).map(|cell| cell.to_string())
    }
}