owmods_core 0.15.5

The core library for the Outer Wilds Mod Manager
Documentation
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
use log::warn;
use std::{
    collections::HashSet,
    ffi::OsStr,
    fs::File,
    io::{BufReader, BufWriter, Read, Write},
    path::{Path, PathBuf},
    sync::Arc,
    time::Duration,
};

use anyhow::Result;
use anyhow::{Context, anyhow};
use futures::{StreamExt, stream::FuturesUnordered};
use log::{debug, info};
use tempfile::TempDir;
use tokio::sync::Mutex;
use zip::ZipArchive;

use crate::{
    analytics::{AnalyticsEventName, send_analytics_deferred},
    config::Config,
    constants::OWML_UNIQUE_NAME,
    db::{LocalDatabase, RemoteDatabase},
    file::{check_file_matches_paths, create_all_parents, fix_bom},
    mods::{
        local::{LocalMod, ModManifest, get_paths_to_preserve},
        remote::RemoteMod,
    },
    progress::{ProgressAction, ProgressBar, ProgressType},
    remove::remove_old_mod_files,
    toggle::generate_config,
};

fn get_end_of_url(url: &str) -> &str {
    url.split('/').next_back().unwrap_or(url)
}

async fn download_zip(url: &str, unique_name: Option<&str>, target_path: &Path) -> Result<()> {
    debug!(
        "Begin download of {} to {}",
        url,
        target_path.to_str().unwrap()
    );
    let client = reqwest::Client::new();
    let zip_name = get_end_of_url(url);
    let request = client.get(url);

    let mut stream = File::create(target_path)?;
    let mut download = request.send().await?.error_for_status()?;

    let content_length = download
        .headers()
        .get("Content-Length")
        .ok_or(anyhow!("Response missing Content-Length header"))
        .and_then(|v| {
            v.to_str()
                .context("Failed to decode Content-Length")?
                .parse::<u32>()
                .context("Failed to parse Content-Length")
        });

    let (progress_type, progress_max) = match content_length {
        Ok(max) => (ProgressType::Definite, max),
        Err(why) => {
            warn!("Failed to get content length for download: {why:?}");
            // If we can't get the length or it's to large, just use the max value for
            // the progress bar and make it indefinite.
            (ProgressType::Indefinite, u32::MAX)
        }
    };

    let mut progress = ProgressBar::new(
        target_path.to_str().unwrap(),
        unique_name,
        progress_max,
        &format!("Downloading {zip_name}"),
        &format!("Failed to download {zip_name}"),
        progress_type,
        ProgressAction::Download,
    );

    while let Some(chunk) = download.chunk().await? {
        progress.inc(chunk.len().try_into().unwrap());
        stream.write_all(&chunk)?;
    }

    progress.finish(true, &format!("Downloaded {zip_name}"));

    Ok(())
}

// Does this mean that i'll have to re-open the archive to do anything with it? Yes.
// Do I really care? No.
// You want a better one make it pls thx.
fn get_manifest_path_from_zip(zip_path: &PathBuf) -> Result<(String, PathBuf)> {
    let file = File::open(zip_path)?;
    let mut archive = ZipArchive::new(file)?;

    for index in 0..archive.len() {
        let zip_file = archive.by_index(index)?;
        let path = zip_file.enclosed_name();

        if let Some(path) = path {
            let name = path.file_name();
            if name == Some(OsStr::new("manifest.json")) {
                return Ok((
                    zip_file.name().to_string(),
                    zip_file
                        .enclosed_name()
                        .context("Error reading zip file")?
                        .to_path_buf(),
                ));
            }
        }
    }
    Err(anyhow!("Manifest not found in zip archive"))
}

fn get_unique_name_from_zip(zip_path: &PathBuf) -> Result<String> {
    let (manifest_name, _) = get_manifest_path_from_zip(zip_path)?;
    let file = File::open(zip_path)?;
    let mut archive = ZipArchive::new(file)?;
    let mut manifest = archive.by_name(&manifest_name)?;
    let mut buf = String::new();
    manifest.read_to_string(&mut buf)?;
    let manifest: ModManifest = serde_json::from_str(fix_bom(&buf))?;
    Ok(manifest.unique_name)
}

