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
use crate::error::{Result, UrbitAPIError};
use chrono::prelude::*;
use json::{object, JsonValue};
use regex::Regex;

/// Struct which represents a graph in Graph Store
/// as a list of Nodes. Simplistic implementation
/// may be updated in the future if performance becomes
/// inadequate in real world use cases.
#[derive(Clone, Debug)]
pub struct Graph {
    pub nodes: Vec<Node>,
}

/// Struct which represents a node in a graph in Graph Store
#[derive(Clone, Debug)]
pub struct Node {
    pub index: String,
    pub author: String,
    pub time_sent: u64,
    pub signatures: Vec<String>,
    pub contents: NodeContents,
    pub hash: Option<String>,
}

/// Struct which represents the contents inside of a node
#[derive(Debug, Clone)]
pub struct NodeContents {
    pub content_list: Vec<JsonValue>,
}

impl Graph {
    /// Create a new `Graph`
    pub fn new(nodes: Vec<Node>) -> Graph {
        Graph { nodes: nodes }
    }

    /// Insert a `Node` into the `Graph`.
    /// Reads the index of the node and embeds it within
    /// the correct parent node if it is a child.
    pub fn insert(&mut self, node: Node) {
        self.nodes.push(node);
    }

    /// Attempts to find the parent of a given node within `self`
    /// with a naive linear search.
    pub fn find_node_parent(&self, child: &Node) -> Option<&Node> {
        self.nodes.iter().find(|n| n.is_direct_parent(&child))
    }

    /// Convert from graph `JsonValue` to `Graph`
    pub fn from_json(graph_json: JsonValue) -> Result<Graph> {
        // Create a new empty graph to insert nodes into
        let mut graph = Graph::new(vec![]);
        // Create a list of nodes all stripped of child associations
        let mut childless_nodes = vec![];
        // Get the graph inner json
        let graph_text = format!("{}", graph_json["graph-update"]["add-graph"]["graph"]);

        // Create regex to capture each node json
        let re = Regex::new(r#""\d+":(.+?children":).+?"#)
            .map_err(|_| UrbitAPIError::FailedToCreateGraphFromJSON)?;
        // For each capture group, create a childless node
        for capture in re.captures_iter(&graph_text) {
            // Get the node json string without it's children
            let node_string = capture
                .get(1)
                .ok_or(UrbitAPIError::FailedToCreateGraphFromJSON)?
                .as_str()
                .to_string()
                + r#"null}"#;
            let json = json::parse(&node_string)
                .map_err(|_| UrbitAPIError::FailedToCreateGraphNodeFromJSON)?;
            let processed_node = Node::from_json(&json)?;
            childless_nodes.push(processed_node);
        }

        // Insert all of the childless nodes into the graph.
        // Places them under the correct parent as required.
        for cn in childless_nodes {
            graph.insert(cn);
        }

        Ok(graph)
    }

    // Converts to `JsonValue`
    pub fn to_json(&self) -> JsonValue {
        let nodes_json: Vec<JsonValue> = self.nodes.iter().map(|n| n.to_json(None)).collect();
        object! {
                            "graph-update": {
                                "add-graph": {
                                    "graph": nodes_json,
        }
                }
                        }
    }
}

impl Node {
    // Create a new `Node`
    pub fn new(
        index: String,
        author: String,
        time_sent: u64,
        signatures: Vec<String>,
        contents: NodeContents,
        hash: Option<String>,
    ) -> Node {
        Node {
            index: index,
            author: author,
            time_sent: time_sent,
            signatures: signatures,
            contents: contents,
            hash: hash,
        }
    }

    /// Extract the `Node`'s parent's index (if parent exists)
    pub fn parent_index(&self) -> Option<String> {
        let rev_index = self.index.chars().rev().collect::<String>();
        let split_index: Vec<&str> = rev_index.splitn(2, "/").collect();
        // Error check
        if split_index.len() < 2 {
            return None;
        }

        let parent_index = split_index[1].chars().rev().collect::<String>();

        Some(parent_index)
    }

    /// Check if a self is the direct parent of another `Node`.
    pub fn is_direct_parent(&self, potential_child: &Node) -> bool {
        if let Some(index) = potential_child.parent_index() {
            return self.index == index;
        }
        false
    }

    /// Check if self is a parent (direct or indirect) of another `Node`
    pub fn is_parent(&self, potential_child: &Node) -> bool {
        let pc_split_index: Vec<&str> = potential_child.index.split("/").collect();
        let parent_split_index: Vec<&str> = self.index.split("/").collect();

        // Verify the parent has a smaller split index than child
        if parent_split_index.len() > pc_split_index.len() {
            return false;
        }

        // Check if every index split part of the parent is part of
        // the child
        let mut matching = false;
        for n in 0..parent_split_index.len() - 1 {
            matching = parent_split_index[n] == pc_split_index[n]
        }

        // Return if parent index is fully part of the child index
        matching
    }

    /// Converts the `Node` into a human readable formatted string which
    /// includes the author, date, and node contents.
    pub fn to_formatted_string(&self) -> String {
        let unix_time = self.time_sent as i64 / 1000;
        let date_time: DateTime<Utc> =
            DateTime::from_utc(NaiveDateTime::from_timestamp(unix_time, 0), Utc);
        let new_date = date_time.format("%Y-%m-%d %H:%M:%S");

        let content = self.contents.to_formatted_string();
        format!("{} - ~{}:{}", new_date, self.author, content)
    }

