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
|
#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2015 Alexandre Detiste <alexandre@detiste.be>
# SPDX-License-Identifier: GPL-2.0-or-later
from __future__ import annotations
import glob
import logging
import os
import tempfile
import xml.etree.ElementTree
import urllib.request
from collections.abc import (Iterator)
from typing import (TYPE_CHECKING)
from .build import (
BinaryExecutablesNotAllowed,
DownloadsFailed,
NoPackagesPossible,
)
from .packaging import (get_native_packaging_system)
from .util import (
AGENT,
ascii_safe,
lang_score,
rm_rf,
)
if TYPE_CHECKING:
import argparse
from .game import GameData
logger = logging.getLogger(__name__)
def parse_acf(path: str) -> Iterator[dict[str, str]]:
for manifest in glob.glob(path + '/*.acf'):
with open(manifest) as data:
# the .acf files are not really JSON files
level = 0
acf_struct = {}
for line in data.readlines():
if line.strip() == '{':
level += 1
elif line.strip() == '}':
level -= 1
elif level != 1:
continue
elif '"\t\t"' in line:
key, value = line.split('\t\t')
key = key.strip().strip('"')
value = value.strip().strip('"')
if key in ('appid', 'name', 'installdir'):
acf_struct[key] = value
if 'name' not in acf_struct:
acf_struct['name'] = acf_struct['installdir']
yield acf_struct
STEAM_GAMES: list[tuple[int, str]] | None = None
def owned_steam_games(
steam_id: str | None = None,
) -> list[tuple[int, str]]:
global STEAM_GAMES
if steam_id is None:
steam_id = get_steam_id()
if STEAM_GAMES is not None:
return STEAM_GAMES
STEAM_GAMES = []
if steam_id is None:
return []
url = "http://steamcommunity.com/profiles/" + steam_id + "/games?xml=1"
try:
html = urllib.request.urlopen(
urllib.request.Request(url, headers={'User-Agent': AGENT}),
)
tree = xml.etree.ElementTree.ElementTree()
tree.parse(html)
games_xml = tree.iter('game')
for game in games_xml:
el = game.find('appID')
assert el
assert el.text
appid = int(el.text)
el = game.find('name')
assert el
assert el.text
name = el.text
# print(appid, name)
STEAM_GAMES.append((appid, name))
except urllib.error.URLError:
# e="[Errno 111] Connection refused" but e.errno=None ?
pass
return STEAM_GAMES
def get_steam_vdf() -> str | None:
for p in ['~/.steam/debian-installation/config/loginusers.vdf',
'~/.steam/config/loginusers.vdf']:
path = os.path.expanduser(p)
if os.path.isfile(path):
return path
return None
def get_steam_id() -> str | None:
path = get_steam_vdf()
if path is None:
return None
with open(path, 'r', ) as data:
for line in data.readlines():
line = line.strip('\t\n "')
if line not in ('users', '{'):
return line
return None
def get_steam_account() -> str | None:
path = get_steam_vdf()
if path is None:
return None
with open(path, 'r', ) as data:
for line in data.readlines():
if 'AccountName' in line:
return line.split('"')[-2]
return None
class FoundPackage:
def __init__(
self,
game: str,
game_type: int,
package: str,
installed: bool,
longname: str,
paths: list[str],
) -> None:
self.game = game
self.game_type = type
self.package = package
self.installed = installed
self.longname = longname
self.paths = paths
def run_steam_meta_mode(
args: argparse.Namespace,
games: dict[str, GameData]
) -> None:
logger.info(
'Visit our community page: '
'https://steamcommunity.com/groups/debian_gdp#curation',
)
owned = set()
if args.download:
steam_id = get_steam_id()
if steam_id is None:
logger.error(
"Couldn't read SteamID from ~/.steam/config/loginusers.vdf"
)
else:
logger.info('Getting list of owned games from '
'http://steamcommunity.com/profiles/' + steam_id)
owned = set(g[0] for g in owned_steam_games(steam_id))
logging.info('Searching for locally installed Steam games...')
found_games = []
found_packages = []
tasks = {}
packaging = get_native_packaging_system()
for game, gamedata in games.items():
for package in gamedata.packages.values():
id = package.steam.get('id') or gamedata.steam.get('id')
if not id:
continue
if package.type == 'demo':
continue
# ignore other translations for "I Have No Mouth"
if lang_score(package.lang) == 0:
continue
installed = packaging.is_installed(package.name)
if args.new and installed:
continue
if game not in tasks:
tasks[game] = gamedata.construct_task(packaging=packaging)
paths = []
for path in tasks[game].iter_steam_paths((package,)):
if path not in paths:
paths.append(path)
if not paths and id not in owned:
continue
if game not in found_games:
found_games.append(game)
found_packages.append(FoundPackage(
game,
1 if package.type == 'full' else 2,
package.name,
installed,
package.longname or gamedata.longname,
paths
))
if not found_games:
logger.error('No Steam games found')
return
print('[x] = package is already installed')
print('-' * 70 + '\n')
found_packages = sorted(
found_packages,
key=lambda k: (k.game, k.game_type, k.longname),
)
for g in sorted(found_games):
print(g)
for p in found_packages:
if p.game != g:
continue
print(
'[%s] %-42s %s' % (
'x' if p.installed else ' ',
p.package,
ascii_safe(p.longname)
)
)
for path in p.paths:
print(path)
if not p.paths:
print('<game owned but not installed/found>')
print()
if not args.new and not args.all:
logger.info(
'Please specify --all or --new to create desired packages.'
)
return
preserve = (getattr(args, 'destination', None) is not None)
install = getattr(args, 'install', True)
if getattr(args, 'compress', None) is None:
# default to not compressing if we aren't going to install it
# anyway
args.compress = preserve
all_packages: set[str] = set()
for shortname in sorted(found_games):
task = tasks[shortname]
task.verbose = getattr(args, 'verbose', False)
task.save_downloads = args.save_downloads
try:
task.look_for_files(binary_executables=args.binary_executables)
except BinaryExecutablesNotAllowed:
continue
except NoPackagesPossible:
continue
todo = list()
for found_package in found_packages:
if found_package.game == shortname and found_package.paths:
todo.append(task.game.packages[found_package.package])
if not todo:
continue
try:
ready = task.prepare_packages(log_immediately=False,
packages=todo)
except NoPackagesPossible:
logger.error('No package possible for %s.' % task.game.shortname)
continue
except DownloadsFailed:
logger.error('Unable to complete any packages of %s'
' because downloads failed.' % task.game.shortname)
continue
if args.destination is None:
destination = workdir = tempfile.mkdtemp(prefix='gdptmp.')
else:
workdir = None
destination = args.destination
debs = task.build_packages(
ready,
compress=getattr(args, 'compress', True),
destination=destination,
download=getattr(args, 'download', True),
)
rm_rf(os.path.join(task.get_workdir(), 'tmp'))
if preserve:
for deb in debs:
print('generated "%s"' % os.path.abspath(deb))
all_packages = all_packages.union(debs)
if not all_packages:
logger.error('Unable to package any game.')
if workdir:
rm_rf(workdir)
raise SystemExit(1)
if install:
packaging.install_packages(
all_packages, args.install_method, args.gain_root_command,
)
if workdir:
rm_rf(workdir)
|