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
//! `GraphLoader` trait and provides some default implementations for loading a graph.
//! This base class is used to load in-built graphs such as the LOTR, reddit and StackOverflow.
//! It also provides a method to download a CSV file.
//!
//! # Example
//!
//! ```rust
//! use raphtory_io::graph_loader::fetch_file;
//!
//! let path = fetch_file(
//!     "lotr.csv",
//!     true,
//!     "https://raw.githubusercontent.com/Raphtory/Data/main/lotr.csv",
//!     600
//! );
//!
//! // check if a file exists at the path
//! assert!(path.is_ok());
//! ```
//!

use std::env;
use std::fs::File;
use std::io::{copy, Cursor};
use std::path::{Path, PathBuf};
use std::time::Duration;
use std::io::prelude::*;
use zip::read::{ZipArchive, ZipFile};
use std::fs::*;

pub mod example;
pub mod source;

pub fn fetch_file(
    name: &str,
    tmp_save:bool,
    url: &str,
    timeout: u64,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let filepath = if tmp_save {
        let tmp_dir = env::temp_dir();
        tmp_dir.join(name)
    }
    else {
        PathBuf::from(name)
    };
    if !filepath.exists() {
        let client = reqwest::blocking::Client::builder()
            .timeout(Duration::from_secs(timeout))
            .build()?;
        let response = client.get(url).send()?;
        let mut content = Cursor::new(response.bytes()?);
        if !filepath.exists() {
            let mut file = File::create(&filepath)?;
            copy(&mut content, &mut file)?;
        }
    }
    Ok(filepath)
}


fn unzip_file(zip_file_path: &str, destination_path: &str) -> std::io::Result<()> {
    let file = File::open(zip_file_path)?;
    let mut archive = ZipArchive::new(file)?;

    for i in 0..archive.len() {
        let mut file = archive.by_index(i)?;
        let file_path = file.name();
        let dest_path = format!("{}/{}", destination_path, file_path);

        if file.is_dir() {
            create_dir_all(&dest_path)?;
        } else {
            if let Some(parent) = Path::new(&dest_path).parent() {
                if !parent.exists() {
                   create_dir_all(&parent)?;
                }
            }
            let mut output_file = File::create(&dest_path)?;
            std::io::copy(&mut file, &mut output_file)?;
        }
    }

    Ok(())
}




#[cfg(test)]
mod graph_loader_test {
    use csv::StringRecord;
    use raphtory::{
        core::{utils, Prop},
        db::{
            graph::Graph,
            view_api::{GraphViewOps, TimeOps, VertexViewOps},
        },
    };

    use crate::graph_loader::{fetch_file, unzip_file};
    use crate::graph_loader::example::stable_coins::stable_coin_graph;


    #[test]
    fn test_fetch_file() {
        let path = fetch_file(
            "lotr2.csv",
            true,
            "https://raw.githubusercontent.com/Raphtory/Data/main/lotr_test.csv",
            600,
        );
        assert!(path.is_ok());
    }

    #[test]
    fn test_lotr_load_graph() {
        let g = crate::graph_loader::example::lotr_graph::lotr_graph(4);
        assert_eq!(g.num_edges(), 701);
    }

    #[test]
    fn test_graph_at() {
        let g = crate::graph_loader::example::lotr_graph::lotr_graph(1);

        let g_at_empty = g.at(1);
        let g_at_start = g.at(7059);
        let g_at_another = g.at(28373);
        let g_at_max = g.at(i64::MAX);
        let g_at_min = g.at(i64::MIN);

        assert_eq!(g_at_empty.num_vertices(), 0);
        assert_eq!(g_at_start.num_vertices(), 70);
        assert_eq!(g_at_another.num_vertices(), 123);
        assert_eq!(g_at_max.num_vertices(), 139);
        assert_eq!(g_at_min.num_vertices(), 0);
    }

