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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::collections::BTreeMap;
use std::error::Error;
use std::fs::{create_dir_all, remove_file, set_permissions, File, Permissions};
use std::io::{copy, BufRead, BufReader, Read, Write};
use std::process::Command;
use walkdir::WalkDir;

const MD5_BUF_READ_SIZE: usize = 4096;
const TMP_DOWNLOAD_NAME: &str = "tmp_download.zip";

#[tokio::main]
async fn main() {
    match std::env::args().skip(1).next() {
        Some(x) => match x.as_ref() {
            "--upload" => {
                upload();
            }
            "--dry" => {
                just_compare();
            }
            "--checklinks" => {
                check_links().await;
            }
            x => {
                println!("Unknown argument {}", x);
                std::process::exit(1);
            }
        },
        None => {
            download().await;
        }
    }
}

async fn download() {
    let cities = Cities::load_or_create();
    let local = Manifest::generate();
    let truth = Manifest::load("data/MANIFEST.txt".to_string())
        .unwrap()
        .filter(cities);

    // Anything local need deleting?
    for path in local.0.keys() {
        if !truth.0.contains_key(path) {
            rm(&path);
        }
    }

    // Anything missing or needing updating?
    let mut failed = Vec::new();
    for (path, entry) in truth.0 {
        if local.0.get(&path).map(|x| &x.checksum) != Some(&entry.checksum) {
            std::fs::create_dir_all(std::path::Path::new(&path).parent().unwrap()).unwrap();
            match curl(entry).await {
                Ok(()) => {
                    unzip(&path);
                }
                Err(err) => {
                    println!("{}, but continuing", err);
                    failed.push(format!("{} failed: {}", path, err));
                }
            };
            // Whether or not download failed, still try to clean up tmp file
            rm(TMP_DOWNLOAD_NAME);
        }
    }
    if !failed.is_empty() {
        // Fail the build.
        panic!("Failed to download stuff: {:?}", failed);
    }
}

fn just_compare() {
    let cities = Cities::load_or_create();
    let local = Manifest::generate();
    let truth = Manifest::load("data/MANIFEST.txt".to_string())
        .unwrap()
        .filter(cities);

    // Anything local need deleting?
    for path in local.0.keys() {
        if !truth.0.contains_key(path) {
            println!("- Remove {}", path);
        }
    }

    // Anything missing or needing updating?
    for (path, entry) in truth.0 {
        if local.0.get(&path).map(|x| &x.checksum) != Some(&entry.checksum) {
            println!("- Update {}", path);
        }
    }
}

fn upload() {
    let remote_base = "/home/dabreegster/Dropbox/abstreet_data";

    let mut local = Manifest::generate();
    let remote = Manifest::load(format!("{}/MANIFEST.txt", remote_base))
        .unwrap_or(Manifest(BTreeMap::new()));

    // Anything remote need deleting?
    for path in remote.0.keys() {
        if !local.0.contains_key(path) {
            rm(&format!("{}/{}.zip", remote_base, path));
        }
    }

    // Anything missing or needing updating?
    for (path, entry) in &mut local.0 {
        let remote_path = format!("{}/{}.zip", remote_base, path);
        let changed = remote.0.get(path).map(|x| &x.checksum) != Some(&entry.checksum);
        if changed {
            std::fs::create_dir_all(std::path::Path::new(&remote_path).parent().unwrap()).unwrap();
            run(Command::new("zip").arg(&remote_path).arg(&path));
            // Wait for the Dropbox client to sync
            loop {
                std::thread::sleep(std::time::Duration::from_millis(1000));
                println!("Waiting for {} to sync", remote_path);
                if run(Command::new("dropbox").arg("filestatus").arg(&remote_path))
                    .contains("up to date")
                {
                    break;
                }
            }
        }
        entry.dropbox_url = remote.0.get(path).map(|x| x.dropbox_url.clone().unwrap());
        // The sharelink sometimes changes when the file does.
        if entry.dropbox_url.is_none() || changed {
            // Dropbox crashes when trying to upload lots of tiny screenshots. :D
            std::thread::sleep(std::time::Duration::from_millis(1000));
            let url = run(Command::new("dropbox").arg("sharelink").arg(remote_path))
                .trim()
                .to_string();
            if !url.contains("dropbox.com") {
                panic!("dropbox daemon is sad, slow down");
            }
            entry.dropbox_url = Some(url);
        }
    }

    local.write(format!("{}/MANIFEST.txt", remote_base));
    local.write("data/MANIFEST.txt".to_string());
}

async fn check_links() {
    let client = reqwest::Client::new();

    for (file, entry) in Manifest::load("data/MANIFEST.txt".to_string()).unwrap().0 {
        // TODO Fiddle with this as needed
        if file.contains("input") {
            continue;
        }
        println!("> Check remote for {}", file);
        let url = entry.dropbox_url.unwrap();
        let url = format!("{}{}", &url[..url.len() - 1], "1");
        if let Err(err) = client
            .head(&url)
            .send()
            .await
            .and_then(|res| res.error_for_status())
        {
            println!("{} broken: {}", url, err);
        }
    }
}

