-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsteam_cli.py
executable file
·789 lines (640 loc) · 24.6 KB
/
steam_cli.py
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
#!/usr/bin/env python3
"""
Usage:
steam-cli login [options]
steam-cli install [options] (--id=<id>|--name=<name>)
steam-cli execute [options] (--id=<id>|--name=<name>)
steam-cli show [options] (--id=<id>|--name=<name>)
steam-cli list [options] [--installed] [--disk-usage]
steam-cli download-covers [options]
steam-cli update-cache [options]
steam-cli categories [options]
steam-cli set-categories [options]
Commands:
login [auth-token] Login to steam (without auth-token to trigger the email)
install Download and install game
execute Execute installed game
show Show game details
list List all available games
download-covers Download game cover images
update-cache Update cached game list
categories List all game categories
set-categories Create or update game categories (all / proton ratings)
-i, --id=<id> Appid of the game
-n, --name=<name> Name of the game
--installed Only list installed games
--disk-usage Print disk usage for each game
Options:
-p, --platform=<p> Platform to install
-b, --bitness=<b> Bitness of the platform
-l, --language=<l> Language of the game to install
-g, --games-dir=<g> Directory where to find installed games [default: ~/]
-s, --steam-dir=<s> Directory where to find steam [default: ~/.steam]
-i, --install-dir=<g> Directory where to install game
--debug Run in debug mode (mostly set -x)
--gui <gui> Choose the GUI to use for progress indication from the
list of supported GUIs: none, text, curses, system
"""
import os
import re
import sys
import json
import getpass
import shutil
import subprocess
import contextlib
import datetime
import asyncio
import tempfile
import docopt
import dateutil.parser
import requests
import pexpect
import xdg
import vdf
STEAM_DIR = os.path.expandvars("$HOME/.steam")
CACHE_DIR = os.path.join(xdg.XDG_CACHE_HOME, "steam-cli")
if not os.path.exists(CACHE_DIR):
os.makedirs(CACHE_DIR)
@contextlib.contextmanager
def progress(ui):
_txt = '...'
_pct = 0
_cmd = None
def message(fmt, pct, txt):
nonlocal _txt
nonlocal _pct
if txt:
_txt = txt
if pct is None:
_pct = 100
elif pct >= 0:
_pct = min(pct, 99)
else:
_pct += -pct
bar = '#' * int(_pct / 2) + ' ' * int(50 - (_pct + 1) / 2)
return fmt.format(pct=int(_pct), txt=_txt, bar=bar)
try:
if ui == 'text':
yield (lambda pct, txt=None:
print(message('\u001b[2K[{bar}] {txt}...', pct, txt),
end='\r'))
elif ui == 'curses':
def cmd():
nonlocal _cmd
if not _cmd:
_cmd = subprocess.Popen(['whiptail', '--gauge', '', '6', '80', '0'],
bufsize=0, stdin=subprocess.PIPE, text=True)
return _cmd
yield (lambda pct, txt=None:
print(message('XXX\n{pct}\n{txt}...\nXXX', pct, txt),
file=cmd().stdin))
elif ui == 'system':
def cmd():
nonlocal _cmd
if not _cmd:
_cmd = subprocess.Popen(['zenity', '--width', '320', '--progress',
'--text', '', '--auto-kill', '--auto-close',
'--no-cancel', '--time-remaining'],
bufsize=0, stdin=subprocess.PIPE, text=True)
return _cmd
yield (lambda pct, txt=None:
print(message('# {txt}...\n{pct}', pct, txt), file=cmd().stdin))
else:
yield (lambda pct, txt=None:
print(message('{txt}... {pct}%', pct, txt), file=sys.stderr))
finally:
pass
if _cmd:
_cmd.stdin.close()
_cmd.wait()
def trydecode(bytes, encodings=['utf-8', 'iso-8859-1']):
for e in encodings[:-1]:
try:
return bytes.decode(e)
except:
continue
return bytes.decode(encodings[-1])
async def download(session, source, target):
if os.path.exists(target) or os.path.exists(target + '~'):
return
if not os.path.exists(os.path.dirname(target)):
os.makedirs(os.path.dirname(target))
async with session.get(source, allow_redirects=True) as r:
if 200 <= r.status < 300:
print(f'Downloading {source} to {target}')
open(target, 'wb').write(await r.read())
else:
print(f'Missing {source}')
open(target + '~', 'wb').write(bytes())
async def execute(cmd, *args, **kwargs):
print(f'Executing "{cmd}"')
proc = await asyncio.create_subprocess_shell(cmd, *args, **kwargs)
stdout, stderr = await proc.communicate()
return (proc.returncode,
stdout.decode('utf-8') if stdout else None,
stderr.decode('utf-8') if stderr else None)
def titlecase(txt):
return txt[0].upper() + txt[1:]
class GameNotFoundError(Exception):
pass
class SteamClient:
def __init__(self, progress=None, **kwargs):
self.logged_on = False
self._steam = None
self._pkgids = None
self._pkgs = None
self._appids = None
self._apps = None
self._cats = None
self.progress = progress
def load_cache(self):
if self._pkgs and self._pkgids and \
self._apps and self._appids:
return
pkgs_cache = os.path.join(CACHE_DIR, 'pkgs.json')
if os.path.exists(pkgs_cache):
with open(pkgs_cache, 'r') as f:
self._pkgs = dict(sorted([(int(k), v) for k,v in json.load(f).items()]))
self._pkgids = list(self._pkgs.keys())
apps_cache = os.path.join(CACHE_DIR, 'apps.json')
if os.path.exists(apps_cache):
with open(apps_cache, 'r') as f:
self._apps = dict(sorted([(int(k), v) for k,v in json.load(f).items()]))
self._appids = list(self._apps.keys())
def save_cache(self):
pkgs_cache = os.path.join(CACHE_DIR, 'pkgs.json')
if self._pkgs:
with open(pkgs_cache, 'w') as f:
json.dump(self._pkgs, f)
apps_cache = os.path.join(CACHE_DIR, 'apps.json')
if self._apps:
with open(apps_cache, 'w') as f:
json.dump(self._apps, f)
def update_cache(self):
shutil.rmtree(CACHE_DIR)
os.makedirs(CACHE_DIR)
self._pkgs = None
self._pkgids = None
self._apps = None
self._appids = None
self.pkgs
self.apps
def close_progress(self):
self.progress(None)
def expect(self, patterns, callbacks):
compiled = self.steam.compile_pattern_list([*patterns,
'\x1b\[1m\r\nSteam>\x1b\[0m'])
i = self.steam.expect_list(compiled)
while i < len(patterns):
callbacks[i](*self.steam.match.groups())
i = self.steam.expect_list(compiled)
def steam_file(self, path):
file = os.path.join(STEAM_DIR, 'steam', path)
if os.path.exists(file):
return file
file = os.path.join(STEAM_DIR, 'root', path)
if os.path.exists(file):
return file
file = os.path.join(STEAM_DIR, 'debian-installation', path)
if os.path.exists(file):
return file
os.path.join(STEAM_DIR, path)
@property
def steam(self):
if not self._steam:
self._steam = pexpect.spawn('steamcmd +@ShutdownOnFailedCommand 0',
echo=False)
self.expect([r'\[([^\]]+)\] (Checking for available update|Downloading [Uu]pdate|Download complete)[^\n]+\r\n'],
[lambda pct, txt: self.progress(int('0' + trydecode(pct).strip(' %-')), 'Updating')])
return self._steam
def quit(self):
if self._steam:
self._steam.sendline('quit');
def on_login(self):
self.logged_on = True
def on_error(self, error):
print(error)
raise Exception()
def login(self):
while not self.logged_on:
cfg = self.steam_file('config/config.vdf')
if os.path.exists(cfg):
with open(cfg) as f:
username = list(vdf.parse(f)['InstallConfigStore']['Software']['Valve']['Steam']['Accounts'].keys())[0]
else:
username = input('Username: ')
self.steam.sendline(f'login {username}')
self.progress(0, 'Login')
self.expect([r'password:', r"Steam Guard code:", r'Two-factor code:',
r'Logged in OK\r\n',
r'FAILED login with result code ([^\n]+)\r\n',
r"Logging in user '.*' to Steam Public \.\.\.\r\n",
r"Waiting for user info\.\.\.OK\r\n"],
[lambda: self.steam.sendline(getpass.getpass('Password: ')),
lambda: self.steam.sendline(input('Email code: ')),
lambda: self.steam.sendline(input('Two-factor code: ')),
lambda: self.on_login(), lambda e: self.on_error(e),
lambda: self.progress(50), lambda: self.progress(90)])
def on_pkgid(self, i):
self._pkgids += [i]
@property
def pkgids(self):
self.load_cache()
if not self._pkgids:
self._pkgids = []
self.login()
self.steam.sendline('licenses_print')
self.expect([r'License packageID (\d+):\r\n'],
[lambda i: self.on_pkgid(int(i))])
self._pkgids = sorted(list(set(self._pkgids)))
self.save_cache()
return self._pkgids
def on_pkg(self, i, s):
with open(os.path.join(CACHE_DIR, f'pkg-{i}.vdf'), 'wb') as f:
f.write(s)
self._pkgs[i] = vdf.loads(trydecode(s))
self.progress(100 * len(self._pkgs) / len(self._pkgids))
@property
def pkgs(self):
self.load_cache()
if not self._pkgs:
self._pkgs = {}
self.login()
self.progress(0, 'Loading pkgs')
with tempfile.NamedTemporaryFile(mode='w+') as s:
for i in self.pkgids:
cache = os.path.join(CACHE_DIR, f'pkg-{i}.vdf')
if os.path.exists(cache):
self.on_pkg(i, open(cache, 'rb').read())
continue
print(f'package_info_print {i}', file=s)
s.flush()
self.steam.sendline(f'runscript "{s.name}"')
self.expect([r'"(\d+)"\r\n{\r\n((?:[^\n]*\r\n)*?)}\r\n'],
[lambda i, s: self.on_pkg(int(i), s)])
self._pkgs = dict(sorted(self._pkgs.items()))
self.save_cache()
return self._pkgs
@property
def appids(self):
self.load_cache()
if not self._appids:
self._appids = []
for p in self.pkgs.values():
self._appids += list([int(i) for i in p['appids'].values()])
self._appids = list(set(self._appids))
self.save_cache()
return self._appids
def on_app(self, i, s):
with open(os.path.join(CACHE_DIR, f'app-{i}.vdf'), 'wb') as f:
f.write(s)
self._apps[i] = vdf.loads(trydecode(s))
self.progress(100 * len(self._apps) / len(self._appids))
@property
def apps(self):
self.load_cache()
if not self._apps:
self._apps = {}
self.login()
self.progress(0, 'Loading apps')
with tempfile.NamedTemporaryFile(mode='w+') as s:
for i in self.appids:
cache = os.path.join(CACHE_DIR, f'app-{i}.vdf')
if os.path.exists(cache):
self.on_app(i, open(cache, 'rb').read())
continue
print(f'app_info_print {i}', file=s)
s.flush()
self.steam.sendline(f'runscript "{s.name}"')
self.expect([r'"(\d+)"\r\n{\r\n((?:[^\n]*\r\n)*?)}\r\n'],
[lambda i, s: self.on_app(int(i), s)])
self._apps = dict(sorted(self._apps.items()))
self.save_cache()
return self._apps
def apps_by_type(self, t):
for k,v in self.apps.items():
if not 'common' in v:
continue
if 'driverversion' in v['common']:
continue
if v['common']['type'].lower() == t:
yield k,v
@property
def tools(self):
return dict(self.apps_by_type('tool'))
@property
def configs(self):
return dict(self.apps_by_type('config'))
@property
def dlcs(self):
return dict(self.apps_by_type('dlc'))
@property
def applications(self):
return dict(self.apps_by_type('application'))
@property
def games(self):
return dict(self.apps_by_type('game'))
@property
def demos(self):
return dict(self.apps_by_type('demo'))
@property
def cats(self):
if not self._cats:
import plyvel
if os.path.exists(os.path.join(CACHE_DIR, 'leveldb')):
shutil.rmtree(os.path.join(CACHE_DIR, 'leveldb'))
shutil.copytree(self.steam_file('config/htmlcache/Local Storage/leveldb'),
os.path.join(CACHE_DIR, 'leveldb'))
db = plyvel.DB(os.path.join(CACHE_DIR, 'leveldb'))
keys = []
for k,v in db:
if not b'\x00\x01' in k:
continue
site, key = k.split(b'\x00\x01')
if site != b'_https://steamloopback.host':
continue
if b'-cloud-storage-namespace-' in key and not b'.modified' in key:
assert(v[0] == 1)
keys.append(k)
self._cats = dict((i,[]) for i in self.appids)
for k in keys:
v = []
for kk,vv in json.loads(db.get(k)[1:]):
if 'is_deleted' in vv and vv['is_deleted']:
print(f'deleted: {vv}')
pass
elif not 'value' in vv or not 'key' in vv:
print(f'unknown: {vv}')
pass
elif vv['key'] == 'collection-bootstrap-complete':
pass
else:
vvv = json.loads(vv['value'])
if not isinstance(vvv, dict) or not 'added' in vvv:
continue
for i in vvv['added']:
if i in self._cats:
self._cats[i] += [vvv['name'].title()]
else:
print('{}: unknown app:{}'.format(vvv['name'], i))
return self._cats
async def _download_covers(self, s, i, k, v, sem, pct):
SOURCE = 'https://steamcdn-a.akamaihd.net/steam{}/apps/{}/{}.{}'
TARGET = os.path.join(CACHE_DIR, '{}/{}.{}')
await download(s, SOURCE.format('', k, 'library_600x900_2x', 'jpg'),
TARGET.format('covers/600x900', k, 'jpg'))
await download(s, SOURCE.format('', k, 'library_600x900', 'jpg'),
TARGET.format('covers/300x450', k, 'jpg'))
await download(s, SOURCE.format('', k, 'header', 'jpg'),
TARGET.format('headers', k, 'jpg'))
await download(s, SOURCE.format('', k, 'logo', 'png'),
TARGET.format('logos/640x360', k, 'png'))
if 'logo' in v['common']:
n = v['common']['logo']
await download(s, SOURCE.format('community/public/images', k, n, 'jpg'),
TARGET.format('logos/184x69', k, 'jpg'))
if 'logo_small' in v['common']:
n = v['common']['logo_small']
await download(s, SOURCE.format('community/public/images', k, n, 'jpg'),
TARGET.format('logos/120x45', k, 'jpg'))
if 'clienticon' in v['common']:
ico = TARGET.format('icons', k, 'ico')
png = TARGET.format('icons', k, 'png')
n = v['common']['clienticon']
await download(s, SOURCE.format('community/public/images', k, n, 'ico'),
ico)
async with sem:
if 'clienticon' in v['common']:
if os.path.exists(ico) and not os.path.exists(png):
_, n, _ = await execute("identify -quiet -format '%p %h %w %z %k\\n' "
"'{}' | sort -n -r -k2 -k3 -k4 -k5 | head -n1 "
"| awk '{{print $1}}'".format(ico),
stdout=subprocess.PIPE)
await execute('convert {} \\( -clone {} \\) -delete 0--2 {}'
.format(ico, n.strip(), png))
self.progress(-pct)
async def download_covers(self):
import aiohttp
self.progress(0, 'Downloading')
connector = aiohttp.TCPConnector(limit=16)
sem = asyncio.Semaphore(16)
pct = 100. / len(self.games)
async with aiohttp.ClientSession(connector=connector) as s:
await asyncio.gather(*(self._download_covers(s, i, k, v, sem, pct)
for i,(k,v) in enumerate(self.games.items())))
async def _download_protondb(self, s, i, k, v, pct):
SOURCE = 'https://www.protondb.com/api/v1/reports/summaries/{}.json'
TARGET = os.path.join(CACHE_DIR, 'protondb/{}.json')
await download(s, SOURCE.format(k), TARGET.format(k))
async def download_protondb(self):
import aiohttp
connector = aiohttp.TCPConnector(limit=16)
pct = 100. / len(self.games)
async with aiohttp.ClientSession(connector=connector) as s:
await asyncio.gather(*(self._download_protondb(s, i, k, v, pct)
for i,(k,v) in enumerate(self.games.items())))
ratings = {}
for i,(k,v) in enumerate(self.games.items()):
file = os.path.join(CACHE_DIR, f'protondb/{k}.json')
if not os.path.exists(file):
continue
with open(file, 'r') as f:
ratings[k] = json.load(f)
return ratings
def id(self, **kwargs):
if kwargs.get('id', None) and kwargs['id'] in self.apps:
return int(kwargs['id'])
elif kwargs.get('name', None):
for a in self.apps.values():
if not 'common' in a: continue
if not 'gameid' in a['common']: continue
if not 'name' in a['common']: continue
if kwargs['name'] == a['common']['name']:
return int(a['common']['gameid'])
raise GameNotFoundError
def list(self, **kwargs):
for a in sorted(self.games.values(), key=lambda g: g['common']['name']):
kwargs['id'] = int(a['common']['gameid'])
install_dir = self.install_dir(**kwargs)
if not kwargs['installed'] or os.path.exists(install_dir):
if kwargs['disk_usage'] and os.path.exists(install_dir):
print(subprocess.check_output(['du','-sh', install_dir]).split()[0].decode('utf-8'), end='\t')
else:
print(' ', end='\t')
print(a['common']['name'])
def show(self, **kwargs):
kwargs['id'] = self.id(**kwargs)
print(json.dumps(self.apps[kwargs['id']], indent=2))
def install_dir(self, **kwargs):
if kwargs.get('install_dir', None):
d = kwargs['install_dir']
else:
d = self.apps[kwargs['id']]['config']['installdir']
d = os.path.join(os.path.expanduser(kwargs['games_dir']), d)
d = os.path.expandvars(d)
return d
def install(self, **kwargs):
self.login()
kwargs['id'] = self.id(**kwargs)
kwargs['install_dir'] = self.install_dir(**kwargs)
with tempfile.NamedTemporaryFile(mode='w+') as s:
script = 'force_install_dir \"{install_dir}\"\n'
if kwargs.get('platform', None):
script += '@sSteamCmdForcePlatformType "{platform}"\n'
if kwargs.get('bitness', None):
script += '@sSteamCmdForcePlatformBitness "{bitness}"\n'
if kwargs.get('language', None):
script += 'app_update "{id}" -validate -language "{language}"\n'
else:
script += 'app_update "{id}" -validate\n'
print(script.format(**kwargs), file=s)
s.flush()
self.steam.sendline(f'runscript "{s.name}"')
self.expect([r'Update state .* (reconfiguring|downloading|validating), progress: ([\d]+).*\r\n',
r"Success! App '{id}' fully installed\.\r\n".format(**kwargs)],
[lambda txt, pct: self.progress(int(pct), titlecase(trydecode(txt))),
lambda: self.progress(100)])
def command(self, **kwargs):
kwargs['id'] = self.id(**kwargs)
kwargs['install_dir'] = self.install_dir(**kwargs)
if not os.path.exists(kwargs['install_dir']):
self.install(**kwargs)
app = self.apps[kwargs['id']]
print(app['config']['launch'])
for v in app['config']['launch'].values():
exe = os.path.join(kwargs['install_dir'], v['executable'])
if os.path.exists(exe):
return exe, v
def execute(self, **kwargs):
cmd, config = self.command(**kwargs)
self.close_progress()
print(cmd, config)
if 'linux' in config['config']['oslist']:
subprocess.run([cmd])
elif 'windows' in config['config']['oslist']:
subprocess.run(['wine', cmd])
def categories(self):
for k,v in sorted(self.games.items(), key=lambda p: p[1]['common']['name']):
print(v['common']['name'])
for c in self.cats[k]:
print(' ', c)
def set_categories(self):
import plyvel
db = plyvel.DB(self.steam_file('config/htmlcache/Local Storage/leveldb'))
pdb = asyncio.run(self.download_protondb())
keys = []
for k,v in db:
if not b'\x00\x01' in k:
continue
site, key = k.split(b'\x00\x01')
if site != b'_https://steamloopback.host':
continue
if b'-cloud-storage-namespace-' in key and not b'.modified' in key:
assert(v[0] == 1)
keys.append(k)
for k in keys:
cats = {}
for key, cat in json.loads(db.get(k)[1:]):
if not 'value' in cat or not 'key' in cat:
cats[key] = cat
elif cat['key'] == 'collection-bootstrap-complete':
cats[key] = cat
else:
val = json.loads(cat['value'])
if not isinstance(val, dict) or not 'added' in val:
cats[key] = cat
continue
name = val['name'] = val['name'].title()
id = val['id'] = f'from-tag-{name}'
key = cat['key'] = f'user-collections.{id}'
cats[key] = cat
def add_category(name):
id = f'from-tag-{name.title()}'
key = f'user-collections.{id}'
if key in cats: return
val = {'id': id, 'name': name.title(), 'added': [], 'removed': []}
cat = {'key': key, 'timestamp': 1584215160,
'conflictResolutionMethod': 'last-write',
'value': json.dumps(val, separators=(',',':'))}
cats[key] = cat
print(f'creating {name} category')
add_category('All')
add_category('Proton Unrated')
add_category('Proton Borked')
add_category('Proton Bronze')
add_category('Proton Silver')
add_category('Proton Gold')
add_category('Proton Platinum')
for key, cat in cats.items():
if 'is_deleted' in cat and cat['is_deleted']:
continue
elif not 'value' in cat or not 'key' in cat:
continue
elif cat['key'] == 'collection-bootstrap-complete':
continue
else:
val = json.loads(cat['value'])
if not isinstance(val, dict) or not 'added' in val:
continue
if 'All' == val['name']:
val['added'] = [i for i in self.games.keys()]
cat['value'] = json.dumps(val, separators=(',',':'))
elif 'Proton Unrated' == val['name']:
val['added'] = [i for i in self.games.keys() if i not in pdb]
cat['value'] = json.dumps(val, separators=(',',':'))
elif 'Proton Borked' == val['name']:
val['added'] = [i for i in self.games.keys()
if i in pdb and pdb[i]['tier'] == 'borked']
cat['value'] = json.dumps(val, separators=(',',':'))
elif 'Proton Bronze' == val['name']:
val['added'] = [i for i in self.games.keys()
if i in pdb and pdb[i]['tier'] == 'bronze']
cat['value'] = json.dumps(val, separators=(',',':'))
elif 'Proton Silver' == val['name']:
val['added'] = [i for i in self.games.keys()
if i in pdb and pdb[i]['tier'] == 'silver']
cat['value'] = json.dumps(val, separators=(',',':'))
elif 'Proton Gold' == val['name']:
val['added'] = [i for i in self.games.keys()
if i in pdb and pdb[i]['tier'] == 'gold']
cat['value'] = json.dumps(val, separators=(',',':'))
elif 'Proton Platinum' == val['name']:
val['added'] = [i for i in self.games.keys()
if i in pdb and pdb[i]['tier'] == 'platinum']
cat['value'] = json.dumps(val, separators=(',',':'))
cats[key] = cat
cats = json.dumps([[key, cat] for key, cat in cats.items()],
separators=(',',':'))
db.put(k, '\x01{}'.format(cats).encode('utf-8'), sync=True)
def main():
args = docopt.docopt(__doc__, version='steam-cli v1.0.0')
args = dict(((k if '--' not in k else k.strip('-').replace('-', '_'),v)
for k,v in args.items()))
STEAM_DIR = os.path.expanduser(args['steam_dir'])
GAMES_DIR = os.path.expanduser(args['games_dir'])
with progress(args['gui']) as p:
client = SteamClient(progress=p, **args)
if args['login']:
client.login()
elif args['list']:
client.list(**args)
elif args['show']:
client.show(**args)
elif args['install']:
client.install(**args)
elif args['execute']:
client.execute(**args)
elif args['download-covers']:
asyncio.run(client.download_covers())
elif args['update-cache']:
client.update_cache()
elif args['categories']:
client.categories()
elif args['set-categories']:
client.set_categories()
else:
print(args)
client.quit()
if __name__ == '__main__':
main()