    #[test]
    fn db_lotr() {
        let g = Graph::new(4);

        let data_dir = crate::graph_loader::example::lotr_graph::lotr_file()
            .expect("Failed to get lotr.csv file");

        fn parse_record(rec: &StringRecord) -> Option<(String, String, i64)> {
            let src = rec.get(0).and_then(|s| s.parse::<String>().ok())?;
            let dst = rec.get(1).and_then(|s| s.parse::<String>().ok())?;
            let t = rec.get(2).and_then(|s| s.parse::<i64>().ok())?;
            Some((src, dst, t))
        }

        if let Ok(mut reader) = csv::Reader::from_path(data_dir) {
            for rec in reader.records().flatten() {
                if let Some((src, dst, t)) = parse_record(&rec) {
                    let src_id = utils::calculate_hash(&src);
                    let dst_id = utils::calculate_hash(&dst);

                    g.add_vertex(
                        t,
                        src_id,
                        &vec![("name".to_string(), Prop::Str("Character".to_string()))],
                    )
                    .unwrap();
                    g.add_vertex(
                        t,
                        dst_id,
                        &vec![("name".to_string(), Prop::Str("Character".to_string()))],
                    )
                    .unwrap();
                    g.add_edge(
                        t,
                        src_id,
                        dst_id,
                        &vec![(
                            "name".to_string(),
                            Prop::Str("Character Co-occurrence".to_string()),
                        )],
                        None,
                    )
                    .unwrap();
                }
            }
        }

        let gandalf = utils::calculate_hash(&"Gandalf");
        assert!(g.has_vertex(gandalf));
        assert!(g.has_vertex("Gandalf"))
    }

    #[test]
    fn test_all_degrees_window() {
        let g = crate::graph_loader::example::lotr_graph::lotr_graph(4);

        assert_eq!(g.num_edges(), 701);
        assert_eq!(g.vertex("Gandalf").unwrap().degree(), 49);
        assert_eq!(
            g.vertex("Gandalf").unwrap().window(1356, 24792).degree(),
            34
        );
        assert_eq!(g.vertex("Gandalf").unwrap().in_degree(), 24);
        assert_eq!(
            g.vertex("Gandalf").unwrap().window(1356, 24792).in_degree(),
            16
        );
        assert_eq!(g.vertex("Gandalf").unwrap().out_degree(), 35);
        assert_eq!(
            g.vertex("Gandalf")
                .unwrap()
                .window(1356, 24792)
                .out_degree(),
            20
        );
    }

    #[test]
    fn test_all_neighbours_window() {
        let g = crate::graph_loader::example::lotr_graph::lotr_graph(4);

        assert_eq!(g.num_edges(), 701);
        assert_eq!(g.vertex("Gandalf").unwrap().neighbours().iter().count(), 49);

        for v in g
            .vertex("Gandalf")
            .unwrap()
            .window(1356, 24792)
            .neighbours()
            .iter()
        {
            println!("{:?}", v.id())
        }
        assert_eq!(
            g.vertex("Gandalf")
                .unwrap()
                .window(1356, 24792)
                .neighbours()
                .iter()
                .count(),
            34
        );
        assert_eq!(
            g.vertex("Gandalf").unwrap().in_neighbours().iter().count(),
            24
        );
        assert_eq!(
            g.vertex("Gandalf")
                .unwrap()
                .window(1356, 24792)
                .in_neighbours()
                .iter()
                .count(),
            16
        );
        assert_eq!(
            g.vertex("Gandalf").unwrap().out_neighbours().iter().count(),
            35
        );
        assert_eq!(
            g.vertex("Gandalf")
                .unwrap()
                .window(1356, 24792)
                .out_neighbours()
                .iter()
                .count(),
            20
        );
    }

    #[test]
    fn test_all_edges_window() {
        let g = crate::graph_loader::example::lotr_graph::lotr_graph(4);

        assert_eq!(g.num_edges(), 701);
        assert_eq!(g.vertex("Gandalf").unwrap().edges().count(), 59);
        assert_eq!(
            g.vertex("Gandalf")
                .unwrap()
                .window(1356, 24792)
                .edges()
                .count(),
            36
        );
        assert_eq!(g.vertex("Gandalf").unwrap().in_edges().count(), 24);
        assert_eq!(
            g.vertex("Gandalf")
                .unwrap()
                .window(1356, 24792)
                .in_edges()
                .count(),
            16
        );
        assert_eq!(g.vertex("Gandalf").unwrap().out_edges().count(), 35);
        assert_eq!(
            g.vertex("Gandalf")
                .unwrap()
                .window(1356, 24792)
                .out_edges()
                .count(),
            20
        );
    }
}