fn extract_zip(zip_path: &PathBuf, target_path: &PathBuf, display_name: &str) -> Result<()> {
    debug!(
        "Begin extraction of {} to {}",
        zip_path.to_str().unwrap(),
        target_path.to_str().unwrap()
    );
    let mut progress = ProgressBar::new(
        zip_path.to_str().unwrap(),
        None,
        0,
        &format!("Extracting {display_name}"),
        &format!("Failed To Extract {display_name}"),
        ProgressType::Indefinite,
        ProgressAction::Extract,
    );
    let file = File::open(zip_path)?;
    let mut archive = ZipArchive::new(file)?;
    archive.extract(target_path)?;
    progress.finish(true, &format!("Extracted {display_name}!"));
    Ok(())
}

fn extract_mod_zip(
    zip_path: &PathBuf,
    unique_name: Option<&str>,
    target_path: &Path,
    exclude_paths: Vec<PathBuf>,
) -> Result<LocalMod> {
    debug!(
        "Begin extraction of {} to {}",
        zip_path.to_str().unwrap(),
        target_path.to_str().unwrap()
    );
    let (_, manifest_path) = get_manifest_path_from_zip(zip_path)?;
    debug!(
        "Found manifest at {} in zip, extracting siblings",
        manifest_path.to_str().unwrap()
    );
    let parent_path = manifest_path.parent().unwrap_or_else(|| Path::new(""));
    let zip_name = zip_path.file_name().unwrap().to_str().unwrap();

    let file = File::open(zip_path)?;
    let mut archive = ZipArchive::new(file);

    let mut progress = ProgressBar::new(
        zip_path.to_str().unwrap(),
        unique_name,
        archive
            .as_ref()
            .map(|a| a.len().try_into().unwrap_or(0))
            .unwrap_or(0),
        &format!("Extracting {zip_name}"),
        &format!("Failed To Extract {zip_name}"),
        ProgressType::Definite,
        ProgressAction::Extract,
    );

    match &mut archive {
        Ok(archive) => {
            for idx in 0..archive.len() {
                progress.inc(1);
                let zip_file = archive.by_index(idx)?;
                if zip_file.is_file() {
                    let file_path = zip_file.enclosed_name().context("Can't Read Zip File")?;
                    if file_path.starts_with(parent_path) {
                        // Unwrap is safe bc we know it's a file and OsStr.to_str shouldn't fail
                        let file_name = file_path.file_name().unwrap().to_str().unwrap();
                        progress.set_msg(&format!("Extracting {file_name}"));
                        // Unwrap is safe bc we just checked if it starts with the parent path
                        let rel_path = file_path.strip_prefix(parent_path).unwrap();
                        if !check_file_matches_paths(rel_path, &exclude_paths) {
                            let output_path = target_path.join(rel_path);
                            create_all_parents(&output_path)?;
                            let out_file = File::create(&output_path)?;
                            let reader = BufReader::new(zip_file);
                            let mut writer = BufWriter::new(out_file);
                            for byte in reader.bytes() {
                                writer.write_all(&[byte?])?;
                            }
                        }
                    }
                }
            }

            let new_mod = LocalDatabase::read_local_mod(&target_path.join("manifest.json"))?;
            progress.finish(true, &format!("Installed {}", new_mod.manifest.name));
            Ok(new_mod)
        }
        Err(why) => {
            progress.finish(false, "");
            Err(anyhow!("Failed to extract {zip_name}: {why:?}"))
        }
    }
}