// keyed by path
struct Manifest(BTreeMap<String, Entry>);
struct Entry {
    checksum: String,
    dropbox_url: Option<String>,
}

impl Manifest {
    fn generate() -> Manifest {
        let mut kv = BTreeMap::new();
        for entry in WalkDir::new("data/input")
            .into_iter()
            .chain(WalkDir::new("data/system").into_iter())
            .filter_map(|e| e.ok())
        {
            if entry.file_type().is_dir() {
                continue;
            }
            let orig_path = entry.path().display().to_string();
            let path = orig_path.replace("\\", "/");
            if path.contains("system/assets/")
                || path.contains("system/fonts")
                || path.contains("system/proposals")
                || path.contains("system/synthetic_maps")
                || path.contains("/polygons/")
            {
                continue;
            }

            println!("> compute md5sum of {}", path);

            // since these files can be very large, computes the md5 hash in chunks
            let mut file = File::open(&orig_path).unwrap();
            let mut buffer = [0 as u8; MD5_BUF_READ_SIZE];
            let mut context = md5::Context::new();
            while let Ok(n) = file.read(&mut buffer) {
                if n == 0 {
                    break;
                }
                context.consume(&buffer[..n]);
            }
            let checksum = format!("{:x}", context.compute());
            kv.insert(
                path,
                Entry {
                    checksum,
                    dropbox_url: None,
                },
            );
        }
        Manifest(kv)
    }

    fn write(&self, path: String) {
        let mut f = File::create(&path).unwrap();
        for (path, entry) in &self.0 {
            writeln!(
                f,
                "{},{},{}",
                path,
                entry.checksum,
                entry.dropbox_url.as_ref().unwrap()
            )
            .unwrap();
        }
        println!("- Wrote {}", path);
    }

    fn load(path: String) -> Result<Manifest, Box<dyn Error>> {
        let mut kv = BTreeMap::new();
        for line in BufReader::new(File::open(path)?).lines() {
            let line = line?;
            let parts = line.split(",").collect::<Vec<_>>();
            assert_eq!(parts.len(), 3);
            kv.insert(
                parts[0].to_string(),
                Entry {
                    checksum: parts[1].to_string(),
                    dropbox_url: Some(parts[2].to_string()),
                },
            );
        }
        Ok(Manifest(kv))
    }

    fn filter(mut self, cities: Cities) -> Manifest {
        // TODO Temporary hack until directories are organized better
        fn map_belongs_to_city(map: &str, city: &str) -> bool {
            match city {
                "seattle" => {
                    map == "ballard"
                        || map == "downtown"
                        || map == "lakeslice"
                        || map == "montlake"
                        || map == "south_seattle"
                        || map == "udistrict"
                        || map == "west_seattle"
                }
                "huge_seattle" => map == "huge_seattle",
                "krakow" => map == "krakow_center",
                "berlin" => map == "berlin_center",
                "xian" => map == "xian",
                "tel_aviv" => map == "tel_aviv",
                "london" => map == "southbank",
                _ => panic!("Unknown city {}. Check your data/config", city),
            }
        }

        let mut remove = Vec::new();
        for path in self.0.keys() {
            // TODO Some hardcoded weird exceptions
            if !cities.runtime.contains(&"huge_seattle".to_string())
                && path == "data/system/scenarios/montlake/everyone_weekday.bin"
            {
                remove.push(path.clone());
                continue;
            }

            let parts = path.split("/").collect::<Vec<_>>();
            if parts[1] == "input" {
                if parts[2] == "screenshots" {
                    let map = parts[3].trim_end_matches(".zip");
                    if cities
                        .input
                        .iter()
                        .any(|city| map_belongs_to_city(map, city))
                    {
                        continue;
                    }
                }
                if parts[2] == "raw_maps" {
                    let map = parts[3].trim_end_matches(".bin");
                    if cities
                        .input
                        .iter()
                        .any(|city| map_belongs_to_city(map, city))
                    {
                        continue;
                    }
                }
                if cities.input.contains(&parts[2].to_string()) {
                    continue;
                }
            } else if parts[1] == "system" {
                if parts[2] == "maps" {
                    let map = parts[3].trim_end_matches(".bin");
                    if cities
                        .runtime
                        .iter()
                        .any(|city| map_belongs_to_city(map, city))
                    {
                        continue;
                    }
                } else if parts[2] == "cities" {
                    if cities.runtime.contains(&basename(parts[3])) {
                        continue;
                    }
                } else {
                    let map = &parts[3];
                    if cities
                        .runtime
                        .iter()
                        .any(|city| map_belongs_to_city(map, city))
                    {
                        continue;
                    }
                }
            } else {
                panic!("Wait what's {}", path);
            }
            remove.push(path.clone());
        }
        for path in remove {
            self.0.remove(&path).unwrap();
        }
        self
    }
}

