summaryrefslogtreecommitdiff
path: root/game/update.rpy
blob: 234516e026f2b0efa55ff868206c5f833b5ab2df (plain) (blame)
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
#################################################################################
#     This file is part of Mana Launcher.
#     Copyright (C) 2021  Jesusalva <jesusalva@tmw2.org>
#
#     Distributed under the MIT license, except for Steam parts.
#################################################################################

init python:
    def status_update(smsg="", pc=-1):
        global progress, statusmsg
        if pc > 0 and pc != progress:
            progress=min(pc, 100)
        if (smsg != ""):
            statusmsg=smsg
            stdout(smsg)

    def validate_server(srv):
        name="Unknown Server"; ok=False
        try:
            name=srv["Name"]
            stdout("Validating server \"%s\"..." % name)
            print("Host: %s" % srv["Host"])
            print("Port: %04d" % srv["Port"])
            print("Desc: %s" % srv["Desc"])
            print("Link: %s" % srv["Link"])
            print("News: %s" % srv["News"])
            print("Back: %s" % srv["Back"])
            print("UUID: %s" % srv["UUID"])
            print("Help: %s" % srv["Help"])
            print("Online List: %s" % srv["Online"])
            print("Policy: %s" % srv["Policy"])
            stdout("Server \"%s\" is valid! Downloading assets..." % name)
            ok=True
        except:
            traceback.print_exc()
            stdout("Validation for server \"%s\" FAILED!" % name)

        ## Fetch server background (optional) if successful
        """
        if (ok):
            bgname="bg_%s.png" % (name.replace(" ", ""))
            if os.path.exists(get_path(bgname)):
                return ok
            try:
                stdout("Fetching background for server \"%s\"" % bgname)
                r=requests.get(srv["Back"], timeout=10.0)
                with open(bgname, 'wb') as fd:
                    for chunk in r.iter_content(chunk_size=128):
                        fd.write(chunk)
            except:
                traceback.print_exc()
                stdout("Background error for server \"%s\"." % name)
        """

        return ok

    def update_serverlist(host):
        try:
            r=requests.get("%s/server_list.json" % host, timeout=10.0)

            if (r.status_code != 200):
                raise AssertionError("Mirror %s seems to be down!\nReturned error %03d\n" % (host.replace("https://", "").replace("http://", ""), r.status_code))

            j=json.loads(r.text)

            ## If we reached here, then everything is likely fine
            ## We can now build the persistent data
            status_update("Fetching server list and assets...", 20)
            persistent.serverlist = []
            slist=len(j)
            for server in j:
                if (validate_server(server)):
                    persistent.serverlist.append(server)
                status_update(pc=int(10+(70.0/slist)))

            ## If we were truly successful, save this host as our mirror
            persistent.host = host
            return True
        except:
            traceback.print_exc()
            return False

    #############################################################################
    def CONFIGURE_LAUNCHER():
        global progress, statusmsg, responsive, has_steam, vaultId, vaultToken
        statusmsg="Loading user configuration..."
        #########################################################################
        # If persistent data is not yet set, it must be created
        # This block is 1~60%
        # But first we check for updates
        if persistent.host is not None:
            stdout("Fetching data from %s" % persistent.host, True)
            retry=3
            while retry > 0:
                try:
                    retry-=1
                    rv=requests.get("%s/version.txt" % persistent.host, timeout=10.0)

                    if (rv.status_code != 200):
                        raise AssertionError("Mirror %s seems to be down!\nReturned error %03d" % (persistent.host.replace("https://", "").replace("http://", ""), rv.status_code))

                    # Everything went fine! Update server list if needed
                    if (persistent.version != rv.text):
                        if not update_serverlist(persistent.host):
                            raise Exception("Mirror serverlist error")
                        persistent.version=rv.text
                        stdout("Version updated to %s" % persistent.version, True)
                    retry=0
                except:
                    traceback.print_exc()
                    if retry < 1:
                        persistent.host=None
                        stdout("Too many failures, seeking a new mirror.")

        ## Either our original mirror died, or it was never a thing
        ## Maybe you're offline but in any case:
        ## Seek a new mirror and update server list accordingly.
        if persistent.host is None:
            status_update("Welcome to the Mana Launcher.\nBuilding user data, please wait...", 1)
            time.sleep(1.0)

            # Determine from where we should fetch updates
            for host in HOST_LIST:
                try:
                    if not update_serverlist(host):
                        raise Exception("Mirror serverlist error")
                    break
                except:
                    stdout("An error happened on mirror \"%s\"." % host.split("//")[1])
                    stdout("\nTrying next mirror...\n")

            ## If we don't have a host - DIE HARD
            if (persistent.host is None):
                stdout("No mirror could be found.", True)
                status_update("{color=#f00}{b}ERROR: No active mirror found.\nMana Launcher needs to be updated.{/b}{/color}")
                responsive=False
                return

            ## Everything was successful!


        #########################################################################
        # Check for clients, this block is 60~80%
        status_update("Checking for installed clients...", 60)

        r=handle_client()

        ## Oh sh--
        if not r:
            time.sleep(0.4)
            responsive = False
            time.sleep(2.6)
            status_update("{color=#F00}ERROR: \"%s\" client is NOT supported!{/color}" % persistent.client, 70)
            return


        status_update(pc=70)

        time.sleep(0.1)

        #########################################################################
        # Before starting, we must check for Vault or Steam credentials
        # This block is 1~20%
        status_update("Verifying credentials...", 80)
        try:
            if not persistent.steam:
                raise Exception("Steam login was disabled!")
            stdout("Steam Status: %s" % str(steam.initialized))
            if steam.init() != True:
                raise Exception("Steam is not running!")
            status_update("Attempting Steam authentication...", 81)
            accId = steam.get_account_id()
            stdout("Steam login active, user %d" % accId)

            ## Retrieve new ticket ("token"), send it in Base64 to the API
            token = steam.get_session_ticket()
            auth = {"accId": accId, "token": base64.b64encode(token)}
            time.sleep(1.0)
            status_update("Waiting for Vault reply...", 85)

            ## Request the Vault for the ticket validation
            r = vault.post(VAULT_HOST+"/steam_auth", json=auth, timeout=15.0)

            ## Ticket error, we die here.
            if (r.status_code == 406):
                status_update("{color=#f00}{b}STEAM AUTHENTICATION ERROR.\nSteam refused authentication. Try restarting the app.{/b}{/color}")
                responsive=False
                return

            ## Intercept rate-limiting (429) and retry once
            if (r.status_code == 429 or r.status_code == 500):
                status_update("Rate limited! Trying again 15s...", 85)
                time.sleep(5.0)
                status_update("Rate limited! Trying again 10s...", 85)
                time.sleep(5.0)
                status_update("Rate limited! Trying again 5s...", 85)
                time.sleep(5.0)
                status_update("Rate limited! Trying again...", 85)
                r = vault.post(VAULT_HOST+"/steam_auth", json=auth, timeout=15.0)

            ## If still unsucessful, give up on Steam Auth
            if (r.status_code != 200):
                raise Exception("Vault returned code %d" % r.status_code)

            ## Receive the Vault Token
            status_update("Waiting for Vault reply...", 90)
            stdout("Steam result: (%d) %s" % (r.status_code, ifte(config.developer, r.text, accId)))
            auth2 = r.json()
            vaultId = auth2["vaultId"]
            vaultToken = auth2["token"]

            # If everything went well, inform Steam support is ON
            # Enable all Steam features and skip Vault-only auth
            has_steam = True
            stdout("Steam session initialized successfully", True)
            status_update("Steam session initialized successfully", 99)
            time.sleep(0.1)
        except:
            # NO FALLBACK: if Steam Login is on, do not try vault (no multiacc)
            if persistent.steam:
                traceback.print_exc()
                status_update("{color=#f00}{b}STEAM AUTHENTICATION ERROR.\nIf the issue persists, try closing the app and opening again.{/b}{/color}")
                responsive=False
                return

            # Prepare to do Vault authentication
            status_update("Steam auth disabled, trying Vault...", 80)
            time.sleep(1.0)
            vaultId = 0
            vaultToken = "ERROR"
            #########################################
            ####### TODO FIXME
            # Must return and let a prompt for username & password
            # (Or Email, in the case of the modern Vault)
            # If vaultId is zero
            #status_update("{color=#F00}VaultError: Not yet implemented{/color}")
            #responsive = False
            #return
            ####### TODO FIXME
            #########################################


        status_update(pc=100)
        return


