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
use crate::graph::{Graph, Node, NodeContents};
use crate::helper::{get_current_da_time, get_current_time, index_dec_to_ud};
use crate::{Channel, Result, UrbitAPIError};
use json::{object, JsonValue};

/// A struct which exposes Graph Store functionality
pub struct GraphStore<'a> {
    pub channel: &'a mut Channel,
}

impl<'a> GraphStore<'a> {
    /// Create a new Graph Store node using defaults from the connected ship and local time.
    /// This is a wrapper method around `Node::new()` which fills out a lot of boilerplate.
    pub fn new_node(&self, contents: &NodeContents) -> Node {
        // Add the ~ to the ship name to be used within the post as author
        let ship = format!("~{}", self.channel.ship_interface.ship_name);
        // The index. For chat the default is current `@da` time as atom encoding with a `/` in front.
        let index = format!("/{}", get_current_da_time());

        // Get the current Unix Time
        let unix_time = get_current_time();

        Node::new(
            index,
            ship.clone(),
            unix_time,
            vec![],
            contents.clone(),
            None,
        )
    }

    /// Create a new Graph Store node using a specified index and creation time
    /// using the connected ship as author
    pub fn new_node_specified(
        &self,
        node_index: &str,
        unix_time: u64,
        contents: &NodeContents,
    ) -> Node {
        // Add the ~ to the ship name to be used within the post as author
        let ship = format!("~{}", self.channel.ship_interface.ship_name);
        Node::new(
            node_index.to_string(),
            ship.clone(),
            unix_time,
            vec![],
            contents.clone(),
            None,
        )
    }

    /// Add node to Graph Store
    pub fn add_node(
        &mut self,
        resource_ship: &str,
        resource_name: &str,
        node: &Node,
    ) -> Result<()> {
        let prepped_json = object! {
            "add-nodes": {
                "resource": {
                    "ship": resource_ship,
                    "name": resource_name
                },
            "nodes": node.to_json()
            }
        };

        let resp = (&mut self.channel).poke("graph-push-hook", "graph-update", &prepped_json)?;

        if resp.status().as_u16() == 204 {
            Ok(())
        } else {
            return Err(UrbitAPIError::FailedToAddNodesToGraphStore(
                resource_name.to_string(),
            ));
        }
    }

    /// Remove nodes from Graph Store using the provided list of indices
    pub fn remove_nodes(
        &mut self,
        resource_ship: &str,
        resource_name: &str,
        indices: Vec<&str>,
    ) -> Result<()> {
        let prepped_json = object! {
            "remove-nodes": {
                "resource": {
                    "ship": resource_ship,
                    "name": resource_name
                },
            "indices": indices
            }
        };

        let resp = (&mut self.channel).poke("graph-push-hook", "graph-update", &prepped_json)?;

        if resp.status().as_u16() == 204 {
            Ok(())
        } else {
            return Err(UrbitAPIError::FailedToRemoveNodesFromGraphStore(
                resource_name.to_string(),
            ));
        }
    }

    /// Acquire a node from Graph Store
    pub fn get_node(
        &mut self,
        resource_ship: &str,
        resource_name: &str,
        node_index: &str,
    ) -> Result<Node> {
        let path_nodes = index_dec_to_ud(node_index);
        let path = format!("/node/{}/{}{}", resource_ship, resource_name, &path_nodes);
        let res = self
            .channel
            .ship_interface
            .scry("graph-store", &path, "json")?;

        // If successfully acquired node json
        if res.status().as_u16() == 200 {
            if let Ok(body) = res.text() {
                if let Ok(node_json) = json::parse(&body) {
                    return Node::from_graph_update_json(&node_json);
                }
            }
        }
        // Else return error
        Err(UrbitAPIError::FailedToGetGraphNode(format!(
            "/{}/{}/{}",
            resource_ship, resource_name, node_index
        )))
    }

    /// Acquire a subset of children of a node from Graph Store by specifying the start and end indices
    /// of the subset children.
    pub fn get_node_subset(
        &mut self,
        resource_ship: &str,
        resource_name: &str,
        node_index: &str,
        start_index: &str,
        end_index: &str,
    ) -> Result<Graph> {
        let path = format!(
            "/node-children-subset/{}/{}/{}/{}/{}",
            resource_ship, resource_name, node_index, end_index, start_index
        );
        let res = self
            .channel
            .ship_interface
            .scry("graph-store", &path, "json")?;

        // If successfully acquired node json
        if res.status().as_u16() == 200 {
            if let Ok(body) = res.text() {
                if let Ok(graph_json) = json::parse(&body) {
                    return Graph::from_json(graph_json);
                }
            }
        }
        // Else return error
        Err(UrbitAPIError::FailedToGetGraph(resource_name.to_string()))
    }

