summaryrefslogtreecommitdiff
path: root/game/02_init.rpy
blob: 6186e329f6283fcc567ee3b56259e98629384fa7 (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
########################################################################################
#     This file is part of Spheres.
#     Copyright (C) 2019  Jesusalva

#     This library 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 2.1 of the License, or (at your option) any later version.

#     This library 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 this library; if not, write to the Free Software
#     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
########################################################################################
# Definitions
############################################################################
init -1 python:
    # Android might have special SSL problems
    if renpy.android:
        try:
            import ssl
        except ImportError:
            SSL_IS_BROKEN=True
            stdout("Android SSL misbehavior detected")
            import _openssl as ssl
    else:
        import ssl
        print("Using system-wide SSL implementation...")

    # wsock already imported

    stdout("======================= %s %s %s" % (config.name, config.version, persistent.release_name))
    print "[STDBY] Loading Basic functions......."

    # 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

    def check_fail(raw):
        global debug, FAILUREMSG

        if (debug):
            stdout(str(raw))
        if (raw == FAILUREMSG):
            return True
        return False

    def json_decode(raw):
        global ERRNO

        if (check_fail(raw)):
            return ERR_LOGIN_DEFAULT

        # TODO Move this to check_fail and rewrite check_fail
        # ERR_OFF should be handled top-level no? With full_restart()
        if raw in ERRNO:
            return raw

        try:
            return int(raw)
        except:
            pass

        # Maybe base 64
        try:
            rw=base64.b64decode(raw)
            raw=rw
            if (debug):
                print "base64 decoded"
        except:
            pass

        # Maybe zlib compressed
        try:
            rw=zlib.decompress(raw)
            raw=rw
            if (debug):
                print str(raw)
        except:
            pass

        # Decode JSON
        try:
            return json.loads(raw)
        except:
            return ERR_JSONDECODER

    def get_token():
        try:
            t=Player['token']
        except:
            t="0" #"f528764d624db129b32c21fbca0cb8d6"
        return t

    def login():
        global Player
        stdout("Login requested for %s" % logindata())
        raw=send_packet("login", logindata())

        Player=json_decode(raw)
        if (Player == ERR_JSONDECODER):
            return ERR_JSONDECODER
        if (Player == ERR_LOGIN_DEFAULT):
            return ERR_LOGIN_DEFAULT

        try:
            Player["inv"]=dlist()
        except:
            pass
        return Player["code"]

    def send_packet_now(packet, args="", legacy=False):
        global tr_load, tr_val, tr_busy
        global ws

        stdout("Sending: %s" % packet)
        try:
            ws.send(get_token() + ";" + packet + ";" + args)
        except:
            stdout("Failed to send message!!")
            # FIXME set tr_val/tr_load/tr_busy to good values
            return False
        # TODO: Wait for onmsg
        # TODO: ping packets
        return True

    def send_packet(packet, args=""):
        global tr_load, tr_val, tr_busy
        # TODO: if tr_busy already true, wait until it is made false
        while tr_busy:
            sdelay()

        # Book processing space for ourselves
        tr_busy=True
        tr_load=False
        tr_val=None

        # This is a secret variable which disables threading and queue
        # This may cause hangs and other issues.
        if persistent.nothreading:
            send_packet_now(packet, args)
            tr_busy=False
            val=tr_val
            return val

        # FIXME
        timeout=0.0
        renpy.show("spinner", at_list=[truecenter])
        r = send_packet_now(packet, args)
        if not r:
            # Something went wrong
            return ERR_INVALID

        while not tr_load:
            sdelay() # FIXME: This can cause errors in mobile?
            timeout+=0.02

            if timeout >= TIMEOUT_INTERVAL:
                # FIXME: What if a screen is already being displayed? BUG
                try:
                    renpy.call_screen("msgbox", "Error Code: %d\n\nApplication timeout, click to try again" % (ERR_TIMEOUT))
                    timeout=0.0
                except:
                    if not "ping" in packet.lower():
                        stdout("WARNING, ILLEGAL PACKET ON SCREEN TIME: %s" % packet)
                    pass

        renpy.hide("spinner")
        val=tr_val
        tr_busy=False
        del tr_val

        print "value obtained"
        if (val is None):
            return ERR_INVALID
        return val

    def GAME_LOADER():
        global allunitsbase, allunits, allquests, allstory, allworld, alltaverns
        global allnews, tr_load
        tr_load=False

        # Wait until everything is up to date
        while not tr_uptodate:
            sdelay()

        # Load unit data
        allunitsbase=json.loads(requests.get("http://"+HOST+'/units.json').text)
        #    f=open(get_path_if_exists("units.json"), "r")
        #    allunitsbase=json.load(f)
        #    f.close()

        # Reorder unit data
        allunits={}
        for j in allunitsbase:
            allunits[j["unit_id"]]=j

        # Load summons data
        f=open(get_path_if_exists("summons.json"), "r")
        allworld=json.load(f)
        f.close()

        # Load quest data
        f=open(get_path_if_exists("quests.json"), "r")
        allquests=json.load(f)
        f.close()

        # Load story data
        f=open(get_path_if_exists("story.json"), "r")
        allstory=json.load(f)
        f.close()

        # Load world data
        f=open(get_path_if_exists("world.json"), "r")
        allworld=json.load(f)
        f.close()

        # Load tavern data
        f=open(get_path_if_exists("bar.json"), "r")
        alltaverns=json.load(f)
        f.close()

        # Load server news
        try:
            allnews=json.loads(requests.get("http://"+HOST+'/news.json', timeout=5.0).text)
        except:
            allnews=[]
            pass

        stdout("[OK] Game data loaded to memory")
        tr_load=True
        tr_memcheck=True
        return tr_load