#################################################################################
screen register_method():
    ## Ensure other screens do not get input while this screen is displayed.
    modal True
    zorder 200
    style_prefix "confirm"
    add "gui/overlay/confirm.png"
    frame:
        vbox:
            xalign .5
            yalign .5
            spacing 30
            label _("{b}Vault Authentication{/b}\n\nWhich method do you want to use to login on TMW Vault?\n{size=14}An account will be automatically created if it does not exists already. This implies accepting the {a=%s}Terms of Service.{/a}{/size}" % ("https://tmw2.org/legal")):
                style "confirm_prompt"
                xalign 0.5

            hbox:
                xalign 0.5
                spacing 100
                textbutton _("Email Auth") action Return(1)
                textbutton _("Pass+2FA Auth") action Return(2)

screen register_input(prompt):
    ## Ensure other screens do not get input while this screen is displayed.
    modal True
    zorder 200
    style_prefix "confirm"
    add "gui/overlay/confirm.png"
    frame:
        vbox:
            xalign .5
            yalign .5
            spacing 30
            label _(prompt):
                style "confirm_prompt"
                xalign 0.5

            null height 24

            input:
                xalign 0.5
                id "input"
                copypaste True

screen notice(prompt):
    ## Ensure other screens do not get input while this screen is displayed.
    modal True
    zorder 200
    style_prefix "confirm"
    add "gui/overlay/confirm.png"
    frame:
        vbox:
            xalign .5
            yalign .5
            spacing 30
            label _(prompt):
                style "confirm_prompt"
                xalign 0.5
            hbox:
                xalign 0.5
                spacing 100
                textbutton _("OK") action Return()