    /// Acquire a graph from Graph Store
    pub fn get_graph(&mut self, resource_ship: &str, resource_name: &str) -> Result<Graph> {
        let path = format!("/graph/{}/{}", resource_ship, resource_name);
        let res = self
            .channel
            .ship_interface
            .scry("graph-store", &path, "json")?;

        // If successfully acquired graph json
        if res.status().as_u16() == 200 {
            if let Ok(body) = res.text() {
                if let Ok(graph_json) = json::parse(&body) {
                    return Graph::from_json(graph_json);
                }
            }
        }
        // Else return error
        Err(UrbitAPIError::FailedToGetGraph(resource_name.to_string()))
    }

    /// Acquire a subset of a graph from Graph Store by specifying the start and end indices
    /// of the subset of the graph.
    pub fn get_graph_subset(
        &mut self,
        resource_ship: &str,
        resource_name: &str,
        start_index: &str,
        end_index: &str,
    ) -> Result<Graph> {
        let path = format!(
            "/graph-subset/{}/{}/{}/{}",
            resource_ship, resource_name, end_index, start_index
        );
        let res = self
            .channel
            .ship_interface
            .scry("graph-store", &path, "json")?;

        // If successfully acquired graph json
        if res.status().as_u16() == 200 {
            if let Ok(body) = res.text() {
                if let Ok(graph_json) = json::parse(&body) {
                    return Graph::from_json(graph_json);
                }
            }
        }
        // Else return error
        Err(UrbitAPIError::FailedToGetGraph(resource_name.to_string()))
    }

    /// Remove graph from Graph Store
    pub fn remove_graph(&mut self, resource_ship: &str, resource_name: &str) -> Result<()> {
        let prepped_json = object! {
            "remove-graph": {
                "resource": {
                    "ship": resource_ship,
                    "name": resource_name
                }
            }
        };

        let resp = (&mut self.channel).poke("graph-push-hook", "graph-update", &prepped_json)?;

        if resp.status().as_u16() == 204 {
            Ok(())
        } else {
            return Err(UrbitAPIError::FailedToRemoveGraphFromGraphStore(
                resource_name.to_string(),
            ));
        }
    }

    /// Archive a graph in Graph Store
    pub fn archive_graph(&mut self, resource_ship: &str, resource_name: &str) -> Result<String> {
        let path = format!("/archive/{}/{}", resource_ship, resource_name);
        let res = self
            .channel
            .ship_interface
            .scry("graph-store", &path, "json")?;

        if res.status().as_u16() == 200 {
            if let Ok(body) = res.text() {
                return Ok(body);
            }
        }
        return Err(UrbitAPIError::FailedToArchiveGraph(
            resource_name.to_string(),
        ));
    }

    /// Unarchive a graph in Graph Store
    pub fn unarchive_graph(&mut self, resource_ship: &str, resource_name: &str) -> Result<String> {
        let path = format!("/unarchive/{}/{}", resource_ship, resource_name);
        let res = self
            .channel
            .ship_interface
            .scry("graph-store", &path, "json")?;

        if res.status().as_u16() == 200 {
            if let Ok(body) = res.text() {
                return Ok(body);
            }
        }
        return Err(UrbitAPIError::FailedToArchiveGraph(
            resource_name.to_string(),
        ));
    }

    /// Add a tag to a graph
    pub fn add_tag(&mut self, resource_ship: &str, resource_name: &str, tag: &str) -> Result<()> {
        let prepped_json = object! {
            "add-tag": {
                "resource": {
                    "ship": resource_ship,
                    "name": resource_name
                },
                "term":  tag
                }
        };

        let resp = (&mut self.channel).poke("graph-push-hook", "graph-update", &prepped_json)?;

        if resp.status().as_u16() == 204 {
            Ok(())
        } else {
            return Err(UrbitAPIError::FailedToAddTag(resource_name.to_string()));
        }
    }

