summaryrefslogtreecommitdiff
path: root/game/core.rpy
blob: 343a703c8a0b875dfa5c34cc7cf01806512e846e (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
#################################################################################
#     This file is part of Mana Launcher.
#     Copyright (C) 2021  Jesusalva <jesusalva@tmw2.org>
#
#     Distributed under the MIT license.
#################################################################################

init -3 python:
    renpy.add_python_directory("python-extra")
    import requests, zlib, base64, sys, copy, uuid, time, json, traceback
    import os.path, os, shutil, subprocess, hashlib, zipfile, pbkdf2
    # non-free imports
    import _renpysteam as steam
    import discord_rpc

    print("\n[STDBY] Loading Basic functions.......")

    #############################################################################
    ## Compatibility
    # set PYTHON_VERSION variable (e.g. 2715, 3605 etc.)
    PYTHON_VERSION="%d%d%02d" % (sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
    PYTHON_VERSION=int(PYTHON_VERSION)

    # Ren'Py should come with Python 2.7.10 (2710), but just in case
    # After all, I only tested with 2.7.10, 2.7.13 and 2.7.15
    if (PYTHON_VERSION < 2700 or PYTHON_VERSION > 3000):
        execute=subprocess.run
        # FIXME: check must be set and True
        raise Exception("WARNING: Python version is not 2.7\nStrange bugs may happen on your client.\n\nClick on \"Ignore\" to continue.\nClick on \"Quit\" to exit.")
    else:
        execute=subprocess.call

    #############################################################################
    # Functions
    # Encodes something to md5
    def md5(string):
        return hashlib.md5(string.encode()).hexdigest()

    def md5sum(f):
        md5=hashlib.md5()
        fp=open(f, "rb")
        ct=fp.read()
        md5.update(ct)
        rt=copy.copy(md5.hexdigest())
        fp.close()
        del ct
        return rt

    # Smart Print command
    def stdout(message, bd=False):
        if config.developer:
            if renpy.android:
                if not renpy.is_init_phase():
                    renpy.notify(message)
            else:
                if bd:
                    print("\033[1m%s\033[0m" % message)
                else:
                    print(message)
            renpy.write_log("[DEBUG] %s" % message)
        else:
            renpy.write_log("[GAME] %s" % message)
        return

    # Smart wait
    def sdelay(delta=0.02):
        try:
            renpy.pause(delta, hard=True)
        except:
            time.sleep(delta)
        return

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

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

    # File Managment Functions
    def get_path(path):
        # Not all systems can record on the game folder
        if renpy.android:
            path=path.replace("/", "_")
            return renpy.config.savedir + "/" + path
        else:
            return renpy.config.basedir + "/" + path

    #############################################################################
    # Global classes
    # We need to override standard list method. Original by Triptych (stackoverflow)
    class dlist(list):

        def __setitem__(self, index, value):
            size = len(self)
            if index >= size:
                self.extend(None for _ in range(size, index + 1))

            list.__setitem__(self, index, value)

    # Search for array[?][key]==search in an array of dicts
    # Returns the dictionary, or returns ERR_INVALID
    def dl_search(array, key, search):
        try:
            r=(item for item in array if item[key] == search).next()
        except:
            r=ERR_INVALID
        if r is None:
            r=ERR_INVALID
            stdout("dlsearch: r is None")
        return r

    #############################################################################
    ## Some other stuff
    if renpy.linux:
        os.environ["APPIMAGELAUNCHER_DISABLE"]="1"

    #############################################################################
    ## Configuration and Defaults
    if (persistent.discord is None):
        persistent.discord = True
    if (persistent.steam is None):
        persistent.steam = False
    if (persistent.client is None):
        persistent.client = "manaplus"
    if (persistent.iconify is None):
        persistent.iconify = ifte(renpy.windows, False, True)

    #############################################################################
    # ["themanaworld.org", "germantmw.de", "moubootaurlegends.org"]
    if config.developer:
        VAULT_HOST = "https://localhost:13370"
        VAULT_CERT = "http://localhost/launcher/cert.pem"
    else:
        VAULT_HOST = "http://api.tmw2.org:13370"
        VAULT_CERT = "https://tmw2.org/launcher/cert.pem"

    ###################
    # Vault SSL wrapper
    vault=requests.Session()
    vault.cert = get_path("cert.pem")
    vault.verify = get_path("cert.pem")

    ############################################################################
    ## Retrieve the Vault certificate. Otherwise, we cannot proceed.
    ## From here and until the end of this code block,
    ## ALL ERRORS ARE FATAL
    def build_vault():
        while True:
            try:
                ######################################
                # Fetch a new PEM Certificate
                stdout("Fetching SSL Certificate from %s" % VAULT_CERT)
                r = requests.get(VAULT_CERT)
                if (r.status_code != 200):
                    raise Exception("\nFailed to fetch Vault SSL Certificate.\b\n Returned HTTP error %d.\n\nClick \"Ignore\" to retry.\n\n" % r.status_code)
                # Save it
                with open(get_path("cert.pem"), 'wb') as fd:
                    for chunk in r.iter_content(chunk_size=128):
                        fd.write(chunk)
                # Presumably all good, so do not continue and break the loop
                stdout("PEM Download OK")
                break
            except:
                traceback.print_exc()
                raise
                stdout("Automatically retry in 5 seconds...")
                time.sleep(5.0)
            ## End FATAL mode
            #############################################################

######### Done with pre-init
label splashscreen:
    show TMW2 at truecenter with fade
    python:
        if persistent.hello is None:
            p1=2.5
            p2=1.5
        else:
            p1=0.5
            p2=0.5
    pause p1
    hide TMW2 with Dissolve(p2)
    call before_main_menu
    if persistent.hello is None:
        call screen preferences
        $ persistent.hello=True
    return

label die:
    $ stdout("Program died.")
    pause
    return

####### Defaults
default statusmsg = "Not yet initialized"
default progress = 0
default responsive = True
default has_steam = False
default SCR_PROMPT = None
default SCR_RESULT = None

## Command Line Interface
init -4 python:
    USE_DUMMY_DATA = False
    def parse_command():
        global USE_DUMMY_DATA
        parser = renpy.arguments.ArgumentParser()

        ## Collect args
        parser.add_argument('args', nargs='+', help="Command-line arguments.")
        targs = parser.parse_args()
        args = targs.args

        ## Debug information
        if config.developer:
            print("PARSEC")
            print("Args: %s" % str(args))

        ## Command Line Defaults
        if ("steam" in args):
            print("Steam Mode Enabled")
            persistent.steam = True
        if ("dummy" in args):
            print("Dummy Mode Enabled")
            USE_DUMMY_DATA = True
        return True

    renpy.arguments.register_command('adv', parse_command)