// What data to download?
struct Cities {
    runtime: Vec<String>,
    input: Vec<String>,
}

impl Cities {
    fn load_or_create() -> Cities {
        let path = "data/config";
        if let Ok(f) = File::open(path) {
            let mut cities = Cities {
                runtime: Vec::new(),
                input: Vec::new(),
            };
            for line in BufReader::new(f).lines() {
                let line = line.unwrap();
                let parts = line.split(": ").collect::<Vec<_>>();
                assert_eq!(parts.len(), 2);
                let list = parts[1]
                    .split(",")
                    .map(|x| x.to_string())
                    .filter(|x| !x.is_empty())
                    .collect::<Vec<_>>();
                if parts[0] == "runtime" {
                    cities.runtime = list;
                } else if parts[0] == "input" {
                    cities.input = list;
                } else {
                    panic!("{} is corrupted, what's {}", path, parts[0]);
                }
            }
            if !cities.runtime.contains(&"seattle".to_string()) {
                panic!(
                    "{}: runtime must contain seattle; the game breaks without this",
                    path
                );
            }
            cities
        } else {
            let mut f = File::create(&path).unwrap();
            writeln!(f, "runtime: seattle,berlin,krakow").unwrap();
            writeln!(f, "input: ").unwrap();
            println!("- Wrote {}", path);
            Cities {
                runtime: vec![
                    "seattle".to_string(),
                    "berlin".to_string(),
                    "krakow".to_string(),
                ],
                input: vec![],
            }
        }
    }
}

fn basename(path: &str) -> String {
    std::path::Path::new(path)
        .file_stem()
        .unwrap()
        .to_os_string()
        .into_string()
        .unwrap()
}

fn run(cmd: &mut Command) -> String {
    println!("> {:?}", cmd);
    String::from_utf8(cmd.output().unwrap().stdout).unwrap()
}

fn rm(path: &str) {
    println!("> rm {}", path);
    match remove_file(path) {
        Ok(_) => {}
        Err(e) => match e.kind() {
            std::io::ErrorKind::NotFound => {
                println!("file {} does not exist, continuing", &path);
            }
            other_error => {
                panic!("problem removing file: {:?}", other_error);
            }
        },
    }
}

async fn curl(entry: Entry) -> Result<(), Box<dyn Error>> {
    let src = entry.dropbox_url.unwrap();
    // the ?dl=0 param at the end of each URL takes you to an interactive page
    // for viewing the folder in the browser. For some reason, curl and wget can
    // both get around this to download the file with no extra flags needed but
    // I can't figure out how to make reqwest do that so this switches it to ?dl=1
    // which redirects to a direct download link
    let src = &format!("{}{}", &src[..src.len() - 1], "1");

    println!("> download {} to {}", src, TMP_DOWNLOAD_NAME);

    let mut output =
        File::create(TMP_DOWNLOAD_NAME).expect(&format!("unable to create {}", TMP_DOWNLOAD_NAME));

    let mut resp = reqwest::get(src).await.unwrap();

    match resp.error_for_status_ref() {
        Ok(_) => {}
        Err(err) => {
            let err = format!("error getting {}: {}", src, err);
            return Err(err.into());
        }
    };
    while let Some(chunk) = resp.chunk().await.unwrap() {
        output.write_all(&chunk).unwrap();
    }

    Ok(())
}

fn unzip(path: &str) {
    println!("> unzip {} {}", TMP_DOWNLOAD_NAME, path);

    let file =
        File::open(TMP_DOWNLOAD_NAME).expect(&format!("unable to open {}", TMP_DOWNLOAD_NAME));
    let mut archive = zip::ZipArchive::new(file).unwrap();

    for i in 0..archive.len() {
        let mut file = archive.by_index(i).unwrap();
        let outpath = file.sanitized_name();

        {
            let comment = file.comment();
            if !comment.is_empty() {
                println!(">  file {} comment: {}", i, comment);
            }
        }

        if (&*file.name()).ends_with('/') {
            println!(
                ">   file {} extracted to \"{}\"",
                i,
                outpath.as_path().display()
            );
            create_dir_all(&outpath).unwrap();
        } else {
            println!(
                ">   file {} extracted to \"{}\"",
                i,
                outpath.as_path().display(),
            );
            if let Some(p) = outpath.parent() {
                if !p.exists() {
                    create_dir_all(&p).unwrap();
                }
            }
            let mut outfile = File::create(&outpath).unwrap();
            copy(&mut file, &mut outfile).unwrap();
        }

        // Get and Set permissions
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            if let Some(mode) = file.unix_mode() {
                set_permissions(&outpath, Permissions::from_mode(mode)).unwrap();
            }
        }
    }
}