-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
376 lines (326 loc) · 15 KB
/
Copy pathapp.py
File metadata and controls
376 lines (326 loc) · 15 KB
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
374
375
376
from flask import Flask, request, jsonify
from flask_cors import CORS
import json
import time
from datetime import datetime, timedelta
from Utilities.until import load_accounts
from Api.Account import get_garena_token, get_major_login
from Api.InGame import get_player_personal_show, get_player_stats, search_account_by_keyword
accounts = load_accounts()
app = Flask(__name__)
# Enable CORS for all origins on all routes
CORS(app)
@app.route('/get_search_account_by_keyword', methods=['GET'])
def get_search_account_by_keyword():
try:
# Get request parameters
region = request.args.get('server', 'IND').upper()
search_term = request.args.get('keyword')
# Validate keyword parameter
if not search_term:
return json.dumps({"error": "Keyword parameter is required"}, indent=2), 400, {'Content-Type': 'application/json; charset=utf-8'}
# Enforce minimum keyword length
if len(search_term.strip()) < 3:
return json.dumps({"error": "Keyword must be at least 3 characters long"}, indent=2), 400, {'Content-Type': 'application/json; charset=utf-8'}
# Validate server exists in accounts
if region not in accounts:
return json.dumps({"error": f"Invalid server: {region}"}, indent=2), 400, {'Content-Type': 'application/json; charset=utf-8'}
# Authenticate with Garena
auth_response = get_garena_token(accounts[region]['uid'], accounts[region]['password'])
if not auth_response or 'access_token' not in auth_response:
return json.dumps({"error": "Authentication failed"}, indent=2), 401, {'Content-Type': 'application/json; charset=utf-8'}
# Get major login credentials
login_response = get_major_login(auth_response["access_token"], auth_response["open_id"])
if not login_response or 'token' not in login_response:
return json.dumps({"error": "Major login failed"}, indent=2), 401, {'Content-Type': 'application/json; charset=utf-8'}
# Search for accounts
search_results = search_account_by_keyword(login_response["serverUrl"], login_response["token"], search_term)
# Return formatted response
formatted_response = json.dumps(search_results, indent=2, ensure_ascii=False)
return formatted_response, 200, {'Content-Type': 'application/json; charset=utf-8'}
except KeyError as e:
return json.dumps({"error": f"Missing configuration: {str(e)}"}, indent=2), 500, {'Content-Type': 'application/json; charset=utf-8'}
except Exception as e:
return json.dumps({"error": f"Internal server error: {str(e)}"}, indent=2), 500, {'Content-Type': 'application/json; charset=utf-8'}
@app.route('/get_player_stats', methods=['GET'])
def get_player_stat():
try:
# Get and validate parameters
server = request.args.get('server', 'IND').upper()
uid = request.args.get('uid')
gamemode = request.args.get('gamemode', 'br').lower()
matchmode = request.args.get('matchmode', 'CAREER').upper()
# Validate required parameters
if not uid:
return jsonify({
"success": False,
"error": "Missing required parameter",
"message": "UID parameter is required"
}), 400
if not uid.isdigit():
return jsonify({
"success": False,
"error": "Invalid UID",
"message": "UID must be a numeric value"
}), 400
# Validate server
if server not in accounts:
return jsonify({
"success": False,
"error": "Invalid server",
"message": f"Server '{server}' not found. Available servers: {list(accounts.keys())}"
}), 400
# Validate gamemode
if gamemode not in ['br', 'cs']:
return jsonify({
"success": False,
"error": "Invalid gamemode",
"message": "Gamemode must be 'br' or 'cs'"
}), 400
# Validate matchmode
if matchmode not in ['CAREER', 'NORMAL', 'RANKED']:
return jsonify({
"success": False,
"error": "Invalid matchmode",
"message": "Matchmode must be 'CAREER', 'NORMAL', or 'RANKED'"
}), 400
# Step 1: Get Garena token
try:
garena_token_result = get_garena_token(accounts[server]['uid'], accounts[server]['password'])
if not garena_token_result or 'access_token' not in garena_token_result:
return jsonify({
"success": False,
"error": "Garena authentication failed",
"message": "Failed to obtain Garena access token"
}), 401
except Exception as e:
return jsonify({
"success": False,
"error": "Garena authentication error",
"message": f"Failed to authenticate with Garena: {str(e)}"
}), 502
# Step 2: Get Major login
try:
major_login_result = get_major_login(garena_token_result["access_token"], garena_token_result["open_id"])
if not major_login_result or 'token' not in major_login_result:
return jsonify({
"success": False,
"error": "Major login failed",
"message": "Failed to obtain Major login token"
}), 401
except Exception as e:
return jsonify({
"success": False,
"error": "Major login error",
"message": f"Failed to login to Major: {str(e)}"
}), 502
# Step 3: Get player stats
try:
player_stats = get_player_stats(
major_login_result["token"],
major_login_result["serverUrl"],
gamemode,
uid,
matchmode
)
if not player_stats:
return jsonify({
"success": False,
"error": "No stats data",
"message": "No player statistics found for the given parameters"
}), 404
# Return formatted JSON response
return jsonify({
"success": True,
"data": player_stats,
"metadata": {
"server": server,
"uid": uid,
"gamemode": gamemode,
"matchmode": matchmode
}
}), 200
except ValueError as e:
return jsonify({
"success": False,
"error": "Invalid request parameters",
"message": str(e)
}), 400
except ConnectionError as e:
return jsonify({
"success": False,
"error": "Connection error",
"message": str(e)
}), 503
except ProtobufError as e:
return jsonify({
"success": False,
"error": "Data processing error",
"message": str(e)
}), 500
except APIError as e:
return jsonify({
"success": False,
"error": "External API error",
"message": str(e)
}), 502
except Exception as e:
return jsonify({
"success": False,
"error": "Stats retrieval error",
"message": f"Failed to retrieve player stats: {str(e)}"
}), 500
except Exception as e:
# Catch any unexpected errors
return jsonify({
"success": False,
"error": "Internal server error",
"message": "An unexpected error occurred while processing your request"
}), 500
@app.route('/get_player_personal_show', methods=['GET'])
def get_account_info():
try:
# Get parameters with defaults
server = request.args.get('server', 'IND').upper()
uid = request.args.get('uid')
need_gallery_info = request.args.get('need_gallery_info', False)
call_sign_src = request.args.get('call_sign_src', 7)
# Validate UID parameter - must be integer
if not uid:
response = {
"status": "error",
"error": "Missing UID",
"message": "Empty 'uid' parameter. Please provide a valid 'uid'.",
"code": "MISSING_UID"
}
return jsonify(response), 400, {'Content-Type': 'application/json; charset=utf-8'}
# Check if UID is a valid integer
try:
uid_int = int(uid)
# Additional validation for UID range if needed
if uid_int <= 0:
response = {
"status": "error",
"error": "Invalid UID",
"message": "UID must be a positive integer.",
"code": "INVALID_UID_RANGE"
}
return jsonify(response), 400, {'Content-Type': 'application/json; charset=utf-8'}
except (ValueError, TypeError):
response = {
"status": "error",
"error": "Invalid UID",
"message": "UID must be a valid integer.",
"code": "INVALID_UID_FORMAT"
}
return jsonify(response), 400, {'Content-Type': 'application/json; charset=utf-8'}
# Validate server parameter
if server not in accounts:
response = {
"status": "error",
"error": "Invalid Server",
"message": f"Server '{server}' not found. Available servers: {list(accounts.keys())}",
"available_servers": list(accounts.keys()),
"code": "SERVER_NOT_FOUND"
}
return jsonify(response), 400, {'Content-Type': 'application/json; charset=utf-8'}
# Validate need_gallery_info parameter
try:
if isinstance(need_gallery_info, str):
if need_gallery_info.lower() in ['true', '1', 'yes']:
need_gallery_info = True
elif need_gallery_info.lower() in ['false', '0', 'no']:
need_gallery_info = False
else:
raise ValueError("Invalid boolean value")
need_gallery_info = bool(need_gallery_info)
except (ValueError, TypeError):
response = {
"status": "error",
"error": "Invalid Parameter",
"message": "need_gallery_info must be a boolean value (true/false, 1/0).",
"code": "INVALID_GALLERY_PARAM"
}
return jsonify(response), 400, {'Content-Type': 'application/json; charset=utf-8'}
# Validate call_sign_src parameter
try:
call_sign_src_int = int(call_sign_src)
if call_sign_src_int < 0:
response = {
"status": "error",
"error": "Invalid Parameter",
"message": "call_sign_src must be a non-negative integer.",
"code": "INVALID_CALL_SIGN_SRC"
}
return jsonify(response), 400, {'Content-Type': 'application/json; charset=utf-8'}
except (ValueError, TypeError):
response = {
"status": "error",
"error": "Invalid Parameter",
"message": "call_sign_src must be a valid integer.",
"code": "INVALID_CALL_SIGN_FORMAT"
}
return jsonify(response), 400, {'Content-Type': 'application/json; charset=utf-8'}
# Check if server account credentials exist
if 'uid' not in accounts[server] or 'password' not in accounts[server]:
response = {
"status": "error",
"error": "Server Configuration Error",
"message": f"Server '{server}' is missing required credentials.",
"code": "SERVER_CONFIG_ERROR"
}
return jsonify(response), 500, {'Content-Type': 'application/json; charset=utf-8'}
# Step 1: Get Garena token
garena_token_result = get_garena_token(accounts[server]['uid'], accounts[server]['password'])
if not garena_token_result or 'access_token' not in garena_token_result or 'open_id' not in garena_token_result:
response = {
"status": "error",
"error": "Authentication Failed",
"message": "Failed to obtain Garena token. Invalid credentials or service unavailable.",
"code": "GARENA_AUTH_FAILED"
}
return jsonify(response), 401, {'Content-Type': 'application/json; charset=utf-8'}
# Step 2: Get major login
major_login_result = get_major_login(garena_token_result["access_token"], garena_token_result["open_id"])
if not major_login_result or 'serverUrl' not in major_login_result or 'token' not in major_login_result:
response = {
"status": "error",
"error": "Login Failed",
"message": "Failed to perform major login. Service unavailable.",
"code": "MAJOR_LOGIN_FAILED"
}
return jsonify(response), 401, {'Content-Type': 'application/json; charset=utf-8'}
# Step 3: Get player personal show data
player_personal_show_result = get_player_personal_show(
major_login_result["serverUrl"],
major_login_result["token"],
uid_int,
need_gallery_info,
call_sign_src_int
)
if not player_personal_show_result:
response = {
"status": "error",
"error": "Data Not Found",
"message": f"No player data found for UID: {uid_int}",
"code": "PLAYER_DATA_NOT_FOUND"
}
return jsonify(response), 404, {'Content-Type': 'application/json; charset=utf-8'}
# Success response
formatted_json = json.dumps(player_personal_show_result, indent=2, ensure_ascii=False)
return formatted_json, 200, {'Content-Type': 'application/json; charset=utf-8'}
except Exception as e:
# Log the unexpected error for debugging
print(f"Unexpected error in get_player_personal_show: {str(e)}")
print(f"Error type: {type(e).__name__}")
import traceback
print(f"Traceback: {traceback.format_exc()}")
response = {
"status": "error",
"error": "Internal Server Error",
"message": "An unexpected error occurred while processing your request.",
"code": "INTERNAL_SERVER_ERROR"
}
return jsonify(response), 500, {'Content-Type': 'application/json; charset=utf-8'}
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)