steamlocate 2.0.1

Crate for locating Steam game installation directories (and Steam itself!)
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
//! All of the data available from parsing [App] manifest files
//!
//! This contains the definition of [`App`] and all of the types used within it
//!
//! Fundamentally an [`App`] is contained within a [`Library`], but there are a variety of helpers
//! that make locating an app easier. Namely:
//!
//! - [SteamDir::find_app()][crate::SteamDir::find_app]
//!   - Searches through all of the libraries to locate an app by ID
//! - [Library::app()]
//!   - Searches this specific library for an app by ID
//! - [Library::apps()]
//!   - Iterates over all of the apps contained in this library

use std::{
    collections::BTreeMap,
    fs,
    path::{Path, PathBuf},
    slice, time,
};

use crate::{
    error::{ParseError, ParseErrorKind},
    Error, Library, Result,
};

use serde::{Deserialize, Deserializer};

/// An [`Iterator`] over a [`Library`]'s [`App`]s
///
/// Returned from calling [`Library::apps()`]
pub struct Iter<'library> {
    library: &'library Library,
    app_ids: slice::Iter<'library, u32>,
}

impl<'library> Iter<'library> {
    pub(crate) fn new(library: &'library Library) -> Self {
        Self {
            library,
            app_ids: library.app_ids().iter(),
        }
    }
}

impl Iterator for Iter<'_> {
    type Item = Result<App>;

    fn next(&mut self) -> Option<Self::Item> {
        let app_id = *self.app_ids.next()?;
        if let some_res @ Some(_) = self.library.app(app_id) {
            some_res
        } else {
            // We use the listing from libraryfolders, so all apps should be accounted for
            Some(Err(Error::MissingExpectedApp { app_id }))
        }
    }
}

/// Metadata for an installed Steam app
///
/// _See the [module level docs][self] for different ways to get an [`App`]_
///
/// All of the information contained within the `appmanifest_<APP_ID>.acf` file. For instance
///
/// ```vdf
/// "AppState"
/// {
///     "appid"        "599140"
///     "installdir"        "Graveyard Keeper"
///     "name"        "Graveyard Keeper"
///     "LastOwner"        "12312312312312312"
///     "Universe"        "1"
///     "StateFlags"        "6"
///     "LastUpdated"        "1672176869"
///     "UpdateResult"        "0"
///     "SizeOnDisk"        "1805798572"
///     "buildid"        "8559806"
///     "BytesToDownload"        "24348080"
///     "BytesDownloaded"        "0"
///     "TargetBuildID"        "8559806"
///     "AutoUpdateBehavior"        "1"
/// }
/// ```
///
/// gets parsed as
///
/// ```ignore
/// App {
///     app_id: 599140,
///     install_dir: "Graveyard Keeper",
///     name: Some("Graveyard Keeper"),
///     last_user: Some(12312312312312312),
///     universe: Some(Public),
///     state_flags: Some(StateFlags(6)),
///     last_updated: Some(SystemTime {
///         tv_sec: 1672176869,
///         tv_nsec: 0,
///     }),
///     update_result: Some(0),
///     size_on_disk: Some(1805798572),
///     build_id: Some(8559806),
///     bytes_to_download: Some(24348080),
///     bytes_downloaded: Some(0),
///     target_build_id: Some(8559806),
///     auto_update_behavior: Some(OnlyUpdateOnLaunch),
///     // ...
/// }
/// ```
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[cfg_attr(test, derive(serde::Serialize))]
#[non_exhaustive]
#[serde(rename_all = "PascalCase")]
pub struct App {
    /// The app ID of this Steam app
    #[serde(rename = "appid")]
    pub app_id: u32,
    /// The name of the installation directory of this Steam app e.g. `"GarrysMod"`
    ///
    /// If you're trying to get the app's installation directory then take a look at
    /// [`Library::resolve_app_dir()`][crate::Library::resolve_app_dir]
    #[serde(rename = "installdir")]
    pub install_dir: String,
    /// The store name of the Steam app
    #[serde(rename = "name")]
    pub name: Option<String>,
    /// The SteamID64 of the last Steam user that played this game on the filesystem
    #[serde(rename = "LastOwner")]
    pub last_user: Option<u64>,

