~cadence/crumpet

ref: 840407d0a91baf1a1f18456efbe70726c04d523c crumpet/crumpet.py -rw-r--r-- 9.5 KiB
840407d0Cadence Ember Force mime type text/javascript for .js files 1 year, 12 days 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
import cherrypy
import hashlib
import mimetypes
import os
import pathlib
import re
import requests
import shelve
import shutil
import subprocess
import sys

content_host = "https://cadence.moe"

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

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_installed", True)

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 with "Return To Wonderland"
		possible_matches = [line for line in possible_matches if "Return To Wonderland" in line]
		if len(possible_matches) == 1:
			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] = []
			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):
		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):
		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
	@cherrypy.tools.json_out()
	def request_images(self, *path_components):
		# 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 not db["is_installed"]:
			return restricted_message()
		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):
		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"
	}
})