/// Downloads and installs OWML to the path specified in `config.owml_path`
///
/// ## Errors
///
/// If we can't download or extract the OWML zip for any reason.
///
/// ## Examples
///
/// ```no_run
/// use owmods_core::config::Config;
/// use owmods_core::download::download_and_install_owml;
/// use owmods_core::db::RemoteDatabase;
///
/// # tokio_test::block_on(async {
/// let config = Config::get(None).unwrap();
/// let remote_db = RemoteDatabase::fetch(&config.database_url).await.unwrap();
/// let owml = remote_db.get_owml().unwrap();
///
/// download_and_install_owml(&config, &owml, false).await.unwrap();
///
/// println!("Installed OWML!");
/// # });
/// ```
///
/// ```no_run
/// use owmods_core::config::Config;
/// use owmods_core::download::download_and_install_owml;
/// use owmods_core::db::RemoteDatabase;
///
/// # tokio_test::block_on(async {
/// let config = Config::get(None).unwrap();
/// let remote_db = RemoteDatabase::fetch(&config.database_url).await.unwrap();
/// let owml = remote_db.get_owml().unwrap();
///
/// download_and_install_owml(&config, &owml, true).await.unwrap();
///
/// println!("Installed OWML Prerelease!");
/// # });
/// ```
///
pub async fn download_and_install_owml(
    config: &Config,
    owml: &RemoteMod,
    prerelease: bool,
) -> Result<()> {
    let url = if prerelease {
        owml.prerelease
            .as_ref()
            .map(|p| &p.download_url)
            .context("No prerelease for OWML found")
    } else {
        Ok(&owml.download_url)
    }?;
    let target_path = PathBuf::from(&config.owml_path);
    let temp_dir = TempDir::new()?;
    let download_path = temp_dir.path().join("OWML.zip");
    download_zip(url, Some(OWML_UNIQUE_NAME), &download_path).await?;
    extract_zip(&download_path, &target_path, "OWML")?;

    if config.owml_path.is_empty() {
        let mut new_config = config.clone();
        new_config.owml_path = String::from(target_path.to_str().unwrap());
        new_config.save()?;
    }

    temp_dir.close()?;

    send_analytics_deferred(
        AnalyticsEventName::ModRequiredInstall,
        OWML_UNIQUE_NAME,
        config,
    )
    .await;

    Ok(())
}

/// Install a mod from a local ZIP file
///
/// ## Returns
///
/// The newly installed [LocalMod]
///
/// ## Errors
///
/// - If we can't find a `manifest.json` file within the archive
/// - If we can't extract the zip file
///
/// ## Examples
///
/// ```no_run
/// use owmods_core::db::LocalDatabase;
/// use owmods_core::config::Config;
/// use owmods_core::download::install_mod_from_zip;
///
/// let config = Config::get(None).unwrap();
/// let local_db = LocalDatabase::fetch(&config.owml_path).unwrap();
///
/// let new_mod = install_mod_from_zip(&"/home/user/Downloads/Mod.zip".into(), &config, &local_db).unwrap();
///
/// println!("Installed {}", new_mod.manifest.name);
/// ```
///
pub fn install_mod_from_zip(
    zip_path: &PathBuf,
    config: &Config,
    local_db: &LocalDatabase,
) -> Result<LocalMod> {
    let unique_name = get_unique_name_from_zip(zip_path);

    match unique_name {
        Ok(unique_name) => {
            let target_path = local_db
                .get_mod_unsafe(&unique_name)
                .map(|m| PathBuf::from(m.get_path().to_string()))
                .unwrap_or_else(|| {
                    PathBuf::from(&config.owml_path)
                        .join("Mods")
                        .join(&unique_name)
                });
            let local_mod = local_db.get_mod(&unique_name);

            if let Some(local_mod) = local_mod {
                remove_old_mod_files(local_mod)?;
            }

            let paths_to_preserve = get_paths_to_preserve(local_mod);

            let new_mod = extract_mod_zip(
                zip_path,
                Some(&unique_name),
                &target_path,
                paths_to_preserve,
            )?;
            let config_path = target_path.join("config.json");
            if local_mod.is_none() || !config_path.is_file() {
                // First install, generate config
                generate_config(&config_path)?;
            }
            Ok(new_mod)
        }
        Err(why) => {
            // Make a stub progress bar
            let mut progress = ProgressBar::new(
                zip_path.to_str().unwrap(),
                None,
                0,
                "",
                &format!("Failed To Extract {}", zip_path.to_str().unwrap()),
                ProgressType::Indefinite,
                ProgressAction::Extract,
            );
            // Need to wait a sec for the progress to be reported, otherwise the log messages overlap and create an unknown bar
            std::thread::sleep(Duration::from_secs(1));
            progress.finish(false, "");
            Err(anyhow!(
                "Failed To Extract {}: {why:?}",
                zip_path.to_str().unwrap()
            ))
        }
    }
}

