summaryrefslogtreecommitdiff
path: root/__main__.py
blob: fefce51e10ea8b9367f83e60375ff17b343e7fa8 (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
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
#!/usr/bin/python3
#####################################
## This is the Tkinter version
## It is mostly a TMW Vault Wrapper
##
## For lore, you need to use the app
#####################################
## (C) The Mana World Team, 2021-2024
## Published under the MIT License
#####################################

import requests, json, traceback, subprocess, sys, time, os, uuid, base64
#import threading #hmac, struct # < - TODO: Necessary for TOTP-remember support
import tkinter as tk
from tkinter.messagebox import showinfo, showerror, askyesno
from functools import partial

OBFS = uuid.getnode() % 256 # Get a number which *usually* doesn't change
OBFS = 185 # <- For debugging (FIXME ^ above didn't held up in practice)
print("Obfuscation key = %d" % OBFS) # <- Just to not leave it in plain text

## Internal wrapper for preferences
saveSettings = True; newUser = False
def _savePref():
    global saveSettings, pref
    if not saveSettings:
        return
    dump = json.dumps(pref)
    dump = bytearray(ord(x) ^ int(OBFS) for x in dump)
    dump = base64.b64encode(dump)
    dump = dump.decode('ascii')
    with open("settings.b64", 'w') as raw:
        raw.write(str(dump))
    #print("Preferences updated...")
    return

## Try to load previously saved settings
try:
    with open("settings.b64") as raw:
        pref = base64.b64decode(raw.read())
        ## XXX: use ord() if int(x) fails
        pref = bytearray(int(x) ^ int(OBFS) for x in pref)
        pref = pref.decode('utf8')
        print(repr(pref))
        pref = json.loads(str(pref))
        print("User settings loaded...")
except:
    print("Failed to load user settings!")
    err = traceback.format_exc().split("\n")[-2]
    print("Error: %s" % err)
    ## Create new dummy prefs so it doesn't crash
    pref = {"user": "",    # <- User Email
            "pass": "",    # <- User Password
            "totp": "",    # <- NYI
            "mana": False, # <- Prefer Mana over ManaVerse
            "plus": False, # <- Prefer ManaPlus over ManaVerse
            "local": True, # <- system-wide vs manaplus/ folder
            "shell": True, # <- output to console
            "discord": None} # <- Whenever to use Discord RPC or not
    ## If it is an error, give an option to not destroy the old settings
    if ("FileNotFoundError" in err):
        _savePref()
        print("New user settings created!")
        newUser = True
    elif (askyesno("Mana Launcher", "Failed to load user settings!\n\nDo you want to create a new one?")):
        _savePref()
        print("New user settings created!")
    else:
        saveSettings = False

## Load the introduction screens if they exist
try:
    from _info import worldGreet
except ImportError:
    worldGreet={}

## Auto-detect if Discord should be used
## Don't crash only if a new FLOSS purist will immediately deleted discordrpc
if pref["discord"] in [True, None]:
    try:
        import discordrpc
    except ImportError:
        if pref["discord"] == None:
            pref["discord"] = False
        else:
            raise

## Value may have changed
if pref["discord"]:
    try:
        _rpc = discordrpc.RPC.set_id(app_id=840427221193195541)
        _rpc.set_activity(
                        state="The Mana World - Minimal",
                        details="Main Menu",
                        large_image="launcher",
                        large_text="Mana Launcher",
                        timestamp=_rpc.timestamp
                        )
    except discordrpc.exceptions.DiscordNotOpened:
        err = traceback.format_exc().split("\n")[-2]
        _rpc = None
        print("Failed to load Discord RPC!\n%s" % err)

## Value may have changed
if not pref["discord"]:
    _rpc = None

## This is how we'll actually update Discord stuff
def RPCUpdate(status, image):
    global _rpc, pref
    if not pref["discord"] or _rpc is None:
        return
    _rpc.set_activity(
                    state="The Mana World - Minimal",
                    details=status,
                    large_image=image,
                    large_text="Mana Launcher",
                    timestamp=_rpc.timestamp
                    )
    return

## Prepare some basic stuff
execute=subprocess.call
serverlist = []
class HoverButton(tk.Button):
    def enter(self, e):
        self["background"] = self["activebackground"]
    def exit(self, e):
        self["background"] = self.defaultBackground

    def __init__(self, **kw):
        tk.Button.__init__(self, **kw)
        self.defaultBackground = self["background"]
        self.bind("<Enter>", self.enter)
        self.bind("<Leave>", self.exit)

## TODO: Get from `sys` args parameters like world auto-selection

#####################################
#VAULT_HOST = "https://localhost:13370"
#SERVERLIST = "http://localhost/launcher"
VAULT_HOST = "https://api.themanaworld.org:13370"
SERVERLIST = "https://updates.tmw2.org/launcher"
# Vault SSL wrapper
vault=requests.Session()
if "localhost" in VAULT_HOST:
    vault.verify=False
#####################################

## Just print stuff to console, bold or not
def stdout(message, bd=False):
    if bd:
        print("\033[1m%s\033[0m" % message)
    else:
        print(message)

## Smart Delay
def sdelay(delta=0.02):
    time.sleep(delta)
    return

## IF Then Else (IFTE)
def ifte(ifs, then, elses):
    if (ifs):
        return then
    else:
        return elses

# Sanitize a command (strip some flow control chars)
# While it covers all control operators and most metacharacters,
# it doesn't covers well the reserved words.
# ...Of course, it relies on this client not being compromised.
def san(cmd):
    return cmd.replace(";", "").replace("|", "").replace(">", "").replace("<", "").replace("&", "").replace("(", "").replace(")", "").replace("\n", "").replace("[[", "").replace("]]", "")

## Returns number of seconds since UNIX EPOCH
def now():
    return int(time.time())

## Update preferences (only after release)
#if not "local" in list(pref.keys()):
#    pref["local"] = True

## Does nothing, validation purposes only
def nullp(arg):
    return

# Search for array[?][key]==search in an array of dicts
# Returns the index, or returns -1
def dl_search_idx(array, key, search):
    try:
        r=next((i for i, item in enumerate(array) if item[key] == search), None)
    except:
        traceback.print_exc()
        r=-1
    return ifte(r is None, -1, r)

## Validates a server entry
def validate_server(srv):
    name="Unknown Server"; ok=False
    try:
        name=srv["Name"]
        #stdout("Validating server \"%s\"..." % name)
        nullp("Host: %s" % srv["Host"])
        nullp("Port: %04d" % srv["Port"])
        nullp("Desc: %s" % srv["Desc"])
        nullp("Link: %s" % srv["Link"])
        nullp("News: %s" % srv["News"])
        nullp("Back: %s" % srv["Back"])
        nullp("UUID: %s" % srv["UUID"])
        nullp("Help: %s" % srv["Help"])
        nullp("Online List: %s" % srv["Online"])
        nullp("Policy: %s" % srv["Policy"])
        if not "Type" in srv.keys():
            srv["Type"]="evol2"
        stdout("Server \"%s\" loaded." % name)
        ok=True
    except:
        traceback.print_exc()
        stdout("Validation for server \"%s\" FAILED!" % name)

    return ok

## Update server list
def update_serverlist(hosti):
    global serverlist, host
    try:
        r=requests.get("%s/server_list.json" % hosti, timeout=10.0)
        if (r.status_code != 200):
            raise AssertionError("Mirror %s seems to be down!\nReturned error %03d\n" % (hosti.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
        print("Fetching server list and assets... %d servers" % len(j))
        for server in j:
            if (validate_server(server)):
                serverlist.append(server)

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

## Show a game info
def info_game(idx):
    showinfo(title=serverlist[idx]["Name"],
             message=serverlist[idx]["Desc"])
    return

## Launch a specific world with its appropriate client
def launch_game(idx):
    PWD=""
    ## Get credentials
    auth = {"vaultId": vaultId,
            "token": vaultToken,
            "world": serverlist[idx]["UUID"]}

    try:
        r=vault.post(VAULT_HOST+"/world_pass", json=auth, timeout=15.0)
        ## We got the access credentials
        if r.status_code == 200:
            auth2=r.json()
            PWD=" -U %s -P %s" % (auth2["user"], auth2["pass"])
        ## We were refused by Vault
        elif r.status_code == 403:
            stdout("Warning: Connection was refused (Vault logout?)")
            return -1
        ## We are rate-limited, try again
        elif r.status_code == 429:
            stdout("Rate limited!")
            return -1
        ## Internal error, maybe?
        else:
            stdout("Get World Auth - Returned error code %d" % r.status_code)
            return -1
    except:
        traceback.print_exc()
        return -1

    ## First login special greeting
    ## This is full of hacks, though
    if auth2["new"]:
        return (idx, PWD)
    return do_real_launch(idx, PWD)

def do_real_launch(idx, PWD):
    global pref
    ## Get/Set basic data
    HOST=serverlist[idx]["Host"]
    PORT=serverlist[idx]["Port"]
    CMD=""
    OPT=""

    ## Using system-wide versus local path
    if pref["local"]:
        CMD=os.getcwd()+"/manaplus/"
        CMD=CMD.replace(" ", "\\ ")
        CWD=CMD[:-1]

    ## TODO: Handle server type and client
    if not sys.platform.startswith('win'):
        if pref["plus"]:
            CMD+="manaplus"
        elif pref["mana"] and "tmwa" in serverlist[idx]["Type"]:
            CMD+="mana"
        else:
            CMD+="ManaVerse"
        if pref["local"]:
            CMD+=".AppImage"
    else:
        ## Mana and M+ are not available on Windows yet (TODO)
        if pref["local"]:
            CMD+="Mana/manaplus.exe" # FIXME untested
        else:
            CMD+="manaplus.exe"      # FIXME untested

    ## Build the server options
    OPT="-s %s -y %s -p %s -S" % (HOST, serverlist[idx]["Type"], PORT)
    ## Mana "fix"
    if pref["mana"]:
        OPT=OPT[:-2]
    print("%s %s" % (CMD, OPT))

    ## Local or System-Wide Config folders
    if pref["local"]:
        if not sys.platform.startswith('win'):
            OPT+=" -C %s/Config -L %s/Local" % (CWD, CWD)
        else:
            OPT+=" -C %s\\Config -L %s\\Local" % (CWD.replace('/','\\'), CWD.replace('/','\\'))
        ## Mana "fix" (TODO Untested / also, Config may fail)
        if pref["mana"]:
            OPT=OPT.replace(" -L ", " --localdata-dir ")

    ## Update Discord if relevant
    RPCUpdate(serverlist[idx]["Name"], serverlist[idx]["Back"])

    ## Execute the app
    ## TODO: Threading?
    if pref["shell"]:
        app=execute(san("%s %s%s" % (CMD, OPT, PWD)), shell=True) # nosec
    else:
        app=execute(san("%s %s%s" % (CMD, OPT, PWD)), shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # nosec

    return app

## Lame hack
def greetHack(idx, PWD):
    launch_game_master(idx, PWD)
    world_select()
    return

## Run a game from world selection screen, and handles MLP
def launch_game_master(idx, PWD=None):
    if PWD is None:
        app=launch_game(idx)
    else:
        app=do_real_launch(idx, PWD)
    if type(app) != int:
        try:
            # worldGreet dl_
            greeting=worldGreet[serverlist[idx]["UUID"]]
            greeter(greeting, _dest=partial(greetHack, app[0], app[1]))
            return
        except:
            app=do_real_launch(idx, PWD)

    while app == 7:
        stdout("[CLIENT] Mirror Lake triggered.")
        ## Set credentials
        auth = {"vaultId": vaultId,
                "token": vaultToken}
        r=vault.post(VAULT_HOST+"/getlake", json=auth, timeout=15.0)
        if r.status_code == 200:
            goto=r.json()["world"]
            stdout("MLP Target: %s" % str(goto))
            if goto == "" or goto.lower() == "vault":
                stdout("Mirror Lake False Positive")
                break
            try:
                idx=int(dl_search_idx(serverlist, "UUID", goto))
                app=launch_game(idx)
            except:
                traceback.print_exc()
                break
    return

## Only meaningful on Linux
os.environ["APPIMAGELAUNCHER_DISABLE"]="1"

#################################################################################
## Construct session data
update_serverlist(SERVERLIST)
vaultId = -1
saveMail = None
savePass = None

#################################################################################
###### Some generic text speed
def greeter(text, _dest=None):
    global canva, serverlist
    canva.destroy()
    canva = tk.Canvas(root, width=400, height=600, bg="#0c3251")
    canva.pack()
    label1 = tk.Label(root, text=text, anchor="s", wraplength=350, justify="center", bg="#0c3251", fg="#fff")
    label1.config(font=('helvetica', 12))
    canva.create_window(200, 300, window=label1)
    button = HoverButton(text="Continue...", command=_dest, width=40, bg="#cc6600", fg="#fff", activebackground="#ee9933")
    canva.create_window(200, 575, window=button)
    return

## TODO: Settings screen
#################################################################################
###### World Selection Screen
def world_select():
    global canva, serverlist
    canva.destroy()
    canva = tk.Canvas(root, width=400, height=600, bg="#0c3251")
    canva.pack()
    label1 = tk.Label(root, text='World Selection', bg="#0c3251", fg="#fff")
    label1.config(font=('helvetica', 14))
    canva.create_window(200, 30, window=label1)

    ## Fetch soul data
    auth = {"vaultId": vaultId,
            "token": vaultToken}

    r=vault.post(VAULT_HOST+"/souldata", json=auth, timeout=15.0)
    if r.status_code != 200:
        raise Exception("Request error: %d" % r.status_code)
    dat=r.json()
    mySoul={}
    mySoul["level"]=dat["soulv"]
    mySoul["exp"]=dat["soulx"]
    mySoul["next"]=dat["varlv"]
    mySoul["up"]=False
    ## Newer versions of API may level you up - catch it
    try:
        mySoul["up"]=dat["lvlup"]
        mySoul["home"]=dat["homew"]
        for s in serverlist:
            if mySoul["home"] == s["UUID"]:
                mySoul["home"] = s["Name"]
                break
        if mySoul["home"] == "VAULT":
            mySoul["home"]="Not Set"
    except:
        pass

    ## Not really necessary? Or just TODO?
    ## Without these, max is 10 worlds
    #scrollbar = tk.Scrollbar(canva, orient=tk.VERTICAL)
    #canva.create_window(400, 20, window=scrollbar)

    ## Create a list of all worlds
    ypos = 60
    for w in serverlist:
        ## TODO: Do not block main thread, launch this in a threading?
        ## TODO: Image button if an icon can be found
        button = HoverButton(text=w["Name"], command=partial(launch_game_master, serverlist.index(w)), width=40, anchor="w", bg="#cc6600", fg="#fff", activebackground="#ee9933")
        canva.create_window(200, ypos, window=button)
        ## TODO FIXME: World Info Button
        button = HoverButton(text="?", command=partial(info_game, serverlist.index(w)), bg="#cc6600", fg="#fff", activebackground="#ee9933")
        canva.create_window(370, ypos, window=button)
        ypos += 40

    ## TODO: Footnote: Settings button
    labf = "Lv %d, %d/%d EXP" % (mySoul["level"], mySoul["exp"], mySoul["next"])
    labelf = tk.Label(root, text=labf, bg="#0c3251", fg="#fff")
    labelf.config(font=('helvetica', 13))
    canva.create_window(200, 550, window=labelf)
    labelf = tk.Label(root, text="Home: %s" % mySoul["home"], bg="#0c3251", fg="#fff")
    labelf.config(font=('helvetica', 13))
    canva.create_window(200, 570, window=labelf)
    return

#################################################################################
## Login function
def login():
    global canva, vaultId, vaultToken, saveMail, savePass, newUser
    email = entry1.get()
    passw = entry2.get()
    totps = entry3.get()

    ## Save email or delete saved copy
    if saveMail.get():
        pref["user"] = email
    else:
        pref["user"] = ""

    ## Save password or delete saved copy
    if savePass.get():
        pref["pass"] = passw
    else:
        pref["pass"] = ""

    ## Prepare the packet for Vault
    data = {"mail": email,
              "pass": passw,
              "totp": totps[:6]
             }
    try:
        r = vault.post(VAULT_HOST+"/user_auth", json=data)

        if (r.status_code != 200):
            add=""
            if r.status_code == 400:
                add="\nBad request.\n"
            elif r.status_code == 401:
                add="\nIncorrect username/password.\n"
            elif r.status_code == 429:
                add="\nYou are being rate-limited.\n"
            showerror(title="Mana Launcher", message="Vault returned error %d\n%s\nPlease try again later." % (r.status_code, add))
            exit(1)
    except SystemExit:
            exit(1)
    except:
        err = traceback.format_exc().split("\n")[-2]
        print("Error: %s" % err)
        showerror(title="Mana Launcher", message="Python error\n\nPlease try again later.")
        exit(1)

    auth2 = r.json()
    vaultId = auth2["vaultId"]
    vaultToken = auth2["token"]

    ## Only save settings if connection worked
    _savePref()

    ## Change the display
    print("Connected to vault! vaultId = %d" % vaultId)
    ## TODO: Do not jump to world selection if it is a new account
    if newUser:
        greeting="""
Welcome to the Mana Launcher\n
\n
With your soul shattered in pieces, you drift along the void.\n
Faint memories of the figure clad in black emerge, what could they mean?\n
\n
You might not remember much... But your willpower is not gone.\n
"This is not the end". And with it, the determination to continue and see through the end.\n
\n
Which world will you visit first? For once you finish all of the worlds, your true power shall return to you...
        """
        greeter(greeting, _dest=world_select)
    else:
        world_select()
    return

#################################################################################
## Build Tkinter interface
root=tk.Tk()
root.title("Mana Launcher (tk)")
canva = tk.Canvas(root, width=400, height=600, bg="#0c3251")
canva.pack()

## Default variables
saveMail = tk.BooleanVar()
saveMail.set(pref["user"] != "")
savePass = tk.BooleanVar()
savePass.set(pref["pass"] != "")

## Email
label1 = tk.Label(root, text='Email:', bg="#0c3251", fg="#fff")
label1.config(font=('helvetica', 14))
canva.create_window(180, 40, window=label1)
entry1 = tk.Entry(root)
entry1.insert(0, pref["user"])
canva.create_window(180, 80, window=entry1)
c1 = tk.Checkbutton(root, text="Remember", variable=saveMail, bg="#0c3251", fg="#f70")
canva.create_window(320, 80, window=c1)


label2 = tk.Label(root, text='Password:', bg="#0c3251", fg="#fff")
label2.config(font=('helvetica', 14))
canva.create_window(180, 120, window=label2)
entry2 = tk.Entry(root, show="*")
entry2.insert(0, pref["pass"])
canva.create_window(180, 160, window=entry2)
c1 = tk.Checkbutton(root, text="Remember", variable=savePass, bg="#0c3251", fg="#f70")
canva.create_window(320, 160, window=c1)


label3 = tk.Label(root, text='TOTP:', bg="#0c3251", fg="#fff")
label3.config(font=('helvetica', 14))
canva.create_window(180, 200, window=label3)
entry3 = tk.Entry(root)
#entry3.insert(0, pref["totp"])
canva.create_window(180, 240, window=entry3)


button1 = HoverButton(text='Login', command=login, bg="#cc6600", fg="#fff", activebackground="#ee9933")
canva.create_window(200, 300, window=button1)
root.mainloop()

# Check if you were logged in
if vaultId < 1:
    exit(1)

print("Thanks for playing!")