summaryrefslogtreecommitdiff
path: root/game/client.rpy
blob: 2565edc5ac2c6422a61bb7959fdafc669101a83e (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
#################################################################################
#     This file is part of Mana Launcher.
#     Copyright (C) 2021  Jesusalva <jesusalva@tmw2.org>
#
#     Distributed under the MIT license, except for Steam parts.
#################################################################################
init 2 python:
    def handle_client(CLIENT_NAME="", launch=False, download=True):
        ## Local variables
        f=False
        if (CLIENT_NAME == ""):
            CLIENT_NAME=persistent.client

        ## Main loop
        if (CLIENT_NAME == "manaplus"):
            f=cli_manaplus(launch, download)
        elif (CLIENT_NAME == "mana"):
            f=cli_mana(launch, download)
        else:
            status_update("ERROR, unrecognized client: %s" % CLIENT_NAME)

        return f

    def launch_game(idx):
        global progress, responsive
        # TODO: use the proper discord RPC image
        RPCUpdate(persistent.serverlist[idx]["Name"], persistent.serverlist[idx]["Back"])
        HOST=persistent.serverlist[idx]["Host"]
        PORT=persistent.serverlist[idx]["Port"]
        CMD=handle_client(launch=True)
        OPT="-s %s -y evol2 -p %s" % (HOST, PORT)
        stdout("%s %s" % (CMD, OPT))

        ## Obtain access token from vault
        ## TODO: Only skip failure if not dev
        auth = {"vaultId": vaultId,
                "token": vaultToken,
                "world": persistent.serverlist[idx]["UUID"]}
        PWD=""
        try:
            r=vault.post(VAULT_HOST+"/world_pass", json=auth, timeout=15.0)
            if r.status_code == 200:
                auth2=r.json()
                PWD=" -U %s -P %s" % (auth2["user"], auth2["pass"])
            elif r.status_code == 403:
                stdout("Warning: Connection was refused (Vault logout?)")
                responsive = False
                return
            else:
                stdout("Get World Auth - Returned error code %d" % r.status_code)
        except:
            pass

        ## Minimize to tray if set
        if not renpy.mobile and persistent.iconify:
            renpy.iconify()

        ## Launch your prefered game client, wait for it to finish
        if renpy.windows:
            app=execute("\"%s\" %s%s" % (CMD, OPT, PWD), shell=True)
        else:
            app=execute("%s %s%s" % (CMD, OPT, PWD), shell=True)
        if app:
            traceback.print_exc()
            stdout("[CLIENT] An error happened: %d" % app)
            #responsive = False

        # NOTE: Now we would like to un-minimize ourselves
        # But we cannot =/
        # There's a few tricks but not very nice...
        # https://stackoverflow.com/questions/45426203/minimize-window-with-python (Linux)
        # https://stackoverflow.com/questions/2791489/how-do-i-take-out-the-focus-or-minimize-a-window-with-python/2792059 (Windows)
        progress=100

        # Clean discord RPC and go back to world selection menu
        RPCUpdate("Main Menu", "launcher")
        return

    def md5check_client():
      renpy.notify("Checking md5sum...")
      try:
        installdir=get_path(persistent.client)
        fname=handle_client(launch=True, download=False).split("/").pop()
        r=requests.get(persistent.host+"/%s.md5" % fname, timeout=10.0)
        md5up=r.text.replace("\n", "")

        md5us=md5sum(installdir+"/%s" % fname)
        if md5up != md5us:
            stdout("MD5 Mismatch: hashes differ", True)
            stdout("Ours: %s" % md5us, True)
            stdout("Them: %s" % md5up, True)
            shutil.rmtree(get_path(persistent.client))
            renpy.notify("Files are corrupted!")
        else:
            renpy.notify("All files up to date!")
      except:
        traceback.print_exc()
        renpy.notify("An error happened.")
        return

init 1 python:
    #############################################################################
    def download_manaplus(fname):
            installdir=get_path("manaplus")
            status_update("Downloading %s on RAM..." % fname, 62)
            r=requests.get(persistent.host+"/%s" % fname, timeout=60.0)
            if (r.status_code != 200):
                status_update("Failure retrieving M+: ERROR %d" % r.status_code)
                return False

            status_update("Saving %s..." %fname, 64)
            with open(installdir+"/%s" % fname, 'wb') as fd:
                for chunk in r.iter_content(chunk_size=128):
                    fd.write(chunk)

            status_update("Verifying MD5 hash...", 67)
            r=requests.get(persistent.host+"/%s.md5" % fname, timeout=10.0)
            md5up=r.text.replace("\n", "")

            status_update("Verifying MD5 hash...", 69)
            md5us=md5sum(installdir+"/%s" % fname)
            if md5up != md5us:
                status_update("MD5 Hash Error")
                stdout("MD5 Mismatch: hashes differ", True)
                stdout("Ours: %s" % md5us, True)
                stdout("Them: %s" % md5up, True)
                return False
            return True

    #######################
    def install_manaplus():
        status_update("Creating ManaPlus directory...", 61)
        installdir=get_path("manaplus")
        os.mkdir(installdir)
        ## Detect your plataform
        #########################################################
        if renpy.linux:
            if not download_manaplus("ManaPlus.AppImage"):
                return False

            status_update("Marking as executable...", 70)
            execute("chmod +x \"%s\"" % installdir+"/ManaPlus.AppImage", shell=True)
            status_update("Installation successful!", 75)
        #########################################################
        elif renpy.windows:
            if not download_manaplus("ManaPlus.zip"):
                return False

            status_update("Unzipping file...", 70)
            with zipfile.ZipFile(installdir+"/ManaPlus.zip", 'r') as zip_ref:
                zip_ref.extractall(installdir)
            status_update("Installation successful!", 75)
        #########################################################
        #elif renpy.android:
        #elif renpy.macintosh:
        #elif renpy.emscripten: # web
        #########################################################
        else:
            status_update("ERROR: Unsupported Plataform")
            return False
        return True

    ###############################
    def cli_manaplus(launch=False, download=True):
        global SCR_PROMPT, SCR_RESULT
        ## Check if ManaPlus is already installed
        try:
            MANAPLUS=os.path.exists(get_path("manaplus"))
        except:
            traceback.print_exc()
            MANAPLUS=False

        ## Installer
        if not MANAPLUS and download:
            SCR_PROMPT=("Selected client \"%s\" is not installed.\nDo you wish to install it now?\n\n{size=14}By installing you agree with its {a=%s}Terms of Use and Conditions{/a}.%s{/size}" %
            ("ManaPlus", "https://gitlab.com/themanaworld/manaplus/manaplus/-/raw/master/COPYING",
            ifte(renpy.linux, "\n{i}libfuse2{/i} is required to run AppImages.", "")))
            while SCR_RESULT is None:
                time.sleep(0.02)
            ret=copy.copy(SCR_RESULT)
            SCR_RESULT=None
            if (not ret):
                return False

            try:
                if not install_manaplus():
                    # Delete the failed attempt before raising the exception
                    shutil.rmtree(get_path("manaplus"))
                    #os.rmdir(get_path("manaplus"))
                    raise Exception("Installation failed!")
            except:
                traceback.print_exc()
                stdout("Installation failed!", True)
                return False
        elif not MANAPLUS:
            return False

        ##########
        if launch:
            if renpy.linux:
                os.environ["APPIMAGELAUNCHER_DISABLE"]="1"
                pathy=get_path("manaplus")+"/ManaPlus.AppImage"
                return pathy.replace(" ", "\\ ")
            elif renpy.windows:
                pathy=get_path("manaplus")+"/Mana/manaplus.exe"
                return pathy.replace("/", "\\")
            else:
                stdout("Invalid Plataform!")
                return False
        return True

    #############################################################################
    def cli_mana(launch=False, download=True):
        stdout("ERROR, Mana Client is not implemented!")
        return False

        ## Check for Mana
        try:
            MANA=os.path.exists(get_path("mana"))
        except:
            traceback.printexc()
            MANA=False

        ## Installer
        if not MANA and download:
            SCR_PROMPT=("Selected client \"%s\" is not installed.\nDo you wish to install it now?\n\n{size=14}By installing you agree with its {a=%s}Terms of Use and Conditions{/a}.{/size}" %
            ("Mana", "https://gitlab.com/themanaworld/tmw-client/????/-/raw/master/COPYING"))
            while SCR_RESULT is None:
                time.sleep(0.02)
            ret=copy.copy(SCR_RESULT)
            SCR_RESULT=None
            if (not ret):
                return False
        elif not MANA:
            return False
        return True