/// Download and install a mod from a URL
///
/// ## Returns
///
/// The newly installed [LocalMod]
///
/// ## Errors
///
/// - We can't download the ZIP file
/// - We can't extract the ZIP file
/// - There is no `manifest.json` present in the archive / it's not readable
///
/// ## Examples
///
/// ```no_run
/// use owmods_core::db::LocalDatabase;
/// use owmods_core::config::Config;
/// use owmods_core::download::install_mod_from_url;
///
/// # tokio_test::block_on(async {
/// let config = Config::get(None).unwrap();
/// let local_db = LocalDatabase::fetch(&config.owml_path).unwrap();
///
/// let new_mod = install_mod_from_url("https://example.com/Mod.zip", None, &config, &local_db).await.unwrap();
///
/// println!("Installed {}", new_mod.manifest.name);
/// # });
/// ```
///
pub async fn install_mod_from_url(
    url: &str,
    unique_name: Option<&str>,
    config: &Config,
    local_db: &LocalDatabase,
) -> Result<LocalMod> {
    let zip_name = get_end_of_url(url).replace(".zip", "");

    let temp_dir = TempDir::new()?;
    let download_path = temp_dir.path().join(format!("{zip_name}.zip"));

    download_zip(url, unique_name, &download_path).await?;
    let new_mod = install_mod_from_zip(&download_path, config, local_db)?;

    temp_dir.close()?;

    Ok(new_mod)
}

/// A utility for deduplicating mod installs, pass this to [install_mods_parallel] and
/// [install_mod_from_db] to prevent duplicate downloads during installation.
///
#[derive(Default, Debug)]
pub struct ModDeduper {
    /// Mods that are actively being installed
    active: HashSet<String>,
    /// Active installation jobs that are running
    jobs: usize,
}

impl ModDeduper {
    /// Create a new deduper
    pub fn new() -> Self {
        Self::default()
    }

    /// Mark an installation job as started, the deduper will start trying to dedup
    pub(crate) fn start_job(&mut self) {
        self.jobs += 1;
    }

    /// Mark a job as completed, if this is the last job we'll clear the installed mods.
    pub(crate) fn complete_job(&mut self) {
        if self.jobs == 1 {
            self.jobs = 0;
            self.active.clear();
        } else if self.jobs != 0 {
            self.jobs -= 1;
        }
    }

    /// Given a set of mods, return only the mods not currently being installed. Also adds the mods
    /// to the deduper.
    pub(crate) fn dedup(&mut self, mods: &[String]) -> Vec<String> {
        mods.iter()
            .filter(|unique_name| {
                if !self.active.contains(*unique_name) {
                    self.active.insert(unique_name.to_string());
                    true
                } else {
                    false
                }
            })
            .cloned()
            .collect()
    }
}

struct ModDeduperGuard(Arc<Mutex<ModDeduper>>);

impl Drop for ModDeduperGuard {
    fn drop(&mut self) {
        let dedup = self.0.clone();
        tokio::spawn(async move {
            let mut dedup = dedup.lock().await;
            dedup.complete_job();
        });
    }
}