    /// Remove a tag from a graph
    pub fn remove_tag(
        &mut self,
        resource_ship: &str,
        resource_name: &str,
        tag: &str,
    ) -> Result<()> {
        let prepped_json = object! {
            "remove-tag": {
                "resource": {
                    "ship": resource_ship,
                    "name": resource_name
                },
                "term":  tag
                }
        };

        let resp = (&mut self.channel).poke("graph-push-hook", "graph-update", &prepped_json)?;

        if resp.status().as_u16() == 204 {
            Ok(())
        } else {
            return Err(UrbitAPIError::FailedToRemoveTag(resource_name.to_string()));
        }
    }

    /// Performs a scry to get all keys
    pub fn get_keys(&mut self) -> Result<Vec<JsonValue>> {
        let resp = self
            .channel
            .ship_interface
            .scry("graph-store", "/keys", "json")?;

        if resp.status().as_u16() == 200 {
            let json_text = resp.text()?;
            if let Ok(json) = json::parse(&json_text) {
                let keys = json["graph-update"]["keys"].clone();
                let mut keys_list = vec![];
                for key in keys.members() {
                    keys_list.push(key.clone())
                }
                return Ok(keys_list);
            }
        }
        return Err(UrbitAPIError::FailedToFetchKeys);
    }

    /// Performs a scry to get all tags
    pub fn get_tags(&mut self) -> Result<Vec<JsonValue>> {
        let resp = self
            .channel
            .ship_interface
            .scry("graph-store", "/tags", "json")?;

        if resp.status().as_u16() == 200 {
            let json_text = resp.text()?;
            if let Ok(json) = json::parse(&json_text) {
                let tags = json["graph-update"]["tags"].clone();
                let mut tags_list = vec![];
                for tag in tags.members() {
                    tags_list.push(tag.clone())
                }
                return Ok(tags_list);
            }
        }
        return Err(UrbitAPIError::FailedToFetchTags);
    }

    /// Performs a scry to get all tags
    pub fn get_tag_queries(&mut self) -> Result<Vec<JsonValue>> {
        let resp = self
            .channel
            .ship_interface
            .scry("graph-store", "/tag-queries", "json")?;

        if resp.status().as_u16() == 200 {
            let json_text = resp.text()?;
            if let Ok(json) = json::parse(&json_text) {
                let tags = json["graph-update"]["tag-queries"].clone();
                let mut tags_list = vec![];
                for tag in tags.members() {
                    tags_list.push(tag.clone())
                }
                return Ok(tags_list);
            }
        }
        return Err(UrbitAPIError::FailedToFetchTags);
    }

    /// Acquire the time the update log of a given resource was last updated
    pub fn peek_update_log(&mut self, resource_ship: &str, resource_name: &str) -> Result<String> {
        let path = format!("/peek-update-log/{}/{}", resource_ship, resource_name);
        let res = self
            .channel
            .ship_interface
            .scry("graph-store", &path, "json")?;

        // If successfully acquired node json
        if res.status().as_u16() == 200 {
            if let Ok(body) = res.text() {
                return Ok(body);
            }
        }
        // Else return error
        Err(UrbitAPIError::FailedToGetGraph(resource_name.to_string()))
    }

    /// Acquire the update log for a given resource
    pub fn get_update_log(&mut self, resource_ship: &str, resource_name: &str) -> Result<String> {
        let path = format!("/update-log/{}/{}", resource_ship, resource_name);
        let res = self
            .channel
            .ship_interface
            .scry("graph-store", &path, "json")?;

        // println!("body: {}", res.text().unwrap());

        // If successfully acquired node json
        if res.status().as_u16() == 200 {
            if let Ok(body) = res.text() {
                return Ok(body);
            }
        }
        // Else return error
        Err(UrbitAPIError::FailedToGetGraph(resource_name.to_string()))
    }

    /// Acquire a subset of the update log for a given resource
    pub fn get_update_log_subset(
        &mut self,
        resource_ship: &str,
        resource_name: &str,
        start_index: &str,
        end_index: &str,
    ) -> Result<String> {
        let path = format!(
            "/update-log-subset/{}/{}/{}/{}",
            resource_ship, resource_name, end_index, start_index
        );
        let res = self
            .channel
            .ship_interface
            .scry("graph-store", &path, "json")?;

        // If successfully acquired node json
        if res.status().as_u16() == 200 {
            if let Ok(body) = res.text() {
                return Ok(body);
            }
        }
        // Else return error
        Err(UrbitAPIError::FailedToGetUpdateLog(
            resource_name.to_string(),
        ))
    }
}