Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
523 lines (435 loc) · 19.9 KB
/
Copy pathmain.py
File metadata and controls
523 lines (435 loc) · 19.9 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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import httpx
import asyncio
from bs4 import BeautifulSoup
import re
import json
from typing import Optional, List, Dict, Any
import logging
from datetime import datetime, timedelta
import time
# Настройка логирования
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(
title="War Thunder Stats API",
description="API для получения статистики игроков War Thunder",
version="1.0.0"
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # В продакшене укажите конкретные домены
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Кэш для хранения данных
cache = {}
CACHE_DURATION = 300 # 5 минут
class WarThunderAPI:
def __init__(self):
self.session = httpx.AsyncClient(timeout=30.0)
self.base_urls = {
'ru': 'https://warthunder.com/ru/community/userinfo',
'en': 'https://warthunder.com/en/community/userinfo',
'de': 'https://warthunder.com/de/community/userinfo',
'fr': 'https://warthunder.com/fr/community/userinfo'
}
async def get_player_stats(self, username: str, region: str = 'en') -> Dict[str, Any]:
"""Получение статистики игрока"""
cache_key = f"{username}_{region}"
# Проверяем кэш
if cache_key in cache:
cached_data, timestamp = cache[cache_key]
if time.time() - timestamp < CACHE_DURATION:
return cached_data
try:
url = f"{self.base_urls[region]}?nick={username}"
response = await self.session.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Проверяем, существует ли игрок
error_div = soup.find('div', class_='error')
if error_div:
raise HTTPException(status_code=404, detail="Player not found")
# Парсим данные
stats = self._parse_player_page(soup, username)
# Кэшируем результат
cache[cache_key] = (stats, time.time())
return stats
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
raise HTTPException(status_code=404, detail="Player not found")
raise HTTPException(status_code=500, detail="Failed to fetch player data")
except Exception as e:
logger.error(f"Error fetching player data: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
def _parse_player_page(self, soup: BeautifulSoup, username: str) -> Dict[str, Any]:
"""Парсинг страницы игрока"""
stats = {
"username": username,
"general": {},
"aviation": {},
"tanks": {},
"fleet": {},
"achievements": [],
"clan": {},
"charts": {}
}
try:
# Общая информация
stats["general"] = self._parse_general_stats(soup)
# Статистика авиации
stats["aviation"] = self._parse_aviation_stats(soup)
# Статистика танков
stats["tanks"] = self._parse_tank_stats(soup)
# Статистика флота
stats["fleet"] = self._parse_fleet_stats(soup)
# Достижения
stats["achievements"] = self._parse_achievements(soup)
# Клан
stats["clan"] = self._parse_clan_info(soup)
# Графики
stats["charts"] = self._parse_charts(soup)
except Exception as e:
logger.error(f"Error parsing player page: {e}")
return stats
def _parse_general_stats(self, soup: BeautifulSoup) -> Dict[str, Any]:
"""Парсинг общей статистики"""
general = {
"level": 0,
"total_battles": 0,
"win_rate": 0.0,
"total_kills": 0,
"total_deaths": 0,
"kd_ratio": 0.0,
"total_score": 0,
"premium": False,
"registration_date": "",
"last_online": ""
}
try:
# Уровень
level_elem = soup.find('span', class_='level')
if level_elem:
general["level"] = int(level_elem.text.strip())
# Общие бои
battles_elem = soup.find('div', string=re.compile(r'Total battles', re.I))
if battles_elem:
battles_text = battles_elem.find_next('div').text.strip()
general["total_battles"] = int(re.sub(r'[^\d]', '', battles_text) or 0)
# Винрейт
winrate_elem = soup.find('div', string=re.compile(r'Victories', re.I))
if winrate_elem:
winrate_text = winrate_elem.find_next('div').text.strip()
general["win_rate"] = float(re.sub(r'[^\d.]', '', winrate_text) or 0)
# K/D
kd_elem = soup.find('div', string=re.compile(r'K/D', re.I))
if kd_elem:
kd_text = kd_elem.find_next('div').text.strip()
general["kd_ratio"] = float(re.sub(r'[^\d.]', '', kd_text) or 0)
except Exception as e:
logger.error(f"Error parsing general stats: {e}")
return general
def _parse_aviation_stats(self, soup: BeautifulSoup) -> Dict[str, Any]:
"""Парсинг статистики авиации"""
aviation = {
"battles": 0,
"wins": 0,
"losses": 0,
"win_rate": 0.0,
"kills": 0,
"deaths": 0,
"kd_ratio": 0.0,
"air_kills": 0,
"ground_kills": 0,
"bombing_kills": 0,
"accuracy": 0.0
}
try:
# Ищем секцию авиации
aviation_section = soup.find('div', string=re.compile(r'Aviation', re.I))
if aviation_section:
section = aviation_section.find_parent('div')
if section:
# Бои
battles_elem = section.find('div', string=re.compile(r'Battles', re.I))
if battles_elem:
battles_text = battles_elem.find_next('div').text.strip()
aviation["battles"] = int(re.sub(r'[^\d]', '', battles_text) or 0)
# Убийства
kills_elem = section.find('div', string=re.compile(r'Kills', re.I))
if kills_elem:
kills_text = kills_elem.find_next('div').text.strip()
aviation["kills"] = int(re.sub(r'[^\d]', '', kills_text) or 0)
# Смерти
deaths_elem = section.find('div', string=re.compile(r'Deaths', re.I))
if deaths_elem:
deaths_text = deaths_elem.find_next('div').text.strip()
aviation["deaths"] = int(re.sub(r'[^\d]', '', deaths_text) or 0)
if aviation["deaths"] > 0:
aviation["kd_ratio"] = round(aviation["kills"] / aviation["deaths"], 2)
if aviation["battles"] > 0:
aviation["win_rate"] = round((aviation["wins"] / aviation["battles"]) * 100, 1)
except Exception as e:
logger.error(f"Error parsing aviation stats: {e}")
return aviation
def _parse_tank_stats(self, soup: BeautifulSoup) -> Dict[str, Any]:
"""Парсинг статистики танков"""
tanks = {
"battles": 0,
"wins": 0,
"losses": 0,
"win_rate": 0.0,
"kills": 0,
"deaths": 0,
"kd_ratio": 0.0,
"ground_kills": 0,
"air_kills": 0,
"capture_points": 0,
"accuracy": 0.0
}
try:
# Ищем секцию танков
tanks_section = soup.find('div', string=re.compile(r'Ground Forces', re.I))
if tanks_section:
section = tanks_section.find_parent('div')
if section:
# Бои
battles_elem = section.find('div', string=re.compile(r'Battles', re.I))
if battles_elem:
battles_text = battles_elem.find_next('div').text.strip()
tanks["battles"] = int(re.sub(r'[^\d]', '', battles_text) or 0)
# Убийства
kills_elem = section.find('div', string=re.compile(r'Kills', re.I))
if kills_elem:
kills_text = kills_elem.find_next('div').text.strip()
tanks["kills"] = int(re.sub(r'[^\d]', '', kills_text) or 0)
# Смерти
deaths_elem = section.find('div', string=re.compile(r'Deaths', re.I))
if deaths_elem:
deaths_text = deaths_elem.find_next('div').text.strip()
tanks["deaths"] = int(re.sub(r'[^\d]', '', deaths_text) or 0)
if tanks["deaths"] > 0:
tanks["kd_ratio"] = round(tanks["kills"] / tanks["deaths"], 2)
if tanks["battles"] > 0:
tanks["win_rate"] = round((tanks["wins"] / tanks["battles"]) * 100, 1)
except Exception as e:
logger.error(f"Error parsing tank stats: {e}")
return tanks
def _parse_fleet_stats(self, soup: BeautifulSoup) -> Dict[str, Any]:
"""Парсинг статистики флота"""
fleet = {
"battles": 0,
"wins": 0,
"losses": 0,
"win_rate": 0.0,
"kills": 0,
"deaths": 0,
"kd_ratio": 0.0,
"ship_kills": 0,
"air_kills": 0,
"torpedo_kills": 0,
"accuracy": 0.0
}
try:
# Ищем секцию флота
fleet_section = soup.find('div', string=re.compile(r'Fleet', re.I))
if fleet_section:
section = fleet_section.find_parent('div')
if section:
# Бои
battles_elem = section.find('div', string=re.compile(r'Battles', re.I))
if battles_elem:
battles_text = battles_elem.find_next('div').text.strip()
fleet["battles"] = int(re.sub(r'[^\d]', '', battles_text) or 0)
# Убийства
kills_elem = section.find('div', string=re.compile(r'Kills', re.I))
if kills_elem:
kills_text = kills_elem.find_next('div').text.strip()
fleet["kills"] = int(re.sub(r'[^\d]', '', kills_text) or 0)
# Смерти
deaths_elem = section.find('div', string=re.compile(r'Deaths', re.I))
if deaths_elem:
deaths_text = deaths_elem.find_next('div').text.strip()
fleet["deaths"] = int(re.sub(r'[^\d]', '', deaths_text) or 0)
if fleet["deaths"] > 0:
fleet["kd_ratio"] = round(fleet["kills"] / fleet["deaths"], 2)
if fleet["battles"] > 0:
fleet["win_rate"] = round((fleet["wins"] / fleet["battles"]) * 100, 1)
except Exception as e:
logger.error(f"Error parsing fleet stats: {e}")
return fleet
def _parse_achievements(self, soup: BeautifulSoup) -> List[Dict[str, Any]]:
"""Парсинг достижений"""
achievements = []
try:
# Ищем секцию достижений
achievements_section = soup.find('div', string=re.compile(r'Achievements', re.I))
if achievements_section:
achievement_items = achievements_section.find_all('div', class_='achievement')
for item in achievement_items[:10]: # Ограничиваем 10 достижениями
achievement = {
"name": item.get('title', ''),
"description": item.get('data-description', ''),
"icon": item.find('img')['src'] if item.find('img') else '',
"unlocked": True
}
achievements.append(achievement)
except Exception as e:
logger.error(f"Error parsing achievements: {e}")
return achievements
def _parse_clan_info(self, soup: BeautifulSoup) -> Dict[str, Any]:
"""Парсинг информации о клане"""
clan = {
"name": "",
"tag": "",
"role": "",
"member_since": "",
"clan_level": 0
}
try:
# Ищем информацию о клане
clan_elem = soup.find('div', class_='clan-info')
if clan_elem:
clan_name = clan_elem.find('div', class_='clan-name')
if clan_name:
clan["name"] = clan_name.text.strip()
clan_tag = clan_elem.find('div', class_='clan-tag')
if clan_tag:
clan["tag"] = clan_tag.text.strip()
except Exception as e:
logger.error(f"Error parsing clan info: {e}")
return clan
def _parse_charts(self, soup: BeautifulSoup) -> Dict[str, Any]:
"""Парсинг графиков"""
charts = {
"performance_over_time": [],
"vehicle_usage": [],
"nation_stats": []
}
try:
# Здесь можно добавить парсинг графиков, если они есть на странице
# Пока возвращаем пустые данные
pass
except Exception as e:
logger.error(f"Error parsing charts: {e}")
return charts
async def get_top_players(self, region: str = 'en', limit: int = 100) -> List[Dict[str, Any]]:
"""Получение топ игроков"""
cache_key = f"top_players_{region}_{limit}"
# Проверяем кэш
if cache_key in cache:
cached_data, timestamp = cache[cache_key]
if time.time() - timestamp < CACHE_DURATION:
return cached_data
try:
# Здесь можно добавить парсинг топ игроков
# Пока возвращаем демо данные
top_players = []
for i in range(min(limit, 10)):
player = {
"rank": i + 1,
"username": f"TopPlayer{i+1}",
"level": 100 - i * 5,
"total_battles": 10000 - i * 500,
"win_rate": 65.0 - i * 2,
"kd_ratio": 3.5 - i * 0.2,
"total_score": 1000000 - i * 50000
}
top_players.append(player)
# Кэшируем результат
cache[cache_key] = (top_players, time.time())
return top_players
except Exception as e:
logger.error(f"Error fetching top players: {e}")
return []
async def close(self):
"""Закрытие сессии"""
await self.session.aclose()
# Создаем экземпляр API
wt_api = WarThunderAPI()
@app.on_event("shutdown")
async def shutdown_event():
"""Закрытие соединений при выключении"""
await wt_api.close()
@app.get("/")
async def root():
"""Корневой эндпоинт"""
return {
"message": "War Thunder Stats API",
"version": "1.0.0",
"endpoints": {
"/player/{username}": "Get player statistics",
"/top": "Get top players",
"/health": "Health check"
}
}
@app.get("/health")
async def health_check():
"""Проверка здоровья API"""
return {"status": "healthy", "timestamp": datetime.now().isoformat()}
@app.get("/player/{username}")
async def get_player_stats(
username: str,
region: str = Query('en', description="Region: en, ru, de, fr")
):
"""Получение статистики игрока"""
if region not in ['en', 'ru', 'de', 'fr']:
raise HTTPException(status_code=400, detail="Invalid region")
try:
stats = await wt_api.get_player_stats(username, region)
return JSONResponse(content=stats)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error in get_player_stats: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
@app.get("/top")
async def get_top_players(
region: str = Query('en', description="Region: en, ru, de, fr"),
limit: int = Query(100, ge=1, le=1000, description="Number of players to return")
):
"""Получение топ игроков"""
if region not in ['en', 'ru', 'de', 'fr']:
raise HTTPException(status_code=400, detail="Invalid region")
try:
players = await wt_api.get_top_players(region, limit)
return JSONResponse(content={"players": players, "total": len(players)})
except Exception as e:
logger.error(f"Error in get_top_players: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
@app.get("/compare")
async def compare_players(
player1: str = Query(..., description="First player username"),
player2: str = Query(..., description="Second player username"),
region: str = Query('en', description="Region: en, ru, de, fr")
):
"""Сравнение двух игроков"""
if region not in ['en', 'ru', 'de', 'fr']:
raise HTTPException(status_code=400, detail="Invalid region")
try:
stats1 = await wt_api.get_player_stats(player1, region)
stats2 = await wt_api.get_player_stats(player2, region)
comparison = {
"player1": stats1,
"player2": stats2,
"comparison": {
"level_diff": stats1["general"]["level"] - stats2["general"]["level"],
"battles_diff": stats1["general"]["total_battles"] - stats2["general"]["total_battles"],
"win_rate_diff": stats1["general"]["win_rate"] - stats2["general"]["win_rate"],
"kd_ratio_diff": stats1["general"]["kd_ratio"] - stats2["general"]["kd_ratio"]
}
}
return JSONResponse(content=comparison)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error in compare_players: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)