/// Install a list of mods concurrently.
/// This should be your preferred method when installing many mods.
/// **Note that this does not send an analytics event**
///
/// ## Returns
///
/// The newly installed mods
///
/// ## Errors
///
/// If **any** mod fails to install from the list
///
/// ## Examples
///
/// ```no_run
/// use owmods_core::db::{LocalDatabase, RemoteDatabase};
/// use owmods_core::config::Config;
/// use owmods_core::download::install_mods_parallel;
/// use owmods_core::analytics::{send_analytics_event, AnalyticsEventName};
///
/// # tokio_test::block_on(async {
/// let config = Config::get(None).unwrap();
/// let local_db = LocalDatabase::fetch(&config.owml_path).unwrap();
/// let remote_db = RemoteDatabase::fetch(&config.database_url).await.unwrap();
///
/// let installed = install_mods_parallel(vec!["Bwc9876.TimeSaver".into(), "Raicuparta.NomaiVR".into()], &config, &remote_db, &local_db).await.unwrap();
///
/// for installed_mod in installed {
///     println!("Installed {}", installed_mod.manifest.name);
///     send_analytics_event(AnalyticsEventName::ModInstall, &installed_mod.manifest.unique_name, !config.send_analytics).await;
/// }
/// # });
/// ```
///
pub async fn install_mods_parallel(
    unique_names: Vec<String>,
    config: &Config,
    remote_db: &RemoteDatabase,
    local_db: &LocalDatabase,
) -> Result<Vec<LocalMod>> {
    let mut set = FuturesUnordered::new();
    let mut installed: Vec<LocalMod> = Vec::with_capacity(unique_names.len());
    let to_install = {
        let mut dedup = local_db.dedup.lock().await;
        dedup.start_job();
        (
            dedup.dedup(&unique_names),
            ModDeduperGuard(local_db.dedup.clone()),
        )
    };
    for name in to_install.0.iter() {
        let remote_mod = remote_db
            .get_mod(name)
            .with_context(|| format!("Mod {name} not found in database."))?;

        let task = install_mod_from_url(
            &remote_mod.download_url,
            Some(&remote_mod.unique_name),
            config,
            local_db,
        );
        set.push(task);
    }
    while let Some(res) = set.next().await {
        let m = res?;
        installed.push(m);
    }
    drop(to_install);
    Ok(installed)
}