    pub universe: Option<Universe>,
    pub launcher_path: Option<PathBuf>,
    pub state_flags: Option<StateFlags>,
    // NOTE: Need to handle this for serializing too before `App` can `impl Serialize`
    #[serde(
        alias = "lastupdated",
        default,
        deserialize_with = "de_time_as_secs_from_unix_epoch"
    )]
    pub last_updated: Option<time::SystemTime>,
    // Can't find anything on what these values mean. I've seen 0, 2, 4, 6, and 7
    pub update_result: Option<u64>,
    pub size_on_disk: Option<u64>,
    #[serde(rename = "buildid")]
    pub build_id: Option<u64>,
    pub bytes_to_download: Option<u64>,
    pub bytes_downloaded: Option<u64>,
    pub bytes_to_stage: Option<u64>,
    pub bytes_staged: Option<u64>,
    pub staging_size: Option<u64>,
    #[serde(rename = "TargetBuildID")]
    pub target_build_id: Option<u64>,
    pub auto_update_behavior: Option<AutoUpdateBehavior>,
    pub allow_other_downloads_while_running: Option<AllowOtherDownloadsWhileRunning>,
    pub scheduled_auto_update: Option<ScheduledAutoUpdate>,
    pub full_validate_before_next_update: Option<bool>,
    pub full_validate_after_next_update: Option<bool>,
    #[serde(default)]
    pub installed_depots: BTreeMap<u64, Depot>,
    #[serde(default)]
    pub staged_depots: BTreeMap<u64, Depot>,
    #[serde(default)]
    pub user_config: BTreeMap<String, String>,
    #[serde(default)]
    pub mounted_config: BTreeMap<String, String>,
    #[serde(default)]
    pub install_scripts: BTreeMap<u64, PathBuf>,
    #[serde(default)]
    pub shared_depots: BTreeMap<u64, u64>,
}

impl App {
    pub(crate) fn new(manifest: &Path) -> Result<Self> {
        let contents = fs::read_to_string(manifest).map_err(|io| Error::io(io, manifest))?;
        keyvalues_serde::from_str(&contents)
            .map_err(|err| Error::parse(ParseErrorKind::App, ParseError::from_serde(err), manifest))
    }
}

macro_rules! impl_deserialize_from_u64 {
    ( $ty_name:ty ) => {
        impl<'de> Deserialize<'de> for $ty_name {
            fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                let value = u64::deserialize(deserializer)?;
                Ok(Self::from(value))
            }
        }
    };
}

#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(test, derive(serde::Serialize))]
pub enum Universe {
    Invalid,
    Public,
    Beta,
    Internal,
    Dev,
    Unknown(u64),
}

// More info:
// https://developer.valvesoftware.com/wiki/SteamID#Universes_Available_for_Steam_Accounts
impl From<u64> for Universe {
    fn from(value: u64) -> Self {
        match value {
            0 => Self::Invalid,
            1 => Self::Public,
            2 => Self::Beta,
            3 => Self::Internal,
            4 => Self::Dev,
            unknown => Self::Unknown(unknown),
        }
    }
}

impl_deserialize_from_u64!(Universe);

#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
#[cfg_attr(test, derive(serde::Serialize))]
pub struct StateFlags(pub u64);

impl StateFlags {
    pub fn flags(self) -> StateFlagIter {
        self.into()
    }
}

#[derive(Clone, Debug)]
pub struct StateFlagIter(Option<StateFlagIterInner>);

impl From<StateFlags> for StateFlagIter {
    fn from(state: StateFlags) -> Self {
        Self(Some(state.into()))
    }
}

impl Iterator for StateFlagIter {
    type Item = StateFlag;

    fn next(&mut self) -> Option<Self::Item> {
        // Tiny little state machine:
        // - None indicates the iterator is done (trap state)
        // - Invalid will emit invalid once and finish
        // - Valid will pull on the inner iterator till it's finished
        let current = std::mem::take(&mut self.0);
        let (next, ret) = match current? {
            StateFlagIterInner::Invalid => (None, StateFlag::Invalid),
            StateFlagIterInner::Valid(mut valid) => {
                let ret = valid.next()?;
                (Some(StateFlagIterInner::Valid(valid)), ret)
            }
        };
        self.0 = next;
        Some(ret)
    }
}

#[derive(Clone, Debug)]
enum StateFlagIterInner {
    Invalid,
    Valid(ValidIter),
}

impl From<StateFlags> for StateFlagIterInner {
    fn from(state: StateFlags) -> Self {
        if state.0 == 0 {
            Self::Invalid
        } else {
            Self::Valid(state.into())
        }
    }
}

#[derive(Clone, Debug)]
struct ValidIter {
    state: StateFlags,
    offset: u8,
}

impl From<StateFlags> for ValidIter {
    fn from(state: StateFlags) -> Self {
        Self { state, offset: 0 }
    }
}

impl Iterator for ValidIter {
    type Item = StateFlag;

