-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.rs
580 lines (509 loc) · 17.5 KB
/
lib.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
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
#![warn(clippy::all, clippy::pedantic, clippy::multiple_crate_versions)]
use std::{
collections::BTreeSet,
fs, io,
path::{Path, PathBuf},
slice::Iter,
};
use itertools::Itertools;
use serde::{
de::{IgnoredAny, MapAccess, Visitor},
Deserialize,
};
use thiserror::Error;
use tracing::{debug, warn};
use plumber_vdf as vdf;
static SOURCE_APPS: [u32; 90] = [
219, 220, 240, 260, 280, 300, 320, 340, 360, 380, 400, 410, 420, 440, 500, 550, 570, 590, 620,
630, 730, 1300, 1800, 2100, 2120, 2130, 2400, 2430, 2450, 2600, 4000, 17500, 17510, 17520,
17530, 17550, 17570, 17580, 17700, 17710, 17730, 17740, 17750, 90007, 222_880, 224_260,
235_780, 238_430, 252_530, 261_820, 261_980, 265_630, 270_370, 280_740, 286_080, 287_820,
290_930, 313_240, 317_360, 317_400, 317_790, 334_370, 346_290, 346_330, 349_480, 353_220,
362_890, 397_680, 433_970, 440_000, 447_820, 563_560, 587_650, 601_360, 628_410, 638_800,
669_270, 747_250, 869_480, 6_626_680, 1_054_600, 1_057_700, 1_104_390, 1_117_390, 1_154_130,
1_255_980, 1_341_060, 1_367_890, 1_372_780, 1_389_950,
];
fn is_acf_file(filename: &str) -> bool {
filename
.rsplit('.')
.next()
.map(|ext| ext.eq_ignore_ascii_case("acf"))
== Some(true)
}
#[derive(Debug, PartialEq, Deserialize)]
#[serde(case_insensitive)]
struct AppManifest {
#[serde(rename = "AppState")]
pub app_state: AppState,
}
#[derive(Debug, PartialEq, Deserialize)]
#[serde(case_insensitive)]
struct AppState {
#[serde(rename = "appid")]
pub app_id: u32,
pub name: String,
#[serde(rename = "installdir")]
pub install_dir: PathBuf,
}
impl AppState {
pub fn into_app<P: AsRef<Path>>(self, steamapps_folder: P) -> App {
App {
app_id: self.app_id,
name: self.name,
install_dir: steamapps_folder
.as_ref()
.join("common")
.join(self.install_dir),
}
}
}
#[derive(Debug, PartialEq, Deserialize)]
#[serde(case_insensitive)]
struct LibraryFoldersFile {
#[serde(rename = "LibraryFolders")]
pub library_folders: LibraryFolders,
}
#[derive(Debug, PartialEq)]
struct LibraryFolders(Libraries);
impl<'de> Deserialize<'de> for LibraryFolders {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct LibraryFoldersKey;
impl<'de> Deserialize<'de> for LibraryFoldersKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct LibraryFoldersKeyVisitor;
impl<'de> Visitor<'de> for LibraryFoldersKeyVisitor {
type Value = LibraryFoldersKey;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("an int")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
v.parse::<u64>().map_or_else(
|_| {
Err(serde::de::Error::invalid_type(
serde::de::Unexpected::Str(v),
&Self,
))
},
|_| Ok(LibraryFoldersKey),
)
}
}
deserializer.deserialize_str(LibraryFoldersKeyVisitor)
}
}
struct LibraryFoldersVisitor;
impl<'de> Visitor<'de> for LibraryFoldersVisitor {
type Value = LibraryFolders;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("class LibraryFolders")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut library_folders: Vec<LibraryFolder> = Vec::new();
while let Some(key) = if let Ok(key) = map.next_key::<LibraryFoldersKey>() {
key.map(Some)
} else {
Some(None)
} {
if key.is_some() {
library_folders.push(map.next_value()?);
} else {
map.next_value::<IgnoredAny>()?;
}
}
Ok(LibraryFolders(Libraries {
paths: library_folders.into_iter().map(|f| f.path).collect(),
}))
}
}
deserializer.deserialize_map(LibraryFoldersVisitor)
}
}
#[derive(Debug, PartialEq, Deserialize)]
#[serde(case_insensitive)]
struct LibraryFolder {
path: PathBuf,
}
#[derive(Debug, Error)]
pub enum LibraryDiscoveryError {
#[error("io error reading `{path}`: {inner}")]
Io { path: String, inner: io::Error },
#[error("error deserializing libraryfolders.vdf: {0}")]
Deserialization(#[from] vdf::Error),
#[error("home directory is unknown")]
NoHome,
}
impl LibraryDiscoveryError {
fn from_io(err: io::Error, path: &Path) -> Self {
Self::Io {
path: path.as_os_str().to_string_lossy().into_owned(),
inner: err,
}
}
}
#[derive(Debug, Error)]
pub enum AppError {
#[error("io error reading `{path}`: {inner}")]
Io { path: String, inner: io::Error },
#[error("error deserializing appmanifest `{path}`: {inner}")]
Deserialization { path: String, inner: vdf::Error },
}
impl AppError {
fn from_io(err: io::Error, path: &Path) -> Self {
Self::Io {
path: path.as_os_str().to_string_lossy().into_owned(),
inner: err,
}
}
fn from_vdf(err: vdf::Error, path: &Path) -> Self {
Self::Deserialization {
path: path.as_os_str().to_string_lossy().into_owned(),
inner: err,
}
}
}
/// A steam app. `install_dir` is absolute.
#[derive(Debug, PartialEq, Eq)]
pub struct App {
pub app_id: u32,
pub name: String,
pub install_dir: PathBuf,
}
/// A list of steam's libraries.
#[derive(Debug, PartialEq, Eq)]
pub struct Libraries {
pub paths: Vec<PathBuf>,
}
impl Libraries {
#[must_use]
pub fn new(paths: Vec<PathBuf>) -> Self {
Self { paths }
}
/// Discover local Steam libraries.
/// Steam needs to be installed.
///
/// # Errors
///
/// Returns [`Err`] if the libraryfolders.vdf read fails or the deserialization fails.
/// On Windows, also returns [`Err`] if Steam's registry entries can't be read.
/// On other platforms, also returns [`Err`] if the home directroy can't be determined.
pub fn discover() -> Result<Self, LibraryDiscoveryError> {
Self::discover_impl()
}
#[cfg(windows)]
fn discover_impl() -> Result<Self, LibraryDiscoveryError> {
use winreg::{enums::HKEY_CURRENT_USER, RegKey};
debug!("reading registry to determine steam install directory");
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let steam = hkcu.open_subkey("SOFTWARE\\Valve\\Steam").map_err(|err| {
LibraryDiscoveryError::Io {
inner: err,
path: "registry HKEY_CURRENT_USER\\SOFTWARE\\Valve\\Steam".to_string(),
}
})?;
let steam_path: String =
steam
.get_value("SteamPath")
.map_err(|err| LibraryDiscoveryError::Io {
inner: err,
path: "registry HKEY_CURRENT_USER\\SOFTWARE\\Valve\\Steam\\SteamPath"
.to_string(),
})?;
debug!("steam install directory found at `{}`", steam_path);
Self::discover_from_steam_path(Path::new(&steam_path))
}
#[cfg(all(unix, not(target_os = "macos")))]
fn discover_impl() -> Result<Self, LibraryDiscoveryError> {
use home::home_dir;
let steam_path = home_dir()
.ok_or(LibraryDiscoveryError::NoHome)?
.join(".steam")
.join("root");
let steam_path = fs::read_link(&steam_path)
.map_err(|err| LibraryDiscoveryError::from_io(err, &steam_path))?;
Self::discover_from_steam_path(steam_path)
}
#[cfg(target_os = "macos")]
fn discover_impl() -> Result<Self, LibraryDiscoveryError> {
use home::home_dir;
let steam_path = home_dir()
.ok_or(LibraryDiscoveryError::NoHome)?
.join("Library")
.join("Application Support")
.join("Steam");
Self::discover_from_steam_path(steam_path)
}
fn discover_from_steam_path<P: AsRef<Path>>(
steam_path: P,
) -> Result<Self, LibraryDiscoveryError> {
let steam_path = steam_path.as_ref();
let libraryfolders_path = steam_path.join("steamapps").join("libraryfolders.vdf");
debug!(
"reading installed steam games from `{}`, file: `{}`",
steam_path.display(),
libraryfolders_path.display()
);
let mut libraries = vdf::escaped_from_str::<LibraryFoldersFile>(
&fs::read_to_string(&libraryfolders_path)
.map_err(|err| LibraryDiscoveryError::from_io(err, &libraryfolders_path))?,
)?
.library_folders
.0;
let mut normalized_paths = libraries
.paths
.iter()
.filter_map(|p| match p.canonicalize() {
Ok(p) => Some(p),
Err(err) => {
warn!(
"error reading steam library folder `{}`: {}",
p.display(),
err
);
None
}
});
let normalized_steam_path = steam_path
.canonicalize()
.map_err(|err| LibraryDiscoveryError::from_io(err, steam_path))?;
if !normalized_paths.contains(&normalized_steam_path) {
libraries.paths.push(steam_path.to_path_buf());
}
Ok(libraries)
}
/// Returns an iterator over apps in all libraries.
#[must_use]
pub fn apps(&self) -> Apps {
Apps {
paths: self.paths.iter(),
current_path: None,
}
}
}
/// Iterator over apps in libraries.
///
/// # Errors
///
/// The [`Result`] will be an [`Err`] if a library directory read fails,
/// an appmanifest can't be read or the appmanifest deserialization fails.
#[derive(Debug)]
pub struct Apps<'a> {
paths: Iter<'a, PathBuf>,
current_path: Option<(PathBuf, fs::ReadDir)>,
}
impl<'a> Apps<'a> {
/// Filter the iterator to only return Source apps based on a bundled set of Source app ids.
#[must_use]
pub fn source(self) -> SourceApps<'a> {
SourceApps {
apps: self,
source_app_ids: SOURCE_APPS.into(),
}
}
/// Filter the iterator to only return Source apps based on a custom set of Source app ids.
#[must_use]
pub fn defined_source(self, source_app_ids: BTreeSet<u32>) -> SourceApps<'a> {
SourceApps {
apps: self,
source_app_ids,
}
}
}
impl<'a> Iterator for Apps<'a> {
type Item = Result<App, AppError>;
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some((current_path, current_iter)) = &mut self.current_path {
for entry in current_iter {
let entry = match entry {
Ok(entry) => entry,
Err(err) => return Some(Err(AppError::from_io(err, current_path))),
};
if !entry.file_type().map_or(false, |t| t.is_file()) {
continue;
}
if let Some(filename) = entry.file_name().to_str() {
if !filename.starts_with("appmanifest_") || !is_acf_file(filename) {
continue;
}
let path = entry.path();
debug!("reading appmanifest `{}`", path.display());
return Some(
fs::read_to_string(&path)
.map_err(|err| AppError::from_io(err, &path))
.and_then(|s| {
vdf::from_str::<AppManifest>(&s)
.map_err(|err| AppError::from_vdf(err, &path))
})
.map(|m| m.app_state.into_app(¤t_path)),
);
}
}
}
let steamapps_path = self.paths.next()?.join("steamapps");
debug!("reading app manifests from `{}`", steamapps_path.display());
match fs::read_dir(&steamapps_path) {
Ok(iter) => {
self.current_path = Some((steamapps_path, iter));
}
Err(err) => return Some(Err(AppError::from_io(err, &steamapps_path))),
}
}
}
}
/// Iterator over Source apps in libraries.
/// Apps' ids are checked against a static set of known Source ids and filtered.
///
/// # Errors
///
/// The [`Result`] will be an [`Err`] if a library directory read fails,
/// an appmanifest can't be read or the appmanifest deserialization fails.
#[derive(Debug)]
pub struct SourceApps<'a> {
apps: Apps<'a>,
source_app_ids: BTreeSet<u32>,
}
impl<'a> Iterator for SourceApps<'a> {
type Item = Result<App, AppError>;
fn next(&mut self) -> Option<Self::Item> {
self.apps.find(|result| {
result.as_ref().map_or(true, |app| {
if self.source_app_ids.contains(&app.app_id) {
debug!("app id `{}` is a source app", app.app_id);
true
} else {
debug!("skipped app id `{}`: is not a source app", app.app_id);
false
}
})
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_app_manifest_deserialization() {
let app_state = vdf::from_str::<AppManifest>(
r#"
"AppState"
{
"appid" "440"
"Universe" "1"
"LauncherPath" "C:\\Program Files (x86)\\Steam\\steam.exe"
"name" "Team Fortress 2"
"StateFlags" "1542"
"installdir" "Team Fortress 2"
"LastUpdated" "1569517103"
"UpdateResult" "12"
"SizeOnDisk" "22950744170"
"buildid" "4226121"
"LastOwner" "0"
"BytesToDownload" "1612410080"
"BytesDownloaded" "0"
"BytesToStage" "11233613113"
"BytesStaged" "0"
"AutoUpdateBehavior" "0"
"AllowOtherDownloadsWhileRunning" "0"
"ScheduledAutoUpdate" "0"
"InstalledDepots"
{
"441"
{
"manifest" "7381680709773015636"
"size" "0"
}
"440"
{
"manifest" "1118032470228587934"
"size" "0"
}
"232251"
{
"manifest" "1678072318420789394"
"size" "0"
}
}
"SharedDepots"
{
"228990" "228980"
}
"UserConfig"
{
"language" "english"
"betakey" ""
}
}
"#,
)
.unwrap()
.app_state;
assert_eq!(
app_state,
AppState {
app_id: 440,
name: "Team Fortress 2".to_string(),
install_dir: "Team Fortress 2".into(),
}
);
}
#[test]
fn test_libraryfolders_deserialization() {
let libraryfolders = vdf::escaped_from_str::<LibraryFoldersFile>(
r#"
"libraryfolders"
{
"contentstatsid" "3393887322297456883"
"0"
{
"path" "C:\\Program Files (x86)\\Steam"
"label" ""
"contentid" "3393887322297456883"
"totalsize" "0"
"update_clean_bytes_tally" "476447588"
"time_last_update_corruption" "0"
"apps"
{
"211" "2173258931"
}
}
"1"
{
"path" "D:\\Games\\Steam"
"label" ""
"contentid" "2825139553531466896"
"totalsize" "1000068870144"
"update_clean_bytes_tally" "40799269"
"time_last_update_corruption" "0"
"apps"
{
"215" "2811981136"
}
}
}
"#,
)
.unwrap()
.library_folders;
assert_eq!(
libraryfolders,
LibraryFolders(Libraries {
paths: vec![
"C:\\Program Files (x86)\\Steam".into(),
"D:\\Games\\Steam".into(),
],
})
);
}
}