label register:
    $ status_update(" ", 80)
    call screen register_method
    $ status_update(pc=85)
    $ method = _return
    $ email=""
    while email == "":
        call screen register_input("Please insert your {b}email{/b}.")
        $ email=_return
        if not "@" in email or not "." in email:
            call screen notice(_("Please make sure you enter a valid email!"))
            $ email=""

    $ status_update(pc=90)

    ##########################################
    ## What we'll do now depends on the method
    ## Email-Auth (the default)
    if method == 1:
        $ user = {"email": email,
                  "confirmed": True
                 }
        $ r = vault.put(VAULT_HOST+"/vault/session", json=user)

        # Wait for Vault to send you an email
        if (r.status_code != 200):
            call screen notice(_("Vault returned error %d\n\nPlease try again later." % r.status_code))
            return

        $ status_update(pc=92)
        call screen notice(_("An email was sent with your API token.\n\nYou'll need it shortly, so check your email."))

        $ status_update(pc=95)
        call screen register_input("Please insert the {b}token{/b} you received on your email.")
        $ token = _return
        $ user["key"] = token

        $ status_update(pc=97)
        #$ r = vault.get(VAULT_HOST+"/vault/session?token=%s&email=%s" % (token, email)) # FIXME: HTTP formating for email
        # FIXME: Continue from here
        call screen notice(_("{b}INTERNAL SERVER ERROR{/b}\n\nSeems like someone messed up on the APIs!\nThis login method seems to be temporaly unavailable, please choose another one."))
        # Cleanup
        $ del user
        $ del token

    ##########################################
    ## What we'll do now depends on the method
    ## 2FA-Auth
    elif method == 2:
        $ password = ""
        while len(password) < 4:
            call screen register_input("Please insert your {b}Password{/b}.\nIt has to be at least 4 characters long.")
            $ password = _return
            # We must send the password on plain-text; That's why we use SSL

        $ status_update(pc=92)
        call screen register_input("Please insert your {b}2FA code{/b}. If you do not have 2FA, leave blank.\n\n{u}TOTP setup will be emailed and required for later logins.{/u}")
        $ code2FA = _return

        $ status_update(pc=95)
        $ data = {"mail": email,
                  "pass": password,
                  "totp": code2FA[:6]
                 }
        $ r = vault.post(VAULT_HOST+"/user_auth", json=data)

        # Wait for Vault to confirm.
        if (r.status_code != 200):
            call screen notice(_("Vault returned error %d\n\nPlease try again later." % r.status_code))
            return

        # Check if we have success
        python:
          try:
            status_update(pc=98)
            stdout("Vault result: (%d) %s" % (r.status_code, ifte(config.developer, r.text, "OK")))
            auth2 = r.json()
            vaultId = auth2["vaultId"]
            vaultToken = auth2["token"]
          except:
            traceback.print_exc()
            stdout("Error - Vault result is bad.")

        $ del data
        $ del code2FA

    ############
    ## Cleanup
    $ del method
    $ del email
    if vaultId:
        $ status_update("Success!", 100)
    else:
        $ status_update("{color=#F00}Failure!{/color}", pc=100)
    return