-
Notifications
You must be signed in to change notification settings - Fork 23
/
auto.py
executable file
·270 lines (219 loc) · 9.8 KB
/
auto.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
#!/usr/bin/env python
#############################################################################
#
# Copyright (C) 2018 Fabian Schweinfurth
# Contact: autoshift <at> derfabbi.de
#
# This file is part of autoshift
#
# autoshift is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# autoshift is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with autoshift. If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from __future__ import print_function
import sys
from typing import Match, cast
from common import _L, DEBUG, DIRNAME, INFO
# from query import BL3
from query import Key, known_games, known_platforms
from shift import ShiftClient, Status
client: ShiftClient = None # type: ignore
LICENSE_TEXT = """\
========================================================================
autoshift Copyright (C) 2019 Fabian Schweinfurth
This program comes with ABSOLUTELY NO WARRANTY; for details see LICENSE.
This is free software, and you are welcome to redistribute it
under certain conditions; see LICENSE for details.
========================================================================
"""
def redeem(key: Key):
import query
"""Redeem key and set as redeemed if successfull"""
_L.info(f"Trying to redeem {key.reward} ({key.code})")
status = client.redeem(key.code, known_games[key.game], key.platform)
_L.debug(f"Status: {status}")
# set redeemed status
if status in (Status.SUCCESS, Status.REDEEMED,
Status.EXPIRED, Status.INVALID):
query.db.set_redeemed(key)
# notify user
try:
# this may fail if there are other `{<something>}` in the string..
_L.info(" " + status.msg.format(**locals()))
except:
_L.info(" " + status.msg)
return status == Status.SUCCESS
def query_keys(games: list[str], platforms: list[str]):
"""Query new keys for given games and platforms
Returns dict of dicts of lists with [game][platform] as keys"""
from itertools import groupby
import query
all_keys: dict[str, dict[str, list[Key]]] = {}
keys = list(query.db.get_keys(None, None))
# parse all keys
query.update_keys()
new_keys = list(query.db.get_keys(None, None))
diff = len(new_keys) - len(keys)
_L.info(f"done. ({diff if diff else 'no'} new Keys)")
_g = lambda key: key.game
_p = lambda key: key.platform
for g, g_keys in groupby(sorted(new_keys, key=_g), _g):
if g not in games:
continue
all_keys[g] = {p: [] for p in platforms}
for platform, p_keys in groupby(sorted(g_keys, key=_p), _p):
if platform not in platforms and platform != "universal":
continue
_ps = [platform]
if platform == "universal":
_ps = platforms.copy()
for p in _ps:
all_keys[g][p].extend(key.copy().set(platform=p) for key in p_keys)
# all_keys[g][p] = list(p_keys)
for p in platforms:
# count the new keys
n_golden = sum(int(cast(Match[str], m).group(1) or 1)
for m in
filter(lambda m:
m and m.group(1) is not None,
map(lambda key: query.r_golden_keys.match(key.reward),
all_keys[g][p])))
_L.info(f"You have {n_golden} golden {g.upper()} keys to redeem for {p.upper()}")
return all_keys
def setup_argparser():
import argparse
import textwrap
games = list(known_games.keys())
platforms = list(known_platforms.without("universal").keys())
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-u", "--user",
default=None,
help=("User login you want to use "
"(optional. You will be prompted to enter your "
" credentials if you didn't specify them here)"))
parser.add_argument("-p", "--pass",
help=("Password for your login. "
"(optional. You will be prompted to enter your "
" credentials if you didn't specify them here)"))
parser.add_argument("--golden",
action="store_true",
help="Only redeem golden keys")
parser.add_argument("--non-golden", dest="non_golden",
action="store_true",
help="Only redeem non-golden keys")
parser.add_argument("--games",
type=str, required=True,
choices=games, nargs="+",
help=("Games you want to query SHiFT keys for"))
parser.add_argument("--platforms",
type=str, required=True,
choices=platforms, nargs="+",
help=("Platforms you want to query SHiFT keys for"))
parser.add_argument("--limit",
type=int, default=200,
help=textwrap.dedent("""\
Max number of golden Keys you want to redeem.
(default 200)
NOTE: You can only have 255 keys at any given time!""")) # noqa
parser.add_argument("--schedule",
type=float, const=2, nargs="?",
help="Keep checking for keys and redeeming every hour")
parser.add_argument("-v", dest="verbose",
action="store_true",
help="Verbose mode")
return parser
def main(args):
global client
from time import sleep
import query
from query import db, r_golden_keys
with db:
if not client:
client = ShiftClient(args.user, args.pw)
# query all keys
all_keys = query_keys(args.games, args.platforms)
# redeem 0 golden keys but only golden??... duh
if not args.limit and args.golden:
_L.info("Not redeeming anything ...")
return
_L.info("Trying to redeem now.")
# now redeem
for game in all_keys.keys():
for platform in all_keys[game].keys():
t_keys = list(filter(lambda key: not key.redeemed, all_keys[game][platform]))
for num, key in enumerate(t_keys):
if (num and not (num % 15)) or client.last_status == Status.SLOWDOWN:
if client.last_status == Status.SLOWDOWN:
_L.info("Slowing down a bit..")
else:
_L.info("Trying to prevent a 'too many requests'-block.")
sleep(60)
_L.info(f"Key #{num+1}/{len(t_keys)}")
num_g_keys = 0 # number of golden keys in this code
m = r_golden_keys.match(key.reward)
# skip keys we don't want
if ((args.golden and not m) or (args.non_golden and m)):
continue
if m:
num_g_keys = int(m.group(1) or 1)
# skip golden keys if we reached the limit
if args.limit <= 0:
continue
# skip if this code has too many golden keys
if (args.limit - num_g_keys) < 0:
continue
redeemed = redeem(key)
if redeemed:
args.limit -= num_g_keys
_L.info(f"Redeeming another {args.limit} Keys")
else:
# don't spam if we reached the hourly limit
if client.last_status == Status.TRYLATER:
return
_L.info("No more keys left!")
if __name__ == "__main__":
import os
# only print license text on first use
if not os.path.exists(os.path.join(DIRNAME, "data", ".cookies.save")):
print(LICENSE_TEXT)
# build argument parser
parser = setup_argparser()
args = parser.parse_args()
args.pw = getattr(args, "pass")
_L.setLevel(INFO)
if args.verbose:
_L.setLevel(DEBUG)
_L.debug("Debug mode on")
if args.schedule and args.schedule < 2:
_L.warn(f"Running this tool every {args.schedule} hours would result in "
"too many requests.\n"
"Scheduling changed to run every 2 hours!")
# always execute at least once
main(args)
# scheduling will start after first trigger (so in an hour..)
if args.schedule:
hours = int(args.schedule)
minutes = int((args.schedule-hours)*60+1e-5)
_L.info(f"Scheduling to run every {hours:02}:{minutes:02} hours")
from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler()
# fire every 1h5m (to prevent being blocked by the shift platform.)
# (5min safe margin because it somtimes fires a few seconds too early)
scheduler.add_job(main, "interval", args=(args,), hours=args.schedule)
print(f"Press Ctrl+{'Break' if os.name == 'nt' else 'C'} to exit")
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass
_L.info("Goodbye.")