Skip to main content

fauna_api/ant/
graph.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4use crate::drive::{DriveAuthorization, File};
5use crate::termite::versioning::FileOrFiles;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
8#[serde(rename_all = "lowercase")]
9pub enum Stimuli {
10    Start,
11    File,
12    Text,
13    Website,
14    X,
15    Linkedin,
16}
17
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
19#[serde(rename_all = "camelCase")]
20pub struct GraphNodeWire {
21    pub id: String,
22    pub kind: Stimuli,
23    pub x: f64,
24    pub y: f64,
25    #[serde(default)]
26    pub label: String,
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub w: Option<f64>,
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub h: Option<f64>,
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub text: Option<String>,
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub url: Option<String>,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub mime: Option<String>,
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub file_path: Option<String>,
39}
40
41fn wire(
42    id: &str,
43    kind: Stimuli,
44    x: f64,
45    y: f64,
46    label: String,
47    w: Option<f64>,
48    h: Option<f64>,
49) -> GraphNodeWire {
50    GraphNodeWire {
51        id: id.to_string(),
52        kind,
53        x,
54        y,
55        label,
56        w,
57        h,
58        text: None,
59        url: None,
60        mime: None,
61        file_path: None,
62    }
63}
64
65/// `{ path, mime, name }` in the TypeScript SDK: a post's extra media by Drive path.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub struct ExtraPath {
68    pub path: String,
69    pub mime: String,
70    pub name: String,
71}
72
73#[derive(Default, Deserialize)]
74#[serde(rename_all = "camelCase")]
75struct XEnvelope {
76    body: Option<String>,
77    #[serde(default, deserialize_with = "present")]
78    quoted_id: Option<Option<String>>,
79    extra: Option<Vec<ExtraPath>>,
80}
81
82fn present<'de, D: serde::Deserializer<'de>>(
83    deserializer: D,
84) -> std::result::Result<Option<Option<String>>, D::Error> {
85    Ok(Some(Option::<String>::deserialize(deserializer)?))
86}
87
88#[derive(Serialize)]
89#[serde(rename_all = "camelCase")]
90struct XEnvelopeOut<'a> {
91    body: &'a str,
92    quoted_id: Option<&'a str>,
93    #[serde(skip_serializing_if = "Vec::is_empty")]
94    extra: Vec<ExtraPath>,
95}
96
97fn parse_x_envelope(text: Option<&str>) -> XEnvelope {
98    let raw = text.unwrap_or_default().trim();
99    if raw.is_empty() {
100        return XEnvelope::default();
101    }
102    if raw.starts_with('{')
103        && let Ok(Value::Object(fields)) = serde_json::from_str::<Value>(raw)
104        && let Ok(envelope) = serde_json::from_value(Value::Object(fields))
105    {
106        return envelope;
107    }
108    XEnvelope {
109        body: Some(raw.to_string()),
110        ..XEnvelope::default()
111    }
112}
113
114fn file_path_of(file: Option<&File>, fallback: Option<&String>) -> Option<String> {
115    match file.map(|file| &file.authorization) {
116        Some(DriveAuthorization::Path { path, .. })
117        | Some(DriveAuthorization::Repository { path, .. }) => Some(path.clone()),
118        _ => fallback.cloned(),
119    }
120}
121
122fn file_list(files: Option<FileOrFiles>) -> Vec<File> {
123    match files {
124        None => Vec::new(),
125        Some(FileOrFiles::File(file)) => vec![file],
126        Some(FileOrFiles::Files(files)) => files,
127    }
128}
129
130#[derive(Debug, Clone)]
131#[allow(clippy::large_enum_variant)]
132pub enum GraphNode {
133    Start(StartNode),
134    Text(TextNode),
135    Website(WebsiteNode),
136    File(FileNode),
137    X(XNode),
138    LinkedIn(LinkedInNode),
139}
140
141impl GraphNode {
142    pub fn kind(&self) -> Stimuli {
143        match self {
144            GraphNode::Start(_) => Stimuli::Start,
145            GraphNode::Text(_) => Stimuli::Text,
146            GraphNode::Website(_) => Stimuli::Website,
147            GraphNode::File(_) => Stimuli::File,
148            GraphNode::X(_) => Stimuli::X,
149            GraphNode::LinkedIn(_) => Stimuli::Linkedin,
150        }
151    }
152
153    pub fn id(&self) -> &str {
154        match self {
155            GraphNode::Start(node) => &node.id,
156            GraphNode::Text(node) => &node.id,
157            GraphNode::Website(node) => &node.id,
158            GraphNode::File(node) => &node.id,
159            GraphNode::X(node) => &node.id,
160            GraphNode::LinkedIn(node) => &node.id,
161        }
162    }
163
164    #[allow(clippy::should_implement_trait)]
165    pub fn clone(&self) -> GraphNode {
166        Clone::clone(self)
167    }
168
169    pub fn to_json(&self) -> GraphNodeWire {
170        match self {
171            GraphNode::Start(node) => node.to_json(),
172            GraphNode::Text(node) => node.to_json(),
173            GraphNode::Website(node) => node.to_json(),
174            GraphNode::File(node) => node.to_json(),
175            GraphNode::X(node) => node.to_json(),
176            GraphNode::LinkedIn(node) => node.to_json(),
177        }
178    }
179
180    pub fn from_json(json: &GraphNodeWire, files: Option<FileOrFiles>) -> GraphNode {
181        match json.kind {
182            Stimuli::Start => {
183                GraphNode::Start(StartNode::new(&json.id, json.x, json.y, json.w, json.h))
184            }
185            Stimuli::Text => GraphNode::Text(TextNode::new(
186                &json.id,
187                json.x,
188                json.y,
189                &json.label,
190                json.text.as_deref().unwrap_or_default(),
191                json.w,
192                json.h,
193            )),
194            Stimuli::Website => GraphNode::Website(WebsiteNode::new(
195                &json.id,
196                json.x,
197                json.y,
198                json.url.as_deref().unwrap_or_default(),
199                json.w,
200                json.h,
201            )),
202            Stimuli::File => {
203                let mut node = FileNode::new(
204                    &json.id,
205                    json.x,
206                    json.y,
207                    file_list(files).into_iter().next(),
208                );
209                node.w = json.w;
210                node.h = json.h;
211                node.wire_path = json.file_path.clone();
212                node.wire_mime = json.mime.clone();
213                node.wire_name = Some(json.label.clone());
214                GraphNode::File(node)
215            }
216            Stimuli::X => GraphNode::X(XNode::from_json(json, files)),
217            Stimuli::Linkedin => GraphNode::LinkedIn(LinkedInNode::from_json(json, files)),
218        }
219    }
220}
221
222#[derive(Debug, Clone, PartialEq)]
223pub struct StartNode {
224    pub id: String,
225    pub x: f64,
226    pub y: f64,
227    pub w: Option<f64>,
228    pub h: Option<f64>,
229}
230
231impl StartNode {
232    pub fn new(id: &str, x: f64, y: f64, w: Option<f64>, h: Option<f64>) -> StartNode {
233        StartNode {
234            id: id.to_string(),
235            x,
236            y,
237            w,
238            h,
239        }
240    }
241
242    #[allow(clippy::should_implement_trait)]
243    pub fn clone(&self) -> StartNode {
244        Clone::clone(self)
245    }
246
247    pub fn to_json(&self) -> GraphNodeWire {
248        wire(
249            &self.id,
250            Stimuli::Start,
251            self.x,
252            self.y,
253            "Start".to_string(),
254            self.w,
255            self.h,
256        )
257    }
258}
259
260#[derive(Debug, Clone, PartialEq)]
261pub struct TextNode {
262    pub id: String,
263    pub x: f64,
264    pub y: f64,
265    pub w: Option<f64>,
266    pub h: Option<f64>,
267    pub label: String,
268    pub text: String,
269}
270
271impl TextNode {
272    pub fn new(
273        id: &str,
274        x: f64,
275        y: f64,
276        label: &str,
277        text: &str,
278        w: Option<f64>,
279        h: Option<f64>,
280    ) -> TextNode {
281        TextNode {
282            id: id.to_string(),
283            x,
284            y,
285            w,
286            h,
287            label: label.to_string(),
288            text: text.to_string(),
289        }
290    }
291
292    #[allow(clippy::should_implement_trait)]
293    pub fn clone(&self) -> TextNode {
294        Clone::clone(self)
295    }
296
297    pub fn to_json(&self) -> GraphNodeWire {
298        GraphNodeWire {
299            text: Some(self.text.clone()),
300            ..wire(
301                &self.id,
302                Stimuli::Text,
303                self.x,
304                self.y,
305                self.label.clone(),
306                self.w,
307                self.h,
308            )
309        }
310    }
311}
312
313#[derive(Debug, Clone, PartialEq)]
314pub struct WebsiteNode {
315    pub id: String,
316    pub x: f64,
317    pub y: f64,
318    pub w: Option<f64>,
319    pub h: Option<f64>,
320    pub url: String,
321}
322
323impl WebsiteNode {
324    pub fn new(id: &str, x: f64, y: f64, url: &str, w: Option<f64>, h: Option<f64>) -> WebsiteNode {
325        WebsiteNode {
326            id: id.to_string(),
327            x,
328            y,
329            w,
330            h,
331            url: url.to_string(),
332        }
333    }
334
335    #[allow(clippy::should_implement_trait)]
336    pub fn clone(&self) -> WebsiteNode {
337        Clone::clone(self)
338    }
339
340    pub fn to_json(&self) -> GraphNodeWire {
341        let label = if self.url.is_empty() {
342            "Website".to_string()
343        } else {
344            self.url.clone()
345        };
346        GraphNodeWire {
347            url: Some(self.url.clone()),
348            ..wire(
349                &self.id,
350                Stimuli::Website,
351                self.x,
352                self.y,
353                label,
354                self.w,
355                self.h,
356            )
357        }
358    }
359}
360
361#[derive(Debug, Clone)]
362pub struct FileNode {
363    pub id: String,
364    pub x: f64,
365    pub y: f64,
366    pub w: Option<f64>,
367    pub h: Option<f64>,
368    pub file: Option<File>,
369    pub wire_path: Option<String>,
370    pub wire_mime: Option<String>,
371    pub wire_name: Option<String>,
372}
373
374impl FileNode {
375    pub fn new(id: &str, x: f64, y: f64, file: Option<File>) -> FileNode {
376        FileNode {
377            id: id.to_string(),
378            x,
379            y,
380            w: None,
381            h: None,
382            file,
383            wire_path: None,
384            wire_mime: None,
385            wire_name: None,
386        }
387    }
388
389    #[allow(clippy::should_implement_trait)]
390    pub fn clone(&self) -> FileNode {
391        Clone::clone(self)
392    }
393
394    pub fn to_json(&self) -> GraphNodeWire {
395        let label = self
396            .file
397            .as_ref()
398            .map(|file| file.name().to_string())
399            .or_else(|| self.wire_name.clone())
400            .unwrap_or_else(|| "File".to_string());
401        GraphNodeWire {
402            mime: self
403                .file
404                .as_ref()
405                .map(|file| file.content_type.clone())
406                .or_else(|| self.wire_mime.clone()),
407            file_path: file_path_of(self.file.as_ref(), self.wire_path.as_ref()),
408            ..wire(
409                &self.id,
410                Stimuli::File,
411                self.x,
412                self.y,
413                label,
414                self.w,
415                self.h,
416            )
417        }
418    }
419}
420
421#[derive(Debug, Clone)]
422pub struct XNode {
423    pub id: String,
424    pub x: f64,
425    pub y: f64,
426    pub w: Option<f64>,
427    pub h: Option<f64>,
428    pub handle: String,
429    pub body: String,
430    pub media: Vec<File>,
431    pub quoted_id: Option<String>,
432    pub extra_paths: Vec<ExtraPath>,
433    pub wire_path: Option<String>,
434    pub wire_mime: Option<String>,
435}
436
437impl XNode {
438    pub fn new(id: &str, x: f64, y: f64, handle: &str, body: &str) -> XNode {
439        XNode {
440            id: id.to_string(),
441            x,
442            y,
443            w: None,
444            h: None,
445            handle: handle.to_string(),
446            body: body.to_string(),
447            media: Vec::new(),
448            quoted_id: None,
449            extra_paths: Vec::new(),
450            wire_path: None,
451            wire_mime: None,
452        }
453    }
454
455    pub fn is_post(&self) -> bool {
456        self.quoted_id.is_none()
457    }
458
459    pub fn is_repost(&self) -> bool {
460        self.quoted_id.is_some() && self.body.trim().is_empty()
461    }
462
463    pub fn is_quote(&self) -> bool {
464        self.quoted_id.is_some() && !self.body.trim().is_empty()
465    }
466
467    #[allow(clippy::should_implement_trait)]
468    pub fn clone(&self) -> XNode {
469        Clone::clone(self)
470    }
471
472    pub fn to_json(&self) -> GraphNodeWire {
473        let first = self.media.first();
474        let mut extra: Vec<ExtraPath> = self
475            .media
476            .iter()
477            .skip(1)
478            .map(|file| ExtraPath {
479                path: file_path_of(Some(file), None).unwrap_or_default(),
480                mime: file.content_type.clone(),
481                name: file.name().to_string(),
482            })
483            .filter(|row| !row.path.is_empty())
484            .collect();
485        extra.extend(self.extra_paths.iter().cloned());
486        let text = serde_json::to_string(&XEnvelopeOut {
487            body: &self.body,
488            quoted_id: self.quoted_id.as_deref(),
489            extra,
490        })
491        .unwrap_or_default();
492        GraphNodeWire {
493            text: Some(text),
494            mime: first
495                .map(|file| file.content_type.clone())
496                .or_else(|| self.wire_mime.clone()),
497            file_path: file_path_of(first, self.wire_path.as_ref()),
498            ..wire(
499                &self.id,
500                Stimuli::X,
501                self.x,
502                self.y,
503                self.handle.clone(),
504                self.w,
505                self.h,
506            )
507        }
508    }
509
510    pub fn from_json(json: &GraphNodeWire, files: Option<FileOrFiles>) -> XNode {
511        let envelope = parse_x_envelope(json.text.as_deref());
512        let handle = if json.label.is_empty() {
513            json.url.clone().unwrap_or_default()
514        } else {
515            json.label.clone()
516        };
517        XNode {
518            w: json.w,
519            h: json.h,
520            media: file_list(files),
521            quoted_id: envelope.quoted_id.flatten(),
522            extra_paths: envelope.extra.unwrap_or_default(),
523            wire_path: json.file_path.clone(),
524            wire_mime: json.mime.clone(),
525            ..XNode::new(
526                &json.id,
527                json.x,
528                json.y,
529                &handle,
530                &envelope.body.unwrap_or_default(),
531            )
532        }
533    }
534}
535
536#[derive(Debug, Clone)]
537pub struct LinkedInNode {
538    pub id: String,
539    pub x: f64,
540    pub y: f64,
541    pub w: Option<f64>,
542    pub h: Option<f64>,
543    pub author: String,
544    pub body: String,
545    pub media: Vec<File>,
546    pub wire_path: Option<String>,
547    pub wire_mime: Option<String>,
548}
549
550impl LinkedInNode {
551    pub fn new(id: &str, x: f64, y: f64, author: &str, body: &str) -> LinkedInNode {
552        LinkedInNode {
553            id: id.to_string(),
554            x,
555            y,
556            w: None,
557            h: None,
558            author: author.to_string(),
559            body: body.to_string(),
560            media: Vec::new(),
561            wire_path: None,
562            wire_mime: None,
563        }
564    }
565
566    #[allow(clippy::should_implement_trait)]
567    pub fn clone(&self) -> LinkedInNode {
568        Clone::clone(self)
569    }
570
571    pub fn to_json(&self) -> GraphNodeWire {
572        let first = self.media.first();
573        GraphNodeWire {
574            text: Some(self.body.clone()),
575            mime: first
576                .map(|file| file.content_type.clone())
577                .or_else(|| self.wire_mime.clone()),
578            file_path: file_path_of(first, self.wire_path.as_ref()),
579            ..wire(
580                &self.id,
581                Stimuli::Linkedin,
582                self.x,
583                self.y,
584                self.author.clone(),
585                self.w,
586                self.h,
587            )
588        }
589    }
590
591    pub fn from_json(json: &GraphNodeWire, files: Option<FileOrFiles>) -> LinkedInNode {
592        LinkedInNode {
593            w: json.w,
594            h: json.h,
595            media: file_list(files),
596            wire_path: json.file_path.clone(),
597            wire_mime: json.mime.clone(),
598            ..LinkedInNode::new(
599                &json.id,
600                json.x,
601                json.y,
602                &json.label,
603                json.text.as_deref().unwrap_or_default(),
604            )
605        }
606    }
607}
608
609#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
610#[serde(rename_all = "camelCase")]
611pub struct GraphEdge {
612    pub id: String,
613    pub from_node_id: String,
614    pub to_node_id: String,
615}
616
617impl GraphEdge {
618    pub fn new(id: &str, from_node_id: &str, to_node_id: &str) -> GraphEdge {
619        GraphEdge {
620            id: id.to_string(),
621            from_node_id: from_node_id.to_string(),
622            to_node_id: to_node_id.to_string(),
623        }
624    }
625
626    #[allow(clippy::should_implement_trait)]
627    pub fn clone(&self) -> GraphEdge {
628        Clone::clone(self)
629    }
630
631    pub fn to_json(&self) -> Value {
632        serde_json::to_value(self).unwrap_or_default()
633    }
634
635    pub fn from_json(json: &Value) -> GraphEdge {
636        serde_json::from_value(json.clone()).unwrap_or_else(|_| GraphEdge::new("", "", ""))
637    }
638}