/// Install mod from the database with the given unique name.
/// This should be the preferred method when installing a specific mod.
/// It can also install prereleases and auto-install dependencies (recursively) as well.
/// This will also send analytics events given you set `ANALYTICS_API_KEY`.
///
/// ## Errors
///
/// - If you requested a prerelease and the mod doesn't have one.
/// - If we can't install the target mod for any reason.
/// - If we can't install **any** dependencies for any reason.
///
/// ## Examples
///
/// ```no_run
/// use owmods_core::db::{LocalDatabase, RemoteDatabase};
/// use owmods_core::config::Config;
/// use owmods_core::download::install_mod_from_db;
///
/// # tokio_test::block_on(async {
/// let config = Config::get(None).unwrap();
/// let local_db = LocalDatabase::fetch(&config.owml_path).unwrap();
/// let remote_db = RemoteDatabase::fetch(&config.database_url).await.unwrap();
///
/// install_mod_from_db(&"Bwc9876.TimeSaver".to_string(), &config, &remote_db, &local_db, false, false).await.unwrap();
///
/// println!("Installed Bwc9876.TimeSaver!");
/// # });
/// ```
///
/// ```no_run
/// use owmods_core::db::{LocalDatabase, RemoteDatabase};
/// use owmods_core::config::Config;
/// use owmods_core::download::install_mod_from_db;
///
/// # tokio_test::block_on(async {
/// let config = Config::get(None).unwrap();
/// let local_db = LocalDatabase::fetch(&config.owml_path).unwrap();
/// let remote_db = RemoteDatabase::fetch(&config.database_url).await.unwrap();
///
/// install_mod_from_db(&"Bwc9876.TimeSaver".to_string(), &config, &remote_db, &local_db, false, true).await.unwrap();
///
/// println!("Installed Bwc9876.TimeSaver Prerelease!");
/// # });
/// ```
///
/// ```no_run
/// use owmods_core::db::{LocalDatabase, RemoteDatabase};
/// use owmods_core::config::Config;
/// use owmods_core::download::install_mod_from_db;
///
/// # tokio_test::block_on(async {
/// let config = Config::get(None).unwrap();
/// let local_db = LocalDatabase::fetch(&config.owml_path).unwrap();
/// let remote_db = RemoteDatabase::fetch(&config.database_url).await.unwrap();
///
/// install_mod_from_db(&"xen.NewHorizons".to_string(), &config, &remote_db, &local_db, true, false).await.unwrap();
///
/// println!("Installed xen.NewHorizons and all dependencies!");
/// # });
/// ```
///
pub async fn install_mod_from_db(
    unique_name: &String,
    config: &Config,
    remote_db: &RemoteDatabase,
    local_db: &LocalDatabase,
    recursive: bool,
    prerelease: bool,
) -> Result<LocalMod> {
    let existing_mod = local_db.get_mod(unique_name);

    let already_installed = existing_mod.is_some();
    let existing_version = existing_mod
        .as_ref()
        .map(|m| m.manifest.version.clone())
        .unwrap_or_default();

    let remote_mod = remote_db
        .get_mod(unique_name)
        .with_context(|| format!("Mod {unique_name} not found"))?;
    let target_url = if prerelease {
        let prerelease = remote_mod
            .prerelease
            .as_ref()
            .with_context(|| format!("No prerelease for {unique_name} found"))?;
        let url = &prerelease.download_url;
        info!(
            "Using Prerelease {} for {}",
            prerelease.version, remote_mod.name
        );
        url.clone()
    } else {
        remote_mod.download_url.clone()
    };

    // Should we send `ModInstall` to analytics for direct dependencies?
    let root_mod_is_symbolic = remote_mod
        .tags
        .as_ref()
        .is_some_and(|t| t.iter().any(|t| t == "pack"));

    let dedup_lock = {
        let mut dedup = local_db.dedup.lock().await;
        dedup.start_job();
        ModDeduperGuard(local_db.dedup.clone())
    };

    let new_mod =
        install_mod_from_url(&target_url, Some(&remote_mod.unique_name), config, local_db).await?;

    if recursive && let Some(mut to_install) = new_mod.manifest.dependencies.as_ref().cloned() {
        let mut installed: Vec<String> = local_db
            .valid()
            .filter_map(|m| {
                if m.manifest.unique_name == *unique_name {
                    None
                } else {
                    Some(m.manifest.unique_name.clone())
                }
            })
            .collect();

        installed.push(new_mod.manifest.unique_name.clone());

        let mut count = 1;

        while !to_install.is_empty() {
            debug!(
                "Begin round {} of install with {} dependencies",
                count,
                installed.len()
            );
            let newly_installed = install_mods_parallel(
                to_install
                    .drain(..)
                    .filter(|m| !installed.contains(m))
                    .collect(),
                config,
                remote_db,
                local_db,
            )
            .await?;
            for installed_mod in newly_installed
                .iter()
                .filter(|m| &m.manifest.unique_name != unique_name)
            {
                let event = if count == 1 && root_mod_is_symbolic {
                    // Direct dependencies of symbolic mods should be counted as normal
                    // installs
                    AnalyticsEventName::ModInstall
                } else {
                    AnalyticsEventName::ModRequiredInstall
                };
                send_analytics_deferred(event, &installed_mod.manifest.unique_name, config).await;
            }
            installed.append(
                &mut newly_installed
                    .iter()
                    .map(|m| m.manifest.unique_name.to_owned())
                    .collect(),
            );
            for new_mod in newly_installed.into_iter() {
                if let Some(mut deps) = new_mod.manifest.dependencies {
                    to_install.append(&mut deps);
                }
            }
            count += 1;
        }
    }

    drop(dedup_lock);

    let mod_event = if prerelease {
        AnalyticsEventName::ModPrereleaseInstall
    } else if already_installed {
        if existing_version == new_mod.manifest.version {
            AnalyticsEventName::ModReinstall
        } else {
            AnalyticsEventName::ModUpdate
        }
    } else {
        AnalyticsEventName::ModInstall
    };

    send_analytics_deferred(mod_event, unique_name, config).await;
    Ok(new_mod)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        file::serialize_to_json,
        test_utils::{TestContext, get_test_file, make_test_dir},
    };
    use std::fs::read_to_string;

    const TEST_URL: &str =
        "https://github.com/Bwc9876/OW-TimeSaver/releases/download/1.1.1/Bwc9876.TimeSaver.zip";

    #[test]
    fn test_download_zip() {
        tokio_test::block_on(async {
            let dir = make_test_dir();
            let path = dir.path().join("test.zip");
            download_zip(TEST_URL, None, &path).await.unwrap();
            assert!(path.is_file());
            dir.close().unwrap();
        });
    }

    #[test]
    fn test_get_manifest_path() {
        let path = get_test_file("Bwc9876.NestedManifest.zip");
        let (_, manifest_path) = get_manifest_path_from_zip(&path).unwrap();
        assert_eq!(
            manifest_path,
            PathBuf::from("Bwc9876.NestedManifest/Folder1/Folder2/manifest.json")
        );
    }

    #[test]
    fn test_get_unique_name() {
        let path = get_test_file("Bwc9876.TimeSaver.zip");
        let name = get_unique_name_from_zip(&path).unwrap();
        assert_eq!(name, "Bwc9876.TimeSaver");
    }

    #[test]
    fn test_extract_zip() {
        let zip_path = get_test_file("Bwc9876.TimeSaver.zip");
        let dir = make_test_dir();
        let target_path = dir.path().join("Bwc9876.TimeSaver");
        extract_zip(&zip_path, &target_path, "Test").unwrap();
        assert!(target_path.is_dir());
        assert!(target_path.join("manifest.json").is_file());
        dir.close().unwrap();
    }

    #[test]
    fn test_extract_mod_zip_nested() {
        let zip_path = get_test_file("Bwc9876.NestedManifest.zip");
        let dir = make_test_dir();
        let target_path = dir.path().join("Bwc9876.TimeSaver");
        let new_mod = extract_mod_zip(&zip_path, None, &target_path, vec![]).unwrap();
        assert!(target_path.join("manifest.json").is_file());
        assert_eq!(new_mod.mod_path, target_path.to_str().unwrap());
        assert!(!target_path.join("Folder1").is_dir());
        dir.close().unwrap();
    }

    #[test]
    fn test_extract_mod_zip_preserve() {
        let zip_path = get_test_file("Bwc9876.NestedManifest.zip");
        let mut ctx = TestContext::new();
        let target_path = ctx.get_test_path("Bwc9876.TimeSaver");
        ctx.install_test_zip("Bwc9876.TimeSaver.zip", true);
        let preserve_path = target_path.join("preserve_me.json");
        assert!(preserve_path.is_file());
        let mut file = File::create(&preserve_path).unwrap();
        write!(file, "yippee!").unwrap();
        drop(file);
        extract_mod_zip(
            &zip_path,
            None,
            &target_path,
            vec![PathBuf::from("preserve_me.json")],
        )
        .unwrap();
        assert!(preserve_path.is_file());
        let contents = read_to_string(&preserve_path).unwrap();
        assert_eq!(contents, "yippee!");
    }

    #[test]
    fn test_install_mod_from_zip() {
        let zip_path = get_test_file("Bwc9876.TimeSaver.zip");
        let ctx = TestContext::new();
        let target_path = ctx.get_test_path("Bwc9876.TimeSaver");
        let new_mod = install_mod_from_zip(&zip_path, &ctx.config, &ctx.local_db).unwrap();
        assert!(target_path.is_dir());
        assert!(target_path.join("config.json").is_file());
        assert!(target_path.join("manifest.json").is_file());
        assert_eq!(new_mod.manifest.name, "TimeSaver");
        assert_eq!(new_mod.mod_path, target_path.to_str().unwrap());
    }

    #[test]
    fn test_install_from_zip_diff_path() {
        let zip_path = get_test_file("Bwc9876.TimeSaver.zip");
        let mut ctx = TestContext::new();
        let target_path = ctx.get_test_path("Other.Path");
        extract_mod_zip(&zip_path, None, &target_path, vec![]).unwrap();
        ctx.fetch_local_db();
        let new_mod = install_mod_from_zip(&zip_path, &ctx.config, &ctx.local_db).unwrap();
        ctx.fetch_local_db();
        assert!(target_path.is_dir());
        assert!(target_path.join("manifest.json").is_file());
        assert_eq!(new_mod.manifest.name, "TimeSaver");
        assert_eq!(new_mod.mod_path, target_path.to_str().unwrap());
        assert!(!ctx.join_mods_folder("Bwc9876.TimeSaver").is_dir());
    }

    #[test]
    fn test_install_mod_from_url() {
        tokio_test::block_on(async {
            let ctx = TestContext::new();
            let new_mod = install_mod_from_url(TEST_URL, None, &ctx.config, &ctx.local_db)
                .await
                .unwrap();
            let target_path = ctx.get_test_path("Bwc9876.TimeSaver");
            assert!(target_path.is_dir());
            assert_eq!(new_mod.mod_path, target_path.to_str().unwrap());
        });
    }

    #[test]
    fn test_install_mods_parallel() {
        tokio_test::block_on(async {
            let mut ctx = TestContext::new();
            ctx.fetch_remote_db().await;
            let mods: Vec<String> = vec![
                "Bwc9876.TimeSaver".to_string(),
                "Bwc9876.SaveEditor".to_string(),
            ];
            let mods = install_mods_parallel(mods, &ctx.config, &ctx.remote_db, &ctx.local_db)
                .await
                .unwrap();
            assert_eq!(mods.len(), 2);
            assert!(ctx.get_test_path("Bwc9876.TimeSaver").is_dir());
            assert!(ctx.get_test_path("Bwc9876.SaveEditor").is_dir());
        });
    }

    #[test]
    fn test_install_mod_from_db() {
        tokio_test::block_on(async {
            let mut ctx = TestContext::new();
            ctx.fetch_remote_db().await;
            let target_path = ctx.get_test_path("Bwc9876.TimeSaver");
            install_mod_from_db(
                &"Bwc9876.TimeSaver".to_string(),
                &ctx.config,
                &ctx.remote_db,
                &ctx.local_db,
                false,
                false,
            )
            .await
            .unwrap();
            assert!(target_path.is_dir());
        });
    }

    async fn setup_recursive() -> TestContext {
        let mut ctx = TestContext::new();
        let mut new_mod = ctx.install_test_zip("Bwc9876.TimeSaver.zip", true);
        ctx.fetch_remote_db().await;
        new_mod.manifest.dependencies = Some(vec!["Bwc9876.SaveEditor".to_string()]);
        new_mod.manifest.paths_to_preserve = Some(vec!["manifest.json".to_string()]);
        let target_path = ctx.get_test_path("Bwc9876.TimeSaver");
        serialize_to_json(&new_mod.manifest, &target_path.join("manifest.json"), true).unwrap();
        ctx
    }

    #[test]
    fn test_install_mod_from_db_recursive() {
        tokio_test::block_on(async {
            let mut ctx = setup_recursive().await;
            let target_path = ctx.get_test_path("Bwc9876.TimeSaver");
            ctx.fetch_local_db();
            install_mod_from_db(
                &"Bwc9876.TimeSaver".to_string(),
                &ctx.config,
                &ctx.remote_db,
                &ctx.local_db,
                true,
                false,
            )
            .await
            .unwrap();
            assert!(target_path.is_dir());
        });
    }

    #[test]
    fn test_install_mod_from_db_cyclical_deps() {
        tokio_test::block_on(async {
            let mut ctx = setup_recursive().await;

            let mut new_mod_2 = ctx.install_test_zip("Bwc9876.SaveEditor.zip", true);
            let target_path_2 = ctx.get_test_path("Bwc9876.SaveEditor");
            new_mod_2.manifest.dependencies = Some(vec!["Bwc9876.TimeSaver".to_string()]);
            new_mod_2.manifest.paths_to_preserve = Some(vec!["manifest.json".to_string()]);
            serialize_to_json(
                &new_mod_2.manifest,
                &target_path_2.join("manifest.json"),
                true,
            )
            .unwrap();
            ctx.fetch_local_db();
            install_mod_from_db(
                &"Bwc9876.TimeSaver".to_string(),
                &ctx.config,
                &ctx.remote_db,
                &ctx.local_db,
                true,
                false,
            )
            .await
            .unwrap();
            assert!(target_path_2.is_dir());
        });
    }
}