    /// Converts to `JsonValue`
    pub fn to_json(&self, children: Option<JsonValue>) -> JsonValue {
        let mut node_json = object!();

        let final_children = match children {
            Some(json) => json,
            None => JsonValue::Null,
        };

        node_json[self.index.clone()] = object! {
                        "post": {
                            "author": self.author.clone(),
                            "index": self.index.clone(),
                            "time-sent": self.time_sent,
                            "contents": self.contents.to_json(),
                            "hash": null,
                            "signatures": []
                        },
                        "children": final_children
        };
        node_json
    }

    /// Convert from node `JsonValue` which is wrapped up in a few wrapper fields
    /// into a `Node`.
    /// Defaults to no children.
    pub fn from_graph_update_json(wrapped_json: &JsonValue) -> Result<Node> {
        let dumped = wrapped_json["graph-update"]["add-nodes"]["nodes"].dump();
        let split: Vec<&str> = dumped.splitn(2, ":").collect();
        if split.len() <= 1 {
            return Err(UrbitAPIError::FailedToCreateGraphNodeFromJSON);
        }

        let mut inner_string = split[1].to_string();
        inner_string.remove(inner_string.len() - 1);

        let inner_json = json::parse(&inner_string)
            .map_err(|_| UrbitAPIError::FailedToCreateGraphNodeFromJSON)?;

        Self::from_json(&inner_json)
    }

    /// Convert from straight node `JsonValue` to `Node`
    /// Defaults to no children.
    pub fn from_json(json: &JsonValue) -> Result<Node> {
        // Process all of the json fields
        let _children = json["children"].clone();
        let post_json = json["post"].clone();
        let index = post_json["index"]
            .as_str()
            .ok_or(UrbitAPIError::FailedToCreateGraphNodeFromJSON)?;
        let author = post_json["author"]
            .as_str()
            .ok_or(UrbitAPIError::FailedToCreateGraphNodeFromJSON)?;
        let time_sent = post_json["time-sent"]
            .as_u64()
            .ok_or(UrbitAPIError::FailedToCreateGraphNodeFromJSON)?;

        // Wrap hash in an Option for null case
        let hash = match post_json["hash"].is_null() {
            true => None,
            false => Some(
                post_json["hash"]
                    .as_str()
                    .ok_or(UrbitAPIError::FailedToCreateGraphNodeFromJSON)?
                    .to_string(),
            ),
        };

        // Convert array JsonValue to vector for contents
        let mut json_contents = vec![];
        for content in post_json["contents"].members() {
            json_contents.push(content.clone());
        }
        let contents = NodeContents::from_json(json_contents);

        // Convert array JsonValue to vector for signatures
        let mut signatures = vec![];
        for signature in post_json["signatures"].members() {
            signatures.push(
                signature
                    .as_str()
                    .ok_or(UrbitAPIError::FailedToCreateGraphNodeFromJSON)?
                    .to_string(),
            );
        }

        Ok(Node {
            index: index.to_string(),
            author: author.to_string(),
            time_sent: time_sent,
            signatures: signatures,
            contents: contents,
            hash: hash,
        })
    }
}

/// Methods for `NodeContents`
impl NodeContents {
    /// Create a new empty `NodeContents`
    pub fn new() -> NodeContents {
        NodeContents {
            content_list: vec![],
        }
    }

    pub fn is_empty(&self) -> bool {
        self.content_list.len() == 0
    }

    /// Appends text to the end of the list of contents
    pub fn add_text(&self, text: &str) -> NodeContents {
        let formatted = object! {
            "text": text
        };
        self.add_to_contents(formatted)
    }

    /// Appends a url to the end of the list of contents
    pub fn add_url(&self, url: &str) -> NodeContents {
        let formatted = object! {
            "url": url
        };
        self.add_to_contents(formatted)
    }

    /// Appends a mention to another @p/ship to the end of the list of contents
    pub fn add_mention(&self, referenced_ship: &str) -> NodeContents {
        let formatted = object! {
            "mention": referenced_ship
        };
        self.add_to_contents(formatted)
    }

    /// Appends a code block to the end of the list of contents
    pub fn add_code(&self, expression: &str, output: &str) -> NodeContents {
        let formatted = object! {
            "code": {
                "expression": expression,
                "output": [[output]]
            }
        };
        self.add_to_contents(formatted)
    }

    /// Create a `NodeContents` from a list of `JsonValue`s
    pub fn from_json(json_contents: Vec<JsonValue>) -> NodeContents {
        NodeContents {
            content_list: json_contents,
        }
    }

    /// Convert the `NodeContents` into a json array in a `JsonValue`
    pub fn to_json(&self) -> JsonValue {
        self.content_list.clone().into()
    }

    /// Convert the `NodeContents` into a single `String` that is formatted
    /// for human reading.
    pub fn to_formatted_string(&self) -> String {
        let mut result = "".to_string();
        for item in &self.content_list {
            // Convert item into text
            let text = Self::extract_content_text(item);
            result = result + " " + text.trim();
        }
        result
    }

    // Extracts content from a content list item `JsonValue`
    fn extract_content_text(json: &JsonValue) -> String {
        let mut result = "  ".to_string();
        if !json["text"].is_empty() {
            result = json["text"].dump();
        } else if !json["url"].is_empty() {
            result = json["url"].dump();
        } else if !json["mention"].is_empty() {
            result = json["mention"].dump();
            result.remove(0);
            result.remove(result.len() - 1);
            return format!("~{}", result);
        } else if !json["code"].is_empty() {
            result = json["code"].dump();
        }
        result.remove(0);
        result.remove(result.len() - 1);
        result
    }

    /// Internal method to append `JsonValue` to the end of the list of contents
    fn add_to_contents(&self, json: JsonValue) -> NodeContents {
        let mut contents = self.content_list.clone();
        contents.append(&mut vec![json]);
        NodeContents {
            content_list: contents,
        }
    }
}