~cadence/crumpet

crumpet/crumpet.py -rw-r--r-- 11.3 KiB
d25eb2deCadence Ember Use new domain for downloading images 10 months ago
                                                                                
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
import cherrypy
from cherrypy.lib.static import serve_file
import hashlib
import mimetypes
import os
import pathlib
import random
import re
import requests
import shelve
import shutil
import subprocess
import sys
from threading import Lock
import time

content_host = "https://crumpet.cadence.moe"

mimetypes.types_map[".js"] = "text/javascript" # serve correct type for javascript modules; mimetypes module has application/javascript normally

tokens = {}
tokens_lock = Lock()

db = None
def init_database():
	global db
	db = shelve.open("crumpet_server_config", writeback=False)
	db.setdefault("game_directory", None)
	db.setdefault("customlevels_directory", None)
	db.setdefault("is_public_server", False)

try:
	init_database()
except:
	# database corruption error? HOW??? do I actually need to close the file like it told me
	# because I don't know how to close the file like it told me
	print("resetting server configuration due to database corruption")
	db.close()
	os.unlink("crumpet_server_config")
	init_database()

def hash_file(filename):
	h = hashlib.sha256()
	b = bytearray(h.block_size)
	mv = memoryview(b)

	with open(filename, "rb") as file:
		for n in iter(lambda: file.readinto(mv), 0):
			h.update(mv[:n])

	return h

def check_game_path(game_path):
	if not game_path.exists() or not game_path.is_dir():
		return {
			"status": "failure",
			"message": "Directory does not exist."
		}
	res2_path = game_path.joinpath("res2.dat")
	if not res2_path.exists() or res2_path.is_dir():
		return {
			"status": "failure",
			"message": "Directory exists, but does not contain res2.dat."
		}
	return None

def open_level(filename, mode):
	return open(os.path.join(db["customlevels_directory"], filename), mode)

def restricted_message():
	return "This action is restricted. You can enable this action by installing Crumpet on your own computer."

def autodetect_game_directory():
	if sys.platform == "win32":
		# only bother to support x64.
		# if x86 were supported, its prefix would be HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall
		candidates = [c for c in subprocess.run(["REG", "QUERY", "HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"], capture_output=True).stdout.splitlines() if b"Midnight Synergy" in c or b"Return To Wonderland" in c]
		# candidates = [b'HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Midnight Synergy Games Collection_is1', b'HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Return To Wonderland v1.01_is1', b'HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Return To Wonderland_is1']
		candidates.sort()
		preferred = [c for c in candidates if c.endswith(b"\\Return To Wonderland_is1")]
		for c in preferred + candidates:
			info_lines = [re.sub(" +", " ", bytes.decode(line)).split(" ", 3)[1:] for line in subprocess.run(["REG", "QUERY", c], capture_output=True).stdout.splitlines()]
			info_lines = [line for line in info_lines if len(line) == 3]
			info = {line[0]: line[2] for line in info_lines}
			if "InstallLocation" in info:
				try:
					# keep trying to go into "Return To Wonderland" until you can't anymore
					# this ensures we get into the real game directory no matter whether it is from the standalone or the original collection
					install_location = pathlib.WindowsPath(info["InstallLocation"])
					exists = None
					while install_location.exists() and install_location.is_dir():
						exists = install_location
						install_location = install_location.joinpath("Return To Wonderland")
					if exists:
						# this is the final directory to use!
						return str(exists)
				except Exception as e:
					# print the error and move on to the next candidate
					print(e)
		return None # todo!
	else:
		search_locations = [os.path.expanduser(location) for location in [
			"~/.wine",
			"~/.PlayOnLinux",
			"~/.local/share/wineprefixes",
			"~/.lutris"
		]]
		# try ag first since it is faster
		try:
			s = subprocess.run(["ag", "-g", "/res2.dat$"] + search_locations, capture_output=True, cwd="/")
		except FileNotFoundError:
			s = subprocess.run(["find"] + search_locations + ["res2.dat"], capture_output=True, cwd="/")
		possible_matches = [os.path.dirname(line) for line in bytes.decode(s.stdout).splitlines() if line]
		# initial return decisions
		if len(possible_matches) == 0:
			return None
		if len(possible_matches) == 1:
			return possible_matches[0]
		# multiple matches: need to refine them
		# assume that the game is installed to a path ending with "/Return To Wonderland"
		possible_matches = [line for line in possible_matches if line.endswith("/Return To Wonderland")]
		if possible_matches:
			return possible_matches[0]
		# no more strategies for refining
		return None

