destiny_pkg/manager/
path_cache.rs

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
use std::{
    collections::HashMap,
    fs,
    path::{Path, PathBuf},
    time::SystemTime,
};

use itertools::Itertools;
use rustc_hash::FxHashMap;
use tracing::{debug_span, error, info, warn};

use super::PackageManager;
use crate::{package::PackagePlatform, GameVersion};

impl PackageManager {
    #[cfg(feature = "ignore_package_cache")]
    pub(super) fn read_package_cache(silent: bool) -> Option<PathCache> {
        if !silent {
            info!("Not loading tag cache: ignore_package_cache is enabled")
        }
        None
    }

    #[cfg(feature = "ignore_package_cache")]
    pub(super) fn write_package_cache(&self) -> anyhow::Result<()> {
        Ok(())
    }

    #[cfg(not(feature = "ignore_package_cache"))]
    pub(super) fn read_package_cache(silent: bool) -> Option<PathCache> {
        let cache: Option<PathCache> = serde_json::from_reader(
            std::fs::File::open(exe_relative_path("package_cache.json")).ok()?,
        )
        .ok();

        if let Some(ref c) = cache {
            if c.cache_version != PathCache::VERSION {
                if !silent {
                    warn!("Package cache is outdated, building a new one");
                }
                return None;
            }
        }

        cache
    }

    #[cfg(not(feature = "ignore_package_cache"))]
    pub(super) fn write_package_cache(&self) -> anyhow::Result<()> {
        let mut cache = Self::read_package_cache(true).unwrap_or_default();

        let timestamp = fs::metadata(&self.package_dir)
            .ok()
            .and_then(|m| {
                Some(
                    m.modified()
                        .ok()?
                        .duration_since(SystemTime::UNIX_EPOCH)
                        .ok()?
                        .as_secs(),
                )
            })
            .unwrap_or(0);

        let entry = cache
            .versions
            .entry(self.cache_key())
            .or_insert_with(|| PathCacheEntry {
                timestamp,
                version: self.version,
                platform: self.platform,
                base_path: self.package_dir.clone(),
                paths: Default::default(),
            });

        entry.timestamp = timestamp;
        entry.base_path = self.package_dir.clone();
        entry.paths.clear();

        for (id, path) in &self.package_paths {
            entry.paths.insert(*id, path.path.clone());
        }

        Ok(std::fs::write(
            exe_relative_path("package_cache.json"),
            serde_json::to_string_pretty(&cache)?,
        )?)
    }

    #[must_use]
    pub(super) fn validate_cache(
        version: GameVersion,
        platform: Option<PackagePlatform>,
        packages_dir: &Path,
    ) -> Result<FxHashMap<u16, String>, String> {
        if let Some(cache) = Self::read_package_cache(false) {
            info!("Loading package cache");
            if let Some(p) = cache
                .get_paths(version, platform, Some(packages_dir.as_ref()))
                .ok()
                .flatten()
            {
                let timestamp = fs::metadata(&packages_dir)
                    .ok()
                    .and_then(|m| {
                        Some(
                            m.modified()
                                .ok()?
                                .duration_since(SystemTime::UNIX_EPOCH)
                                .ok()?
                                .as_secs(),
                        )
                    })
                    .unwrap_or(0);

                if p.timestamp < timestamp {
                    Err("Package directory changed".to_string())
                } else if &p.base_path != packages_dir {
                    Err("Package directory path changed".to_string())
                } else {
                    Ok(p.paths.clone())
                }
            } else {
                Err(format!(
                    "No cache entry found for version {version:?}, platform {platform:?}"
                ))
            }
        } else {
            Err("Failed to load package cache".to_string())
        }
    }

    /// Generates a key unique to the game version + platform combination
    /// eg. GameVersion::DestinyTheTakenKing and PackagePlatform::PS4 generates cache key "d1_ttk_ps4"
    pub fn cache_key(&self) -> String {
        format!("{}_{}", self.version.id(), self.platform)
    }
}

#[derive(serde::Serialize, serde::Deserialize)]
pub(crate) struct PathCache {
    cache_version: usize,
    versions: HashMap<String, PathCacheEntry>,
}

impl Default for PathCache {
    fn default() -> Self {
        Self {
            cache_version: Self::VERSION,
            versions: HashMap::new(),
        }
    }
}

impl PathCache {
    pub const VERSION: usize = 4;

    /// Gets path cache entry by version and platform
    /// If `platform` is None, the first
    /// This function will return an error if there are multiple entries for the same version when `platform` is None
    pub fn get_paths(
        &self,
        version: GameVersion,
        platform: Option<PackagePlatform>,
        base_path: Option<&Path>,
    ) -> anyhow::Result<Option<&PathCacheEntry>> {
        if let Some(platform) = platform {
            return Ok(self.versions.get(&format!("{}_{}", version.id(), platform)));
        }

        let mut matches = self
            .versions
            .iter()
            .filter(|(_k, v)| {
                v.version == version && platform.map(|p| v.platform == p).unwrap_or(true)
            })
            .map(|(_, v)| v)
            .collect_vec();

        if matches.len() > 1 {
            if let Some(base_path) = base_path {
                matches.retain(|c| c.base_path == base_path)
            }
        }

        if matches.len() > 1 {
            anyhow::bail!(
                "There is more than one cache entry for version '{}', but no platform was given",
                version.name()
            );
        }

        Ok(matches.first().map(|v| *v))
    }
}

#[derive(serde::Serialize, serde::Deserialize)]
pub(crate) struct PathCacheEntry {
    /// Timestamp of the packages directory
    timestamp: u64,
    version: GameVersion,
    platform: PackagePlatform,
    base_path: PathBuf,
    paths: FxHashMap<u16, String>,
}

pub fn exe_directory() -> PathBuf {
    std::env::current_exe()
        .unwrap()
        .parent()
        .unwrap()
        .to_path_buf()
}

pub fn exe_relative_path(path: &str) -> PathBuf {
    exe_directory().join(path)
}