-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserver.py
323 lines (265 loc) · 10.4 KB
/
server.py
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
print (" [+] Loading basics...")
import os
import sys
import json
if os.name == 'nt':
os.system("color")
os.system("title FarmVille Server")
else:
import sys
sys.stdout.write("\x1b]2;FarmVille Server\x07")
from assets import check_assets
print(" [+] Loading assets...")
check_assets()
print (" [+] Loading game settings...")
from game_settings import load_game_settings
load_game_settings()
print(" [+] Loading items...")
from items import load_items
load_items()
print (" [+] Loading players...")
from player import load_saves, load_static_villages, all_saves_info, all_saves_uids, save_info, new_village
load_saves()
print (" [+] Loading static villages...")
load_static_villages()
print (" [+] Loading server...")
from flask import Flask, render_template, send_from_directory, request, Response, redirect, session
from flask.debughelpers import attach_enctype_error_multidict
from werkzeug.utils import safe_join
from pyamf import remoting
import pyamf
import commands
from engine import timestamp_now
from version import version_name
from bundle import BASE_DIR, ASSETS_DIR, EMBEDS_DIR, ASSETHASH_DIR, PATCHED_ASSETS_DIR, TEMPLATES_DIR, XML_DIR
from player import save_session
BIND_IP = "127.0.0.1"
BIND_PORT = 5500
app: Flask = Flask(__name__)
print (" [+] Configuring server routes...")
# Templates
@app.route("/", methods=['GET', 'POST'])
def login():
# Log out previous session
session.pop('UID', default=None)
# Reload saves (not static villages nor quests). Allows saves modification without server reset
load_saves()
# If logging in, set session UID, and go to play
if request.method == 'POST':
session['UID'] = request.form['UID']
print("[LOGIN] UID:", request.form['UID'])
return redirect("/play.html")
# Login page
if request.method == 'GET':
saves_info = all_saves_info()
return render_template("login.html",
saves_info=saves_info,
version=version_name
)
@app.route("/play.html", methods=['GET'])
def play():
if 'UID' not in session:
return redirect("/")
if session['UID'] not in all_saves_uids():
return redirect("/")
UID = session['UID']
print("[PLAY] UID:", UID)
return render_template("play.html",
version=version_name,
base_url=f"http://{BIND_IP}:{BIND_PORT}",
server_time=timestamp_now(),
debug="true",
user={
"uid": UID,
"name": save_info(UID)["name"]
},
save_info=save_info(UID)
)
@app.route("/new.html")
def new():
session['UID'] = new_village()
return redirect("play.html")
@app.route("/img/<path:path>", methods=['GET'])
def img(path):
return send_from_directory(TEMPLATES_DIR + "/img", path)
@app.route("/css/<path:path>")
def css(path):
return send_from_directory(TEMPLATES_DIR + "/css", path)
@app.route("/crossdomain.xml", methods=['GET'])
def crossdomain():
return send_from_directory(TEMPLATES_DIR, "crossdomain.xml")
# Static endpoints
@app.route("/embeds/Flash/v855097-855094/FV_Preloader.swf", methods=['GET'])
def patched_preloader():
return send_from_directory(PATCHED_ASSETS_DIR, "FV_Preloader_mod.swf")
@app.route("/embeds/<path:path>", methods=['GET'])
def embeds(path):
return send_from_directory(EMBEDS_DIR, path)
@app.route("/assethash/<path:path>", methods=['GET'])
def assethash_path(path):
return send_from_directory(ASSETHASH_DIR, path, mimetype="application/x-amf")
@app.route("/xml/<path:path>", methods=['GET'])
def xml(path):
return send_from_directory(XML_DIR, path, mimetype='text/xml')
# @app.route("/assets/Environment/grass_themeBackground_7.swf", methods=['GET'])
# def stub_grass_themeBackground_7():
# return send_from_directory(ASSETS_DIR, "Environment/02de7becb766242e421e1430176f55a2.swf", mimetype='text/xml')
@app.route("/assets/<path:path>", methods=['GET'])
def assets(path):
return send_from_directory(ASSETS_DIR, path)
# Dynamic endpoints
@app.route("/report_exception.php", methods=['POST'])
def report_exception():
print("[!] Exception:", request.data.decode("utf-8"))
return "{}"
@app.route("/record_stats.php", methods=['POST'])
def record_stats():
stats = json.loads(request.data)
print("[+] Stats:")
for i in stats["stats"]:
print(" * ", i["statfunction"], ": ", i["data"], sep="")
return "{}"
@app.route("/report_log.php", methods=['POST'])
def report_log():
print("[+] Log:", request.data.decode("utf-8"))
return "{}"
@app.route("/cb.php", methods=['POST'])
def cb():
print("[+] Callback:", request.data.decode("utf-8"))
return "{}"
@app.route("/sn_app_url/index.php", methods=['GET'])
def sn_app_url_index():
ref = request.args.get("ref")
ooscode = request.args.get("ooscode")
oosfunc = request.args.get("oosfunc")
oosmsg = request.args.get("oosmsg")
print("[!] Reported Error:", ref ,":", ooscode, oosfunc, oosmsg)
return redirect("/")
@app.route("/flashservices/gateway.php", methods=['POST'])
def flashservices_gateway():
resp_msg = remoting.decode(request.data)
# print("[+] Gateway AMF3 Request:", resp_msg)
resps = []
reqs = resp_msg.bodies[0][1].body[1]
for reqq in reqs:
print(f"[+] {reqq.functionName}: {reqq['params']}")
UID = resp_msg.bodies[0][1].body[0]["uid"]
response = {
"errorType": 0,
"errorData": None,
"isDST": 0,
"sequenceNumber": reqq["sequence"],
"worldTime": timestamp_now(),
"metadata": {
"QuestComponent": {},
},
# "zySig": {
# "zy_user": resp_msg.bodies[0][1].body[0]["zy_user"],
# "zy_ts": timestamp_now(),
# "zy_session": resp_msg.bodies[0][1].body[0]["zy_session"]
# },
"data": None
}
if reqq.functionName == 'UserService.initUser':
firstName = reqq['params'][0]
timezoneOffset = reqq['params'][1]
needsToLoadWorld = reqq['params'][2]
flashControllerInit = reqq['params'][3]
response["data"] = commands.init_user(UID)
resps.append(response)
elif reqq.functionName == 'UserService.postInit':
response["data"] = commands.post_init_user(UID)
resps.append(response)
elif reqq.functionName == 'FriendSetService.getBatchFriendSetData':
response["data"] = []
resps.append(response)
elif reqq.functionName == 'UserService.r2InterstitialPostInit':
response["data"] = {
"r2InterstitialItems": [],
"r2InterstitialFeedItems": [],
"r2InterstitialMinigameIndex": [],
"r2InterstitialTypeIndex": None,
"r2InterstitialFriendCount": None
}
resps.append(response)
elif reqq.functionName == 'FriendListService.getFriendsForR2FlashNeighborFlow':
response["data"] = {
"requestedFriends": {
"GhostNeighbor": [],
"FarmVille": [],
"Facebook": [],
"PossibleCommunity": [],
"CurrentAllNeighbor": [],
}
}
resps.append(response)
elif reqq.functionName == 'UserService.incrementActionCount':
action = reqq['params'][0]
commands.increment_action_count(UID, action)
resps.append(response)
elif reqq.functionName == 'UserService.resetActionCount':
action = reqq['params'][0]
commands.reset_action_count(UID, action)
resps.append(response)
elif reqq.functionName == 'UserService.setSeenFlag':
flag = reqq['params'][0]
commands.set_seen_flag(UID, flag)
resps.append(response)
elif reqq.functionName == 'UserService.resetSystemNotifications':
resps.append(response)
elif reqq.functionName == 'UserContentService.onCreateImage':
name = reqq['params'][0]
png_b64 = reqq['params'][1]
feed_post = reqq['params'][2]
if name == "avatar_appearance":
commands.set_avatar_appearance(UID, name, png_b64, feed_post)
resps.append(response)
elif reqq.functionName == 'UserService.saveOptions':
options = reqq['params'][0]
commands.save_options(UID, options)
resps.append(response)
elif reqq.functionName == 'WorldService.performAction':
actionName = reqq['params'][0]
m_save = reqq['params'][1]
params = reqq['params'][2]
object_id = commands.world_perform_action(UID, actionName, m_save, params)
# This infroms the client of the new (non-temporary) object ID
response["id"] = object_id
response["data"] = {"id": object_id} # onMultiComplete and onComplete treat this differently. This is a temporary workaround
resps.append(response)
elif reqq.functionName == 'UserService.updateFeatureFrequencyTimestamp':
feature = reqq['params'][0]
commands.update_feature_frequency_timestamp(UID, feature)
resps.append(response)
elif reqq.functionName == 'UserService.publishUserAction':
action = reqq['params'][0]
params = reqq['params'][1]
commands.publish_user_actions(UID, action, params)
resps.append(response)
else:
resps.append(response)
assert len(resps) == len(reqs)
save_session(UID)
emsg = {
"serverTime": timestamp_now(),
"errorType": 0,
"data": resps
}
req = remoting.Response(emsg)
ev = remoting.Envelope(pyamf.AMF0)
ev[resp_msg.bodies[0][0]] = req
# print("[+] Response:", ev)
ret_body = remoting.encode(ev, strict=True, logger=True).getvalue()
return Response(ret_body, mimetype='application/x-amf')
@app.route("/sn_app_url/gifts.php", methods=['GET'])
def sn_app_url_gifts():
template = request.args.get("template")
ref = request.args.get("ref")
return "{}"
print (" [+] Running server...")
if __name__ == '__main__':
app.secret_key = os.urandom(24)
app.root_path = BASE_DIR
app.template_folder = TEMPLATES_DIR
app.static_folder = TEMPLATES_DIR
app.run(host=BIND_IP, port=BIND_PORT, debug=False, threaded=True)