class Crumpet:
	def _cp_dispatch(self, vpath):
		if vpath[:2] == ["api", "rtw"]:
			vpath[:2] = []

			if vpath[0] == "fetchimages":
				vpath[0] = "images_server"

			return self

		return vpath

	@cherrypy.expose
	@cherrypy.tools.json_out()
	def get_paths(self):
		# Check game directory
		source = "configuration"
		game_directory = db["game_directory"]
		if game_directory:
			game_path = pathlib.Path(game_directory)
			problem = check_game_path(game_path)
			if problem:
				source = "autodetect"
				game_directory = autodetect_game_directory()
		else:
			source = "autodetect"
			game_directory = autodetect_game_directory()
		# do not need to check customlevels directory since the interface should replace whatever is sent.
		customlevels_directory = db["customlevels_directory"]
		return {
			"source": source,
			"game_directory": game_directory,
			"customlevels_directory": customlevels_directory
		}

	@cherrypy.expose
	@cherrypy.tools.json_in()
	@cherrypy.tools.json_out()
	def save_game_directory(self):
		if db["is_public_server"]:
			return {
				"status": "failure",
				"message": "This server cannot be configured."
			}

		try:
			root = cherrypy.request.json
		except AttributeError:
			return {
				"status": "failure",
				"message": "Requires JSON POST input."
			}
		if type(root.get("value")) != str:
			return {
				"status": "failure",
				"message": "Requires `value` string parameter in JSON."
			}
		game_directory = root["value"]
		if game_directory.startswith("file:///"):
			game_directory = game_directory.replace("file:///", "/", 1)
		# Check that the game is there
		game_path = pathlib.Path(game_directory)
		if not game_path.exists() or not game_path.is_dir():
			return {
				"status": "failure",
				"message": "Directory does not exist."
			}
		res2_path = game_path.joinpath("res2.dat")
		if not res2_path.exists() or res2_path.is_dir():
			return {
				"status": "failure",
				"message": "Directory exists, but does not contain res2.dat."
			}
		db["game_directory"] = game_directory
		return {
			"status": "success"
		}

	@cherrypy.expose
	@cherrypy.tools.json_in()
	@cherrypy.tools.json_out()
	def save_customlevels_directory(self):
		if db["is_public_server"]:
			return {
				"status": "failure",
				"message": "This server cannot be configured."
			}

		try:
			root = cherrypy.request.json
		except AttributeError:
			return {
				"status": "failure",
				"message": "Requires JSON POST input."
			}
		if type(root.get("value")) != str:
			return {
				"status": "failure",
				"message": "Requires `value` string parameter in JSON."
			}
		customlevels_directory = root["value"]
		if customlevels_directory.startswith("file:///"):
			customlevels_directory = customlevels_directory.replace("file:///", "/", 1)
		# Check that the directory is there
		customlevels_path = pathlib.Path(customlevels_directory)
		if not customlevels_path.exists() or not customlevels_path.is_dir():
			return {
				"status": "failure",
				"message": "Directory does not exist."
			}
		db["customlevels_directory"] = customlevels_directory
		return {
			"status": "success"
		}

	@cherrypy.expose
	def token(self):
		if not db["is_public_server"]:
			cherrypy.response.status = 403
			return ""

		r = str(random.random()).split(".")[1]
		with tokens_lock:
			tokens[r] = time.time() + 60 # one minute from now
		return r

	@cherrypy.expose
	def images_server(self, *suffix, token, hash, **kwargs):
		print(token, hash)

		if not db["is_public_server"]:
			cherrypy.response.status = 403
			return ""

		if not token or not hash:
			cherrypy.response.status = 400
			return "Must supply token and hash"

		with tokens_lock:
			print(tokens)
			if token not in tokens:
				cherrypy.response.status = 403
				return "Invalid token"

			if tokens[token] < time.time():
				cherrypy.response.status = 403
				return "Expired token"

		h = hash_file("res2.dat")
		h.update(bytes(token, "utf-8"))
		patched_hash = h.hexdigest()

		if hash != patched_hash:
			cherrypy.response.status = 403
			return "Hash does not match"

		return serve_file(pathlib.Path(__file__).parent.joinpath("images.zip").absolute(), "application/zip")

	@cherrypy.expose
	@cherrypy.tools.json_out()
	def request_images(self, *path_components):
		if db["is_public_server"]:
			return {
				"status": "failure",
				"message": "This server cannot be configured."
			}

		# Request a token
		token_request = requests.get(content_host + "/api/rtw/token")
		token = token_request.content
		# print("token is: {}".format(token))

		# Hash the file
		game_directory = db["game_directory"]
		res2_path = pathlib.Path(game_directory).joinpath("res2.dat")
		if not res2_path.exists() or res2_path.is_dir():
			return {
				"status": "failure",
				"message": "Could not locate res2.dat."
			}
		h = hash_file(res2_path.absolute())
		# print("original hash is: {}".format(h.hexdigest()))

		# Update the hash with the token
		h.update(token)
		patched_hash = h.hexdigest()
		# print("patched hash is: {}".format(patched_hash))

		# Ask for images
		download_url = content_host + "/api/rtw/fetchimages?token={}&hash={}".format(token.decode(), patched_hash)
		images_request = requests.get(download_url)
		if images_request.status_code != 200:
			return {
				"status": "failure",
				"message": images_request.content
			}

		output_filename = pathlib.Path(__file__).parent.joinpath("images.zip").absolute()
		with open(output_filename, "wb") as fd:
			for chunk in images_request.iter_content(128):
				fd.write(chunk)

		unpack_directory = pathlib.Path(__file__).parent.joinpath("root").absolute()
		shutil.unpack_archive(output_filename, unpack_directory)

		return {
			"status": "success"
		}

	@cherrypy.expose
	@cherrypy.tools.json_in()
	def download(self):
		if db["is_public_server"]:
			return {
				"status": "failure",
				"message": "This is a public server, and you cannot store levels on it."
			}

		root = cherrypy.request.json
		level_data = bytearray(root["data"])
		filename = root["filename"]
		with open_level(filename, "wb") as fd:
			fd.write(level_data)
		cherrypy.response.status = 204

	@cherrypy.expose
	@cherrypy.tools.json_out()
	def load(self, filename):
		if db["is_public_server"]:
			return {
				"status": "failure",
				"message": "This is a public server, and you cannot store levels on it."
			}

		with open_level(filename, "rb") as fd:
			level_data = fd.read()
		return list(level_data)

server_root = pathlib.Path(__file__).parent.joinpath("root")
cherrypy.config.update({"server.socket_port": 3456, "server.socket_host": "0.0.0.0"})
cherrypy.quickstart(Crumpet(), "/", {
	"/": {
		"tools.staticdir.on": True,
		"tools.staticdir.dir": str(server_root.absolute()),
		"tools.staticdir.index": "index.html"
	}
})