foxapi 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
foxapi/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .foxapi import FoxAPI
foxapi/foxapi.py ADDED
@@ -0,0 +1,613 @@
1
+ try:
2
+ from .utils import HexagonObject, FoxAPIError, HexagonError, EndpointError, APIResponse
3
+ except ImportError:
4
+ from utils import HexagonObject, FoxAPIError, HexagonError, EndpointError, APIResponse
5
+
6
+ from pathlib import Path
7
+ from PIL import Image
8
+ import threading
9
+ import requests
10
+ import aiohttp
11
+ import asyncio
12
+ import math
13
+ import time
14
+ import os
15
+
16
+
17
+ # hexagon shape (png) : 1024 x 888
18
+ # icon shape (png) : 48 x 48
19
+ # documentation at https://foxhole.fandom.com/wiki/War_API
20
+
21
+
22
+ class FoxAPI():
23
+ def __init__(self, safe_mode: bool = True):
24
+ self.base_api: str = "https://war-service-live.foxholeservices.com/api/worldconquest"
25
+ self.session: requests.Session = requests.Session()
26
+
27
+ self._img_dir: str = os.path.join(Path(__file__).parent, "Images")
28
+
29
+ self.cache: dict = {}
30
+ self.etag: dict = {}
31
+
32
+ self._refresh: int = 30
33
+
34
+ self._death_rate_w : dict = {}
35
+ self._death_rate_c : dict = {}
36
+
37
+ self._cpt_rate_total: int = 3600 // self._refresh
38
+ self._cpt_rate: int = 0
39
+
40
+ self._safe_mode: bool = safe_mode
41
+
42
+ self.available_hexagons: list = self.get_maps_sync()
43
+ self._available_hexagons: list = [h.lower() for h in self.available_hexagons]
44
+ self._nb_hex: int = len(self.available_hexagons)
45
+
46
+ self._valid_endpoints: list = self._get_valid_endpoints()
47
+
48
+ self._run: bool = False
49
+
50
+ self._to_call: dict = {}
51
+ self._hex_call: list = []
52
+ self.waiting_list: list = []
53
+
54
+ self._icon_size: tuple = (24, 24)
55
+
56
+ def close_session(self):
57
+ self.session.close()
58
+
59
+ """
60
+ REQUESTS SYNC
61
+ """
62
+
63
+ def get_data_sync(self, endpoint: str, etag: str = None, use_cache: bool = False):
64
+ hexagon: str = self._retrieve_hexagon_from_endpoint(endpoint)
65
+
66
+ if use_cache == True:
67
+ cached_data = self.cache.get(endpoint)
68
+
69
+ if cached_data is not None:
70
+ return APIResponse(headers={}, json=cached_data, status_code=None, hexagon=hexagon, is_cache=True)
71
+
72
+ headers: dict = {"If-None-Match": etag} if etag is not None else {"If-None-Match": self.etag.get(endpoint)}
73
+
74
+ if self.etag.get(endpoint) is None or etag == "":
75
+ headers: dict = {"etag": ""}
76
+
77
+ with self.session.get(f"{self.base_api}{endpoint}", headers=headers) as data:
78
+ self.etag[endpoint]: str = data.headers.get("ETag", self.etag.get(endpoint))
79
+
80
+ if data.status_code == 200:
81
+ self.cache[endpoint] = data.json()
82
+ return APIResponse(headers=data.headers, json=data.json(), status_code=data.status_code, hexagon=hexagon, is_cache=False)
83
+
84
+ elif data.status_code == 304:
85
+ return APIResponse(headers=data.headers, json=self.cache.get(endpoint), status_code=data.status_code, hexagon=hexagon, is_cache=True)
86
+
87
+ def get_headers_sync(self, endpoint: str):
88
+ with self.session.head(f"{self.base_api}{endpoint}") as data:
89
+ return data
90
+
91
+ """
92
+ REQUESTS ASYNC
93
+ """
94
+
95
+ async def get_data(self, endpoint: str, session: aiohttp.ClientSession = None, etag: str = None, use_cache: bool = False):
96
+ hexagon: str = self._retrieve_hexagon_from_endpoint(endpoint)
97
+
98
+ if use_cache == True:
99
+ cached_data = self.cache.get(endpoint)
100
+
101
+ if cached_data is not None:
102
+ return APIResponse(headers={}, json=cached_data, status_code=None, hexagon=hexagon, is_cache=True)
103
+
104
+ headers: dict = {"If-None-Match": etag} if etag is not None else {"If-None-Match": self.etag.get(endpoint)}
105
+
106
+ if self.etag.get(endpoint) is None or etag == "":
107
+ headers: dict = {"etag": ""}
108
+
109
+ if session is None:
110
+ async with aiohttp.ClientSession() as session:
111
+ async with session.get(f"{self.base_api}{endpoint}", headers=headers) as data:
112
+ self.etag[endpoint]: str = data.headers.get("ETag", self.etag.get(endpoint))
113
+
114
+ if data.status == 200:
115
+ data_json = await data.json()
116
+ self.cache[endpoint] = data_json
117
+ return APIResponse(headers=data.headers, json=data_json, status_code=data.status, hexagon=hexagon, is_cache=False)
118
+
119
+ elif data.status == 304:
120
+ return APIResponse(headers=data.headers, json=self.cache.get(endpoint), status_code=data.status, hexagon=hexagon, is_cache=True)
121
+
122
+ else:
123
+ async with session.get(f"{self.base_api}{endpoint}", headers=headers) as data:
124
+ self.etag[endpoint]: str = data.headers.get("ETag", self.etag.get(endpoint))
125
+
126
+ if data.status == 200:
127
+ data_json = await data.json()
128
+ self.cache[endpoint] = data_json
129
+ return APIResponse(json=data_json, status_code=data.status, hexagon=hexagon, is_cache=False)
130
+
131
+ elif data.status == 304:
132
+ return APIResponse(json=self.cache.get(endpoint), status_code=data.status, hexagon=hexagon, is_cache=True)
133
+
134
+ async def get_headers(self, endpoint: str):
135
+ async with aiohttp.ClientSession() as session:
136
+ async with session.head(f"{self.base_api}{endpoint}") as data:
137
+ return data
138
+
139
+ """
140
+ TOOLS
141
+ """
142
+
143
+ def _get_valid_endpoints(self):
144
+ valid: list = ["/war", "/maps"]
145
+
146
+ for hexagon in self.available_hexagons:
147
+ valid.append(f"/maps/{hexagon}/static")
148
+ valid.append(f"/maps/{hexagon}/dynamic/public")
149
+ valid.append(f"/warReport/{hexagon}")
150
+
151
+ return valid
152
+
153
+ def _is_valid_endpoint(self, endpoint: str):
154
+ return endpoint in self._valid_endpoints
155
+
156
+ def _is_valid_hexagon(self, hexagon: str):
157
+ return hexagon in self.available_hexagons
158
+
159
+ def _format_hexagon(self, hexagon: str):
160
+ hexagon: str = hexagon.lower().strip().replace(" ", "")
161
+
162
+ for i in range(self._nb_hex):
163
+ if hexagon in self._available_hexagons[i]:
164
+ return self.available_hexagons[i]
165
+
166
+ return None
167
+
168
+ def _retrieve_hexagon_from_endpoint(self, endpoint: str):
169
+ if endpoint.startswith("/"):
170
+ endpoint = endpoint[1:]
171
+
172
+ if "maps/" in endpoint or "warReport/" in endpoint:
173
+ return endpoint.split("/")[1]
174
+
175
+ def _format_endpoint(self, endpoint: str):
176
+ if "maps/" in endpoint or "warReport/" in endpoint:
177
+ old_hexa: str = self._retrieve_hexagon_from_endpoint(endpoint)
178
+ hexagon: str = self._format_hexagon(old_hexa)
179
+ endpoint: str = endpoint.replace(old_hexa, hexagon)
180
+
181
+ return endpoint
182
+
183
+ def calc_distance(self, x1: float, y1: float, x2: float, y2: float):
184
+ return math.sqrt((abs(x1 - x2) ** 2) + (abs(y1 - y2) ** 2))
185
+
186
+ def load_hexagon_map(self, hexagon: str):
187
+ if self._safe_mode:
188
+ hexagon: str = self._format_hexagon(hexagon)
189
+
190
+ img_path: str = os.path.join(self._img_dir, "MapsHex", f"Map{hexagon}.png")
191
+ return Image.open(img_path).convert("RGBA")
192
+
193
+ """
194
+ ASYNC METHODS
195
+ """
196
+
197
+ async def get_maps(self, use_cache: bool = True):
198
+ data = await self.get_data(endpoint="/maps", use_cache=use_cache)
199
+ return data.json
200
+
201
+ async def get_war(self, use_cache: bool = False):
202
+ data = await self.get_data(endpoint="/war", use_cache=use_cache)
203
+ return data.json
204
+
205
+ async def get_static(self, hexagon: str, use_cache: bool = False):
206
+ if self._safe_mode:
207
+ hexagon: str = self._format_hexagon(hexagon)
208
+
209
+ data = await self.get_data(endpoint=f"/maps/{hexagon}/static", use_cache=use_cache)
210
+ return data.json
211
+
212
+ async def get_dynamic(self, hexagon: str, use_cache: bool = False):
213
+ if self._safe_mode:
214
+ hexagon: str = self._format_hexagon(hexagon)
215
+
216
+ data = await self.get_data(endpoint=f"/maps/{hexagon}/dynamic/public", use_cache=use_cache)
217
+ return data.json
218
+
219
+ async def get_war_report(self, hexagon: str, use_cache: bool = False):
220
+ if self._safe_mode:
221
+ hexagon: str = self._format_hexagon(hexagon)
222
+
223
+ data = await self.get_data(endpoint=f"/warReport/{hexagon}", use_cache=use_cache)
224
+ return data.json
225
+
226
+ """
227
+ ADDITIONAL ASYNC METHODS
228
+ """
229
+
230
+ async def get_captured_towns(self, hexagon: str = None, dynamic: dict = None, static: dict = None):
231
+ if hexagon is not None and static is None and dynamic is None:
232
+ static: dict = await self.get_static(hexagon, use_cache=True)
233
+ dynamic: dict = await self.get_dynamic(hexagon)
234
+
235
+ if static is None or dynamic is None:
236
+ raise FoxAPIError("Please pass the required parameters (static and dynamic or hexagon)")
237
+
238
+ captured_towns: dict = {}
239
+ icons: list = [45, 46, 47, 56, 57, 58] # Town halls and relics
240
+
241
+ for s in static['mapTextItems']:
242
+ deltas: list = []
243
+ faction: list = []
244
+
245
+ if s['mapMarkerType'] == 'Major':
246
+ for d in dynamic['mapItems']:
247
+ if d['iconType'] in icons:
248
+ faction.append(d['teamId'])
249
+ deltas.append(self.calc_distance(s['x'], s['y'], d['x'], d['y']))
250
+
251
+ captured_towns[s['text']]: str = faction[deltas.index(min(deltas))]
252
+
253
+ return captured_towns
254
+
255
+ async def make_map_png(self, hexagon: str, dynamic: dict = None, static: dict = None):
256
+ if dynamic is None:
257
+ dynamic: dict = await self.get_dynamic(hexagon)
258
+
259
+ if dynamic is None:
260
+ raise FoxAPIError("Please pass the required parameters (hexagon or dynamic (static is optional))")
261
+
262
+ img1 = self.load_hexagon_map(hexagon)
263
+ icon_size: tuple = self._icon_size
264
+
265
+ for data in dynamic["mapItems"]:
266
+ image: str = data['iconType']
267
+ team: str = data["teamId"].strip()
268
+
269
+ try:
270
+ img_path: str = os.path.join(self._img_dir, "MapIcons", f"{image}{team}.png")
271
+ img2 = Image.open(img_path).convert("RGBA").resize(icon_size)
272
+ except Exception:
273
+ try:
274
+ img_path: str = os.path.join(self._img_dir, "MapIcons", f"{image}.png")
275
+ img2 = Image.open(img_path).convert("RGBA").resize(icon_size)
276
+ except Exception:
277
+ continue
278
+
279
+ img1.paste(img2, (int(data["x"] * 1024), int(data["y"] * 888)), mask=img2)
280
+
281
+ return img1
282
+
283
+ async def calculate_death_rate(self, hexagon: str = None, war_report: dict = None):
284
+ if self._safe_mode:
285
+ hexagon: str = self._format_hexagon(hexagon=hexagon)
286
+
287
+ if war_report is None:
288
+ war_report: dict = await self.get_war_report(hexagon)
289
+
290
+ if war_report is None:
291
+ raise FoxAPIError("Please pass the required parameters (hexagon or war_report)")
292
+
293
+ war_c: int = war_report['colonialCasualties']
294
+ war_w: int = war_report['wardenCasualties']
295
+
296
+ if self._cpt_rate > self._cpt_rate_total or not self._death_rate_c.get(hexagon):
297
+ self._death_rate_c[hexagon]: int = war_c
298
+ self._death_rate_w[hexagon]: int = war_w
299
+ self._cpt_rate: int = 0
300
+
301
+ return {"colonials": war_c - self._death_rate_c[hexagon], "wardens": war_w - self._death_rate_w[hexagon], "hexagon": hexagon}
302
+
303
+ async def get_hexagon_data(self, hexagon: str, use_cache: bool = False):
304
+ if self._safe_mode:
305
+ hexagon: str = self._format_hexagon(hexagon=hexagon)
306
+
307
+ war_report: dict = await self.get_war_report(hexagon=hexagon, use_cache=use_cache)
308
+ static: dict = await self.get_static(hexagon=hexagon, use_cache=use_cache)
309
+ dynamic: dict = await self.get_dynamic(hexagon=hexagon, use_cache=use_cache)
310
+
311
+ captured_towns: dict = await self.get_captured_towns(dynamic=dynamic, static=static)
312
+ casualty_rate: dict = await self.calculate_death_rate(hexagon=hexagon, war_report=war_report)
313
+ image = await self.make_map_png(hexagon=hexagon, dynamic=dynamic, static=static)
314
+
315
+ return HexagonObject(hexagon=hexagon, war_report=war_report, static=static, dynamic=dynamic, captured_towns=captured_towns, casualty_rate=casualty_rate, image=image)
316
+
317
+ """
318
+ SYNC METHODS
319
+ """
320
+
321
+ def get_maps_sync(self, use_cache: bool = True):
322
+ return self.get_data_sync(endpoint="/maps", use_cache=use_cache).json
323
+
324
+ def get_war_sync(self, use_cache: bool = False):
325
+ return self.get_data_sync(endpoint="/war", use_cache=use_cache).json
326
+
327
+ def get_static_sync(self, hexagon: str, use_cache: bool = False):
328
+ if self._safe_mode:
329
+ hexagon: str = self._format_hexagon(hexagon)
330
+
331
+ return self.get_data_sync(endpoint=f"/maps/{hexagon}/static", use_cache=use_cache).json
332
+
333
+ def get_dynamic_sync(self, hexagon: str, use_cache: bool = False):
334
+ if self._safe_mode:
335
+ hexagon: str = self._format_hexagon(hexagon)
336
+
337
+ return self.get_data_sync(endpoint=f"/maps/{hexagon}/dynamic/public", use_cache=use_cache).json
338
+
339
+ def get_war_report_sync(self, hexagon: str, use_cache: bool = False):
340
+ if self._safe_mode:
341
+ hexagon: str = self._format_hexagon(hexagon)
342
+
343
+ return self.get_data_sync(endpoint=f"/warReport/{hexagon}", use_cache=use_cache).json
344
+
345
+ """
346
+ ADDITIONAL SYNC METHODS
347
+ """
348
+
349
+ def get_captured_towns_sync(self, hexagon: str = None, dynamic: dict = None, static: dict = None):
350
+ if hexagon is not None and static is None and dynamic is None:
351
+ static: dict = self.get_static_sync(hexagon, use_cache=True)
352
+ dynamic: dict = self.get_dynamic_sync(hexagon)
353
+
354
+ if static is None or dynamic is None:
355
+ raise FoxAPIError("Please pass the required parameters (static and dynamic or hexagon)")
356
+
357
+ captured_towns: dict = {}
358
+ icons: list = [45, 46, 47, 56, 57, 58] # Town halls and relics
359
+
360
+ for s in static['mapTextItems']:
361
+ deltas: list = []
362
+ faction: list = []
363
+
364
+ if s['mapMarkerType'] == 'Major':
365
+ for d in dynamic['mapItems']:
366
+ if d['iconType'] in icons:
367
+ faction.append(d['teamId'])
368
+ deltas.append(self.calc_distance(s['x'], s['y'], d['x'], d['y']))
369
+
370
+ captured_towns[s['text']]: str = faction[deltas.index(min(deltas))]
371
+
372
+ return captured_towns
373
+
374
+ def make_map_png_sync(self, hexagon: str, dynamic: dict = None, static: dict = None):
375
+ if dynamic is None:
376
+ dynamic: dict = self.get_dynamic_sync(hexagon)
377
+
378
+ if dynamic is None:
379
+ raise FoxAPIError("Please pass the required parameters (hexagon or dynamic (static is optional))")
380
+
381
+ img1 = self.load_hexagon_map(hexagon)
382
+ icon_size: tuple = self._icon_size
383
+
384
+ for data in dynamic["mapItems"]:
385
+ image: str = data['iconType']
386
+ team: str = data["teamId"].strip()
387
+
388
+ try:
389
+ img_path: str = os.path.join(self._img_dir, "MapIcons", f"{image}{team}.png")
390
+ img2 = Image.open(img_path).convert("RGBA").resize(icon_size)
391
+ except Exception:
392
+ try:
393
+ img_path: str = os.path.join(self._img_dir, "MapIcons", f"{image}.png")
394
+ img2 = Image.open(img_path).convert("RGBA").resize(icon_size)
395
+ except Exception:
396
+ continue
397
+
398
+ img1.paste(img2, (int(data["x"] * 1024), int(data["y"] * 888)), mask=img2)
399
+
400
+ return img1
401
+
402
+ def calculate_death_rate_sync(self, hexagon: str = None, war_report: dict = None):
403
+ if self._safe_mode:
404
+ hexagon: str = self._format_hexagon(hexagon=hexagon)
405
+
406
+ if war_report is None:
407
+ war_report: dict = self.get_war_report(hexagon)
408
+
409
+ if war_report is None:
410
+ raise FoxAPIError("Please pass the required parameters (hexagon or war_report)")
411
+
412
+ war_c: int = war_report['colonialCasualties']
413
+ war_w: int = war_report['wardenCasualties']
414
+
415
+ dph_c: int = war_c
416
+ dph_w: int = war_w
417
+
418
+ if self._cpt_rate > self._cpt_rate_total or not self._death_rate_c.get(hexagon):
419
+ self._death_rate_c[hexagon]: int = war_c
420
+ self._death_rate_w[hexagon]: int = war_w
421
+ self._cpt_rate: int = 0
422
+
423
+ return {"colonials": dph_c - self._death_rate_c[hexagon], "wardens": dph_w - self._death_rate_w[hexagon], "hexagon": hexagon}
424
+
425
+ def get_hexagon_data_sync(self, hexagon: str, use_cache: bool = False):
426
+ if self._safe_mode:
427
+ hexagon: str = self._format_hexagon(hexagon=hexagon)
428
+
429
+ war_report: dict = self.get_war_report_sync(hexagon=hexagon, use_cache=use_cache)
430
+ static: dict = self.get_static_sync(hexagon=hexagon, use_cache=use_cache)
431
+ dynamic: dict = self.get_dynamic_sync(hexagon=hexagon, use_cache=use_cache)
432
+
433
+ captured_towns: dict = self.get_captured_towns_sync(dynamic=dynamic, static=static)
434
+ casualty_rate: dict = self.calculate_death_rate_sync(hexagon=hexagon, war_report=war_report)
435
+ image = self.make_map_png_sync(hexagon=hexagon, dynamic=dynamic, static=static)
436
+
437
+ return HexagonObject(hexagon=hexagon, war_report=war_report, static=static, dynamic=dynamic, captured_towns=captured_towns, casualty_rate=casualty_rate, image=image)
438
+
439
+ """
440
+ CRAWLER ASYNC
441
+ """
442
+
443
+ async def _litsener(self):
444
+ await asyncio.sleep(.1)
445
+
446
+ while self._run:
447
+ for url, callback in self._to_call.items():
448
+ data = self.get_data_sync(endpoint=url)
449
+
450
+ if data.is_cache == False:
451
+ answer: dict = data.json
452
+
453
+ if url in self._hex_call:
454
+ answer: HexagonObject = self.get_hexagon_data_sync(hexagon=data.hexagon, use_cache=True)
455
+
456
+ self.waiting_list.append([callback, answer])
457
+
458
+ await self.run_task()
459
+ self._cpt_rate += 1
460
+ await asyncio.sleep(self._refresh)
461
+
462
+ """
463
+ CRAWLER SYNC
464
+ """
465
+
466
+ def _litsener_sync(self):
467
+ time.sleep(.1)
468
+
469
+ while self._run:
470
+ for url, callback in self._to_call.items():
471
+ data: int = self.get_data_sync(endpoint=url)
472
+
473
+ if data.is_cache == False:
474
+ answer: dict = data.json
475
+
476
+ if url in self._hex_call:
477
+ answer: HexagonObject = self.get_hexagon_data_sync(hexagon=data.hexagon, use_cache=True)
478
+
479
+ callback(answer)
480
+
481
+ self._cpt_rate += 1
482
+ time.sleep(self._refresh)
483
+
484
+ def _check_litsener(self, run_async: bool = True):
485
+ if not self._run:
486
+ self._run: bool = True
487
+ # threading.Thread(target=self._litsener).start()
488
+ if run_async:
489
+ self.start_async_thread(self._litsener())
490
+ else:
491
+ threading.Thread(target=self._litsener_sync).start()
492
+ # threading.Thread(target=self.start_async_thread).start()
493
+
494
+ """
495
+ ASYNC TOOLS
496
+ """
497
+ def add_task(self, function: callable, args: list = "no_args"):
498
+ self.waiting_list.append([function, args])
499
+
500
+ async def run_task(self):
501
+ tasks: list = []
502
+ answers: list = []
503
+
504
+ for function, args in self.waiting_list:
505
+ if args == "no_args":
506
+ tasks.append([asyncio.create_task(function()), function, args])
507
+
508
+ elif isinstance(args, list):
509
+ tasks.append([asyncio.create_task(function(*args)), function, args])
510
+
511
+ elif isinstance(args, dict):
512
+ tasks.append([asyncio.create_task(function(**args)), function, args])
513
+
514
+ else:
515
+ tasks.append([asyncio.create_task(function(args)), function, args])
516
+
517
+ for task, function, args in tasks:
518
+ answers.append({"result": await task, "function": function, "args": args})
519
+
520
+ tasks.clear()
521
+ self.waiting_list.clear()
522
+ self.waiting_list: list = []
523
+ return answers
524
+
525
+ def run_task_sync(self, thread: bool = False):
526
+ if thread:
527
+ threading.Thread(target=self._exec).start()
528
+ else:
529
+ return asyncio.run(self.run_task())
530
+
531
+ def _exec(self):
532
+ return asyncio.run(self.run_task())
533
+
534
+ def start_async_thread(self, awaitable):
535
+ loop = asyncio.new_event_loop()
536
+ asyncio.set_event_loop(loop)
537
+ threading.Thread(target=loop.run_forever).start()
538
+ asyncio.run_coroutine_threadsafe(awaitable, loop)
539
+ return loop
540
+
541
+ def stop_async_thread(self, loop):
542
+ loop.call_soon_threadsafe(loop.stop)
543
+
544
+ """
545
+ EVENT WRAPPER
546
+ """
547
+
548
+ def on_api_update(self, callback: callable = None, endpoints: list = None):
549
+ if (isinstance(callback, str) or isinstance(callback, list)) and endpoints is None:
550
+ endpoints: list = callback
551
+ callback: callable = None
552
+
553
+ if endpoints == "all" or endpoints == ["all"]:
554
+ endpoints: list = self._valid_endpoints
555
+
556
+ elif isinstance(endpoints, str):
557
+ endpoints: list = [endpoints]
558
+
559
+ if self._safe_mode:
560
+ for i in range(len(endpoints)):
561
+ endpoints[i]: str = self._format_endpoint(endpoints[i])
562
+
563
+ for i in range(len(endpoints)):
564
+ if not self._is_valid_endpoint(endpoints[i]):
565
+ raise EndpointError(f"{endpoints[i]} not valid! Please enter a valid endpoint (FoxAPI._valid_endpoints)")
566
+
567
+ def add_debug(func):
568
+ self._check_litsener(asyncio.iscoroutinefunction(func))
569
+
570
+ for endpoint in endpoints:
571
+ self._to_call[endpoint]: callable = func
572
+
573
+ return func
574
+
575
+ if callable(callback):
576
+ return add_debug(callback)
577
+
578
+ return add_debug
579
+
580
+ def on_hexagon_update(self, callback: callable = "all", hexagons: list = None):
581
+ if (isinstance(callback, str) or isinstance(callback, list)) and hexagons is None:
582
+ hexagons: str = callback
583
+ callback: callable = None
584
+
585
+ if hexagons == "all" or hexagons == ["all"]:
586
+ hexagons: list = self.available_hexagons
587
+
588
+ if isinstance(hexagons, str):
589
+ hexagons: list = [hexagons]
590
+
591
+ if self._safe_mode:
592
+ for i in range(len(hexagons)):
593
+ hexagons[i]: str = self._format_hexagon(hexagons[i])
594
+
595
+ if not self._is_valid_hexagon(hexagons[i]):
596
+ raise HexagonError("Please enter a valid hexagon (FoxAPi.available_hexagons")
597
+
598
+ def add_debug(func):
599
+ self._check_litsener(asyncio.iscoroutinefunction(func))
600
+
601
+ for hexagon in hexagons:
602
+ ends: list = [f"/warReport/{hexagon}", f"/maps/{hexagon}/dynamic/public", f"/maps/{hexagon}/static"]
603
+
604
+ for hexa in ends:
605
+ self._to_call[hexa]: callable = func
606
+ self._hex_call.append(hexa)
607
+
608
+ return func
609
+
610
+ if callable(callback):
611
+ return add_debug(callback)
612
+
613
+ return add_debug
foxapi/utils.py ADDED
@@ -0,0 +1,88 @@
1
+
2
+ _images_relations: dict = {
3
+ "5": "StaticBase1",
4
+ "6": "StaticBase2",
5
+ "7": "StaticBase3",
6
+ "8": "ForwardBase1",
7
+ "9": "ForwardBase2",
8
+ "10": "ForwardBase3",
9
+ "11": "Hospital",
10
+ "12": "VehicleFactory",
11
+ "13": "Armory",
12
+ "14": "SupplyStation",
13
+ "15": "Workshop",
14
+ "16": "ManufacturingPlant",
15
+ "17": "Refinery",
16
+ "18": "Shipyard",
17
+ "19": "TechCenter",
18
+ "20": "SalvageField",
19
+ "21": "ComponentField",
20
+ "22": "FuelField",
21
+ "23": "SulfurField",
22
+ "24": "WorldMapTent",
23
+ "25": "TravelTent",
24
+ "26": "TrainingArea",
25
+ "27": "SpecialBase",
26
+ "28": "ObservationTower",
27
+ "29": "Fort",
28
+ "30": "TroopShip",
29
+ "32": "SulfurMine",
30
+ "33": "StorageFacility",
31
+ "34": "Factory",
32
+ "35": "GarrisonStation",
33
+ "36": "AmmoFactory",
34
+ "37": "RocketSite",
35
+ "38": "SalvageMine",
36
+ "39": "ConstructionYard",
37
+ "40": "ComponentMine",
38
+ "41": "OilWell",
39
+ "45": "RelicBase1",
40
+ "46": "RelicBase2",
41
+ "47": "RelicBase3",
42
+ "51": "MassProductionFactory",
43
+ "52": "Seaport",
44
+ "53": "CoastalGun",
45
+ "54": "SoulFactory",
46
+ "56": "TownBase1",
47
+ "57": "TownBase2",
48
+ "58": "TownBase3",
49
+ "59": "StormCannon",
50
+ "60": "IntelCenter",
51
+ "61": "CoalField",
52
+ "62": "OilField",
53
+ "70": "RocketTarget",
54
+ "71": "RocketGroundZero",
55
+ "72": "RocketSiteWithRocket",
56
+ "75": "FacilityMineOilRig"
57
+ }
58
+
59
+ class EndpointError(Exception):
60
+ pass
61
+
62
+
63
+ class HexagonError(Exception):
64
+ pass
65
+
66
+
67
+ class FoxAPIError(Exception):
68
+ pass
69
+
70
+
71
+ class APIResponse:
72
+ def __init__(self, headers: dict, json: dict, status_code: int, hexagon: str, is_cache: bool):
73
+ self.headers: dict = headers
74
+ self.json: dict = json
75
+ self.status_code: int = status_code
76
+ self.hexagon: str = hexagon
77
+ self.is_cache: bool = is_cache
78
+
79
+
80
+ class HexagonObject:
81
+ def __init__(self, hexagon: str, war_report: dict, static: dict, dynamic: dict, captured_towns: dict, casualty_rate: dict, image):
82
+ self.hexagon: str = hexagon
83
+ self.war_report: dict = war_report
84
+ self.static: dict = static
85
+ self.dynamic: dict = dynamic
86
+ self.captured_towns: dict = captured_towns
87
+ self.casualty_rate: dict = casualty_rate
88
+ self.image = image
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ThePhoenix78
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
@@ -0,0 +1,211 @@
1
+ Metadata-Version: 2.1
2
+ Name: foxapi
3
+ Version: 1.0.0
4
+ Summary: A wrapper for the foxhole API
5
+ Home-page: https://github.com/ThePhoenix78/FoxAPI
6
+ Download-URL: https://github.com/ThePhoenix78/FoxAPI/tarball/master
7
+ Author: ThePhoenix78
8
+ Author-email: thephoenix788@gmail.com
9
+ License: MIT
10
+ Keywords: foxhole,foxapi
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: requests
17
+ Requires-Dist: pillow
18
+
19
+ # FoxAPI Documentation
20
+
21
+ `FoxAPI` is a wrapper for the Official Foxhole API. It provides methods to interact with various endpoints related to maps, war data, dynamic/static map states, and more. The client supports data caching and etags natively to avoid overloading the Foxhole servers.
22
+
23
+ If you are new to the developer world (or lazy like me), it's the perfect tool!
24
+
25
+ Also, if you work with discord.py or any asynchronous API, this tool might be useful as well since it support async methods natively as well as synchronous
26
+
27
+
28
+ ## Table of Contents
29
+ - [Dependencies](#dependencies)
30
+ - [Methods](#methods)
31
+ - [API Interaction](#api-interaction)
32
+ - [Map and War Data](#map-and-war-data)
33
+ - [Hexagon Operations](#hexagon-operations)
34
+ - [Listener Functions](#listener-functions)
35
+ - [Error Handling](#error-handling)
36
+ - [Objects](#Objects)
37
+ - [Example Usage](#example-usage)
38
+
39
+ ## Dependencies
40
+
41
+ ```bash
42
+ pip install pillow requests
43
+ ```
44
+
45
+ ## Methods
46
+
47
+ ### API Interaction (async)
48
+
49
+ #### Note : all of theses methods are async, to run the synchronous version, add _sync at the end (see API example)
50
+
51
+ - **get_data(endpoint: str, etag: str = None, cache: bool = False) -> requests.Response**
52
+ Fetches data from the specified endpoint with optional caching and ETag support.
53
+
54
+ - Parameters:
55
+ - `endpoint` (str): The API endpoint to call.
56
+ - `etag` (str, optional): The ETag header for cache validation (not required since managed natively).
57
+ - `cache` (bool, optional): Whether to use cached data (default: False).
58
+
59
+ - Returns: The response data from the API as a requests.Response object.
60
+
61
+ ### Map and War Data
62
+
63
+ - **get_maps(cache: bool = True) -> list**
64
+ Retrieves a list of available hexagons (maps) in the game world.
65
+
66
+ - **get_war(cache: bool = False) -> dict**
67
+ Retrieves the current war state (war data).
68
+
69
+ - **get_static(hexagon: str, cache: bool = False) -> dict**
70
+ Retrieves the static data for the specified hexagon.
71
+
72
+ - **get_dynamic(hexagon: str, cache: bool = False) -> dict**
73
+ Retrieves the dynamic data for the specified hexagon.
74
+
75
+ - **get_war_report(hexagon: str, cache: bool = False) -> dict**
76
+ Retrieves the war report for the specified hexagon.
77
+
78
+ - **get_hexagon_data(hexagon: str, cache: bool = False) -> HexagonObject**
79
+ Retrieves all the data awailable for the specified hexagon.
80
+
81
+ ### Hexagon Operations
82
+
83
+ - **await calc_distance(x1: float, y1: float, x2: float, y2: float) -> float**
84
+ Calculates the Euclidean distance between two points on the map.
85
+
86
+ - **await get_captured_towns(hexagon: str = None, dynamic: dict = None, static: dict = None) -> dict**
87
+ Retrieves the captured towns for a given hexagon based on dynamic and static data.
88
+
89
+ - **load_hexagon_map(hexagon: str) -> pillow.Image**
90
+ Loads the PNG map for the specified hexagon.
91
+
92
+ - **make_map_png(hexagon: str, dynamic: dict = None, static: dict = None) -> pillow.Image**
93
+ Generates a PNG image of the hexagon map with all the icons associated to each faction in their respective colors (included fields and town base). Only public data will be present.
94
+
95
+ - **calculate_death_rate(self, hexagon: str = None, war_report: dict = None): -> dict**
96
+ calculate the death rate between the first launch and the current one
97
+
98
+ ### Listener Functions
99
+
100
+ - **on_api_update(callback: callable = None, endpoints: list = None)**
101
+ Registers a callback function to be called when the data for specified API endpoints is updated.
102
+
103
+ - **on_hexagon_update(callback: callable = None, hexagons: list = None)**
104
+ Registers a callback function to be called when the data for specified hexagons is updated.
105
+
106
+ ## Error Handling
107
+
108
+ - **EndpointError**: Raised if an invalid API endpoint is used.
109
+ - **HexagonError**: Raised if an invalid hexagon is provided.
110
+ - **FoxAPIError**: A general error for issues within the FoxAPI class (e.g., missing data).
111
+
112
+
113
+ ## Objects
114
+
115
+ ```python
116
+ class APIResponse:
117
+ def __init__(self, headers: dict, json: dict, status_code: int, hexagon: str, is_cache: bool):
118
+ self.headers: dict = headers
119
+ self.json: dict = json
120
+ self.status_code: int = status_code
121
+ self.hexagon: str = hexagon
122
+ self.is_cache: bool = is_cache
123
+
124
+
125
+ class HexagonObject:
126
+ def __init__(self, hexagon: str, war_report: dict, static: dict, dynamic: dict, captured_towns: dict, casualty_rate: dict, image: pillow.Image):
127
+ self.hexagon: str = hexagon
128
+ self.war_report: dict = war_report
129
+ self.static: dict = static
130
+ self.dynamic: dict = dynamic
131
+ self.captured_towns: dict = captured_towns
132
+ self.casualty_rate: dict = casualty_rate
133
+ self.image: pillow.Image = image
134
+ ```
135
+
136
+
137
+ ## Example Usage
138
+
139
+ ```python
140
+ from foxapi import FoxAPI
141
+
142
+ # Initialize the API client in safe mode
143
+
144
+ # if you are a developer and plane to use the exact hexagons name
145
+ # you can turn the safe_mod off, otherwise it will convert
146
+ # api calls and hexagons name into valid ones
147
+ # Ex: deadlands -> DeadLandsHex (Yes, I am *that* lazy)
148
+
149
+ fox = FoxAPI(safe_mod=False)
150
+
151
+ hexagon: str = "DeadLandsHex"
152
+
153
+ def retrieve():
154
+ # Get the list of available hexagons (maps) and state of the current war
155
+ maps: list = fox.get_maps_sync()
156
+ war: dict = fox.get_war_sync()
157
+
158
+ # Retrieve data for a specific hexagon
159
+ dynamic_data: dict = fox.get_dynamic_sync(hexagon)
160
+ static_data: dict = fox.get_static_sync(hexagon)
161
+ war_report: dict = fox.get_war_report_sync(hexagon)
162
+
163
+ # Create a map PNG for a hexagon with building informations on it
164
+ map_image = fox.make_map_png_sync(hexagon)
165
+ map_image.show()
166
+
167
+ # to get all the data at once
168
+
169
+ data: HexagonObject = fox.get_hexagon_data_sync(hexagon=hexagon, use_cache=True)
170
+
171
+ # Async equivalent
172
+
173
+ async def retrieve():
174
+ # Get the list of available hexagons (maps) and state of the current war
175
+ maps: list = await fox.get_maps()
176
+ war: dict = await fox.get_war()
177
+
178
+ # Retrieve data for a specific hexagon
179
+ dynamic_data: dict = await fox.get_dynamic(hexagon)
180
+ static_data: dict = await fox.get_static(hexagon)
181
+ war_report: dict = await fox.get_war_report(hexagon)
182
+
183
+ # Create a map PNG for a hexagon with building informations on it
184
+ map_image = await fox.make_map_png(hexagon)
185
+ map_image.show()
186
+
187
+ # to get all the data at once
188
+
189
+ data: HexagonObject = await fox.get_hexagon_data(hexagon=hexagon, use_cache=True)
190
+
191
+
192
+ # Register a callback to listen for updates on all the hexagons
193
+ # it will run forever don't worry
194
+
195
+ @on_hexagon_update("all")
196
+ def on_update(hexa: HexagonObject):
197
+ print(f"Hexagon {hexa.hexagon} has been updated")
198
+ hexa.image.save(f"{hexa.hexagon}.png")
199
+
200
+
201
+ # The following async code works as well
202
+
203
+ @on_hexagon_update("all")
204
+ async def on_update(hexa: HexagonObject):
205
+ print(f"Hexagon {hexa.hexagon} has been updated")
206
+ hexa.image.save(f"{hexa.hexagon}.png")
207
+
208
+ ```
209
+ (Yes, most of this documentation has been generated with ChatGPT, I am alone and too lazy to do that)
210
+
211
+ #### I am not responsible for what you are doing with it
@@ -0,0 +1,8 @@
1
+ foxapi/__init__.py,sha256=-0OL1PMDBDYfuPhtTQqNzBZnwdrqks74qDvvuEZNQFE,28
2
+ foxapi/foxapi.py,sha256=CBvqG9vzNp18MLjMfm6HvXmzVt2wZGxyJ7MUtT0afYc,23667
3
+ foxapi/utils.py,sha256=FBpLbb7M9QO01NiGolPDGW8NNSmSnoB0wImH0DBlkxg,2345
4
+ foxapi-1.0.0.dist-info/LICENSE,sha256=03ioHV45Gxam7SpQhsdgQbig4HJTZtYl5gY2NqT9E9I,1071
5
+ foxapi-1.0.0.dist-info/METADATA,sha256=U4-s96FdfjpEDkMui1uKXjwy8VOTuYEOJA3KI58C6YM,7726
6
+ foxapi-1.0.0.dist-info/WHEEL,sha256=Mdi9PDNwEZptOjTlUcAth7XJDFtKrHYaQMPulZeBCiQ,91
7
+ foxapi-1.0.0.dist-info/top_level.txt,sha256=mQuWTXa1kArKujxHcFvUUmCdukcsDHk8koaJ7DgOBao,7
8
+ foxapi-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (73.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ foxapi