    fn next(&mut self) -> Option<Self::Item> {
        // Rotate over each bit and emit each one that is set
        loop {
            let flag = 1u64.checked_shl(self.offset.into())?;
            self.offset = self.offset.checked_add(1)?;
            if self.state.0 & flag != 0 {
                break Some(StateFlag::from_bit_offset(self.offset - 1));
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(test, derive(serde::Serialize))]
pub enum StateFlag {
    Invalid,
    Uninstalled,
    UpdateRequired,
    FullyInstalled,
    Encrypted,
    Locked,
    FilesMissing,
    AppRunning,
    FilesCorrupt,
    UpdateRunning,
    UpdatePaused,
    UpdateStarted,
    Uninstalling,
    BackupRunning,
    Reconfiguring,
    Validating,
    AddingFiles,
    Preallocating,
    Downloading,
    Staging,
    Committing,
    UpdateStopping,
    Unknown(u8),
}

// More info: https://github.com/lutris/lutris/blob/master/docs/steam.rst
impl StateFlag {
    fn from_bit_offset(offset: u8) -> Self {
        match offset {
            0 => Self::Uninstalled,
            1 => Self::UpdateRequired,
            2 => Self::FullyInstalled,
            3 => Self::Encrypted,
            4 => Self::Locked,
            5 => Self::FilesMissing,
            6 => Self::AppRunning,
            7 => Self::FilesCorrupt,
            8 => Self::UpdateRunning,
            9 => Self::UpdatePaused,
            10 => Self::UpdateStarted,
            11 => Self::Uninstalling,
            12 => Self::BackupRunning,
            16 => Self::Reconfiguring,
            17 => Self::Validating,
            18 => Self::AddingFiles,
            19 => Self::Preallocating,
            20 => Self::Downloading,
            21 => Self::Staging,
            22 => Self::Committing,
            23 => Self::UpdateStopping,
            unknown @ (13..=15 | 24..) => Self::Unknown(unknown),
        }
    }
}

fn de_time_as_secs_from_unix_epoch<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<time::SystemTime>, D::Error>
where
    D: Deserializer<'de>,
{
    let maybe_time =
        <Option<u64>>::deserialize(deserializer)?.and_then(time_as_secs_from_unix_epoch);
    Ok(maybe_time)
}

fn time_as_secs_from_unix_epoch(secs: u64) -> Option<time::SystemTime> {
    let offset = time::Duration::from_secs(secs);
    time::SystemTime::UNIX_EPOCH.checked_add(offset)
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(test, derive(serde::Serialize))]
pub enum AllowOtherDownloadsWhileRunning {
    UseGlobalSetting,
    Allow,
    Never,
    Unknown(u64),
}

impl From<u64> for AllowOtherDownloadsWhileRunning {
    fn from(value: u64) -> Self {
        match value {
            0 => Self::UseGlobalSetting,
            1 => Self::Allow,
            2 => Self::Never,
            unknown => Self::Unknown(unknown),
        }
    }
}

impl_deserialize_from_u64!(AllowOtherDownloadsWhileRunning);

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(test, derive(serde::Serialize))]
pub enum AutoUpdateBehavior {
    KeepUpToDate,
    OnlyUpdateOnLaunch,
    UpdateWithHighPriority,
    Unknown(u64),
}

impl From<u64> for AutoUpdateBehavior {
    fn from(value: u64) -> Self {
        match value {
            0 => Self::KeepUpToDate,
            1 => Self::OnlyUpdateOnLaunch,
            2 => Self::UpdateWithHighPriority,
            unknown => Self::Unknown(unknown),
        }
    }
}

impl_deserialize_from_u64!(AutoUpdateBehavior);

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(test, derive(serde::Serialize))]
pub enum ScheduledAutoUpdate {
    Zero,
    Time(time::SystemTime),
}

impl<'de> Deserialize<'de> for ScheduledAutoUpdate {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let sched_auto_upd = match u64::deserialize(deserializer)? {
            0 => Self::Zero,
            secs => {
                let time = time_as_secs_from_unix_epoch(secs)
                    .ok_or_else(|| serde::de::Error::custom("Exceeded max time"))?;
                Self::Time(time)
            }
        };
        Ok(sched_auto_upd)
    }
}

#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
#[cfg_attr(test, derive(serde::Serialize))]
#[non_exhaustive]
pub struct Depot {
    pub manifest: u64,
    pub size: u64,
    #[serde(rename = "dlcappid")]
    pub dlc_app_id: Option<u64>,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn app_from_manifest_str(s: &str) -> App {
        keyvalues_serde::from_str(s).unwrap()
    }

    #[test]
    fn minimal() {
        let minimal = r#"
"AppState"
{
	"appid"		"2519830"
	"installdir" "Resonite"
}
"#;

        let app = app_from_manifest_str(minimal);
        insta::assert_ron_snapshot!(app);
    }

    #[test]
    fn sanity() {
        let manifest = include_str!("../tests/assets/appmanifest_230410.acf");
        let app = app_from_manifest_str(manifest);
        insta::assert_ron_snapshot!(app);
    }

    #[test]
    fn more_sanity() {
        let manifest = include_str!("../tests/assets/appmanifest_599140.acf");
        let app = app_from_manifest_str(manifest);
        insta::assert_ron_snapshot!(app);
    }

    #[test]
    fn state_flags() {
        let mut it = StateFlags(0).flags();
        assert_eq!(it.next(), Some(StateFlag::Invalid));
        assert_eq!(it.next(), None);

        let mut it = StateFlags(4).flags();
        assert_eq!(it.next(), Some(StateFlag::FullyInstalled));
        assert_eq!(it.next(), None);

        let mut it = StateFlags(6).flags();
        assert_eq!(it.next(), Some(StateFlag::UpdateRequired));
        assert_eq!(it.next(), Some(StateFlag::FullyInstalled));
        assert_eq!(it.next(), None);
    }
}