-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsearch.py
More file actions
645 lines (484 loc) · 18.9 KB
/
search.py
File metadata and controls
645 lines (484 loc) · 18.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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
import os
from dataclasses import dataclass
import pandas as pd
import requests
from .utils import cache
from eve_tools.ESI import ESIClient
from eve_tools.config import SDE_DIR
@cache(expires=24 * 3600 * 30) # one month
def search_id(search: str, category: str, cname: str = "any") -> int:
"""Searches for the id of an entity in EVE that matches search word.
Searches for character_id, region_id, corporation_id, etc., provided with correct search word.
Only allow search that returns one results. Default to strict=true. Use precise search word.
As of July 12th 2022, ESI deprecated unauthenticated /search/ endpoint.
All searches now need to use authenticated "/characters/{character_id}/search/" endpoint.
Note that character_id is not a required param with authenticated endpoint.
Args:
search: str
Precise search word.
category: str
One of ["alliance", "character", "constellation", "corporation", "type", "inventory_type", "region", "solar_system", "system", "station"].
Incorrect category is rejected.
cname: str
cname's character_id will be used in searching. Specifies which character's token to use.
If searching for structure, this character needs to have docking access.
Returns:
An int, the id of the search entity within the given category.
Assume no overflow.
Raises:
ValueError: Invalid category given. Choose ONE from accepted categories.
ValueError: No record of search word in category. Raised when search returns empty result.
Warning: Raised when return value from ESI has more than one entry.
Caches:
cache.db-api_cache: one month
Scopes:
esi-search.search_structures.v1
Example:
>>> from eve_tools import search_id
>>> print(search_id("Ishtar", categories="inventory_type"))
12005
>>> print(search_id("Jita", categories="system"))
30000240
"""
if category == "structure":
return search_structure_id(search, cname)
elif category == "region":
return search_region_id(search)
elif category == "system" or category == "solar_system":
return search_system_id(search)
elif category == "type" or category == "inventory_type":
return search_type_id(search)
accepted_categories = [
"alliance",
"character",
"constellation",
"corporation",
"inventory_type",
"region",
"solar_system",
"station",
]
if category not in accepted_categories:
raise ValueError(
f"Invalid category given. Choose ONE from {accepted_categories}."
)
resp = ESIClient.get(
"/characters/{character_id}/search/",
categories=category,
search=search,
strict="true",
cname=cname,
).data
ret = resp.get(category)
if not ret:
raise ValueError(f"No record of {search} in {category}.")
if len(ret) > 1:
# TODO: change to "use search_ids" upon completion.
raise Warning(
f"Search should only return one result instead of {len(ret)}. Use precise search word and set strict=True to avoid this warning."
)
return ret[0]
@dataclass
class Structure:
structure_id: int
system_id: int
owner_id: int
name: str
def __eq__(self, __o: object) -> bool:
if isinstance(__o, Structure):
return self.structure_id == __o.structure_id
raise NotImplemented
@cache(expires=24 * 3600) # one day
def search_structure(structure_id: int) -> Structure:
"""Searches for a structure's info.
Args:
structure_id: str
A valid structure_id, e.g. 1035466617946
Returns:
A Structure instance with station_id.
Cache:
cache.db-api_cache: one day
Example:
>>> from eve_tools import search_structure
>>> structure = search_structure(1035466617946)
>>> print(structure)
Structure(structure_id=1035466617946, system_id=30000240, owner_id=98599770, name='4-HWWF - WinterCo. Central Station')
"""
resp = ESIClient.get(
"/universe/structures/{structure_id}/", structure_id=structure_id
).data
return Structure(
structure_id=structure_id,
system_id=resp["solar_system_id"],
owner_id=resp["owner_id"],
name=resp["name"],
)
def search_structure_system_id(structure_id: int) -> int:
"""Searches system_id given a structure_id.
Args:
structure_id: int
A valid structure_id, e.g. 1035466617946
Returns:
A int for system_id.
Example:
>>> from eve_tools import search_structure_system_id
>>> print(search_structure_system_id(1035466617946))
30000240
"""
structure = search_structure(structure_id)
return structure.system_id
def search_structure_region_id(structure_id: int) -> int:
"""Searches region_id given a structure_id.
Args:
structure_id: int
A valid structure_id, e.g. 1035466617946
Returns:
A int for region_id.
Example:
>>> from eve_tools import search_structure_region_id
>>> print(search_structure_region_id(1035466617946))
10000003
"""
system_id = search_structure_system_id(structure_id)
region_id = search_system_region_id(system_id)
return region_id
@cache(expires=24 * 3600 * 30) # one month
def search_structure_id(structure_name: str, cname: str = "any") -> int:
"""Searches for structure_id given a structure.
The oauth character should have docking access to the structure, as per ESI requirements.
Args:
structure_name: str
The structure name to search for. It needs to be a precise name of the structure.
For example, for 4-H citadel, search should be "4-HWWF - WinterCo. Central Station",
instead of "4-H Citadel" or "4-HWWF WinterCo Central Station".
cname: str
cname's character_id will be used in searching. This character needs to have docking access to structure.
Returns:
An int, the structure_id of the given structure, if any. A structure_id is in int64.
Raises:
ValueError: No record of structure {search}.
Caches:
cache.db-api_cache: one month
Scopes:
esi-search.search_structures.v1
Example:
>>> from eve_tools import search_structure_id
>>> print(search_structure_id("4-HWWF - WinterCo. Central Station"))
1035466617946
"""
resp = ESIClient.get(
"/characters/{character_id}/search/",
categories="structure",
search=structure_name,
strict="true",
cname=cname,
).data
ret = resp.get("structure")
if not ret:
raise ValueError(f'No record of structure "{structure_name}". ')
return ret[0]
@dataclass
class Station:
station_id: int
system_id: int
region_id: int
name: str
security: float
stationTypeID: int
def __init__(self, df: pd.DataFrame):
self.station_id = int(df["stationID"])
self.system_id = int(df["solarSystemID"])
self.region_id = int(df["regionID"])
self.name = df["stationName"].values[0]
self.security = float(df["security"])
self.stationTypeID = int(df["stationTypeID"])
def __eq__(self, __o: object) -> bool:
if isinstance(__o, Station):
return __o.station_id == self.station_id
raise NotImplemented
@cache(expires=24 * 3600 * 30)
def search_station(station_id: int) -> Station:
"""Searches for a staton's info.
Args:
station_id: int
A valid station_id, e.g. 60000004
Returns:
A Station instance with station_id.
Raises:
ValueError: Invalid station_id given: {station_id}
Cache:
cache.db-api_cache: one month
Example:
>>> from eve_tools import search_station
>>> station = search_station(60000004)
>>> print(station)
Station(station_id=60000004, system_id=30002780, region_id=10000033, name='Muvolailen X - Moon 3 - CBD Corporation Storage', security=0.7080867245, stationTypeID=1531)
"""
staStations = pd.read_csv(os.path.join(SDE_DIR, "staStations.csv.bz2"))
stationIDs = staStations["stationID"]
if station_id not in stationIDs.values:
raise ValueError(f"Invalid station_id given: {station_id}.")
station = staStations.loc[stationIDs == station_id]
return Station(station)
def search_station_region_id(station_id: int) -> int:
"""Searches region_id given a station_id.
Args:
station_id: int
A valid station_id, e.g. 60000004
Returns:
A int for region_id.
Example:
>>> from eve_tools import search_station_region_id
>>> print(search_station_region_id(60000004))
10000033
"""
station = search_station(station_id)
return station.region_id
def search_station_system_id(station_id: int) -> int:
"""Searches system_id given a station_id.
Args:
station_id: int
A valid station_id, e.g. 60000004
Returns:
A int for system_id.
Example:
>>> from eve_tools import search_station_system_id
>>> print(search_station_system_id(60000004))
30002780
"""
station = search_station(station_id)
return station.system_id
@cache(expires=24 * 3600 * 30) # one month
def search_region_id(search: str) -> int:
"""Searches region_id given a region name.
Args:
search: str
A valid region name in precise form. "The Forge" instead of "The For".
Returns:
A int for region_id.
Raises:
ValueError: Invalid region name given: {search}
Caches:
cache.db-api_cache: one month
Example:
>>> from eve_tools import search_region_id
>>> print(search_region_id("The Forge"))
10000002
"""
mapRegions = pd.read_csv(os.path.join(SDE_DIR, "mapRegions.csv.bz2"))
region_name = mapRegions["regionName"]
if search not in region_name.values:
raise ValueError(f"Invalid region name given: {search}.")
region = mapRegions.loc[region_name == search]
return int(region["regionID"])
@dataclass
class SolarSystem:
system_id: int
region_id: int
name: str
security: float
def __init__(self, df: pd.DataFrame):
self.system_id = int(df["solarSystemID"])
self.region_id = int(df["regionID"])
self.name = df["solarSystemName"].values[0]
self.security = float(df["security"])
def __eq__(self, __o: object) -> bool:
if isinstance(__o, SolarSystem):
return self.system_id == __o.system_id and self.name == __o.name
raise NotImplemented
@cache(expires=24 * 3600 * 30)
def search_system(system_id: int) -> SolarSystem:
"""Searches for a system's info.
Args:
system_id: int
A valid system_id, e.g. 30000007
Returns:
A SolarSystem instance with system_id.
Raises:
ValueError: Invalid system_id given: {system_id}
Cache:
cache.db-api_cache: one month
Example:
>>> from eve_tools import search_system
>>> esi_system = search_system(30000007)
>>> print(esi_system)
System(system_id=30000007, region_id=10000001, name='Yuzier', security=0.9065555105)
"""
mapSolarSystems = pd.read_csv(os.path.join(SDE_DIR, "mapSolarSystems.csv.bz2"))
solarSystemID = mapSolarSystems["solarSystemID"]
if system_id not in solarSystemID.values:
raise ValueError(f"Invalid system_id given: {system_id}.")
solar_system = mapSolarSystems.loc[solarSystemID == system_id]
return SolarSystem(solar_system)
@cache(expires=24 * 3600 * 30) # one month
def search_system_id(search: str) -> int:
"""Searches system_id given a system name.
Args:
search: str
A valid system name in precise form, e.g. "Jita"
Returns:
A int for system_id.
Raises:
ValueError: Invalid system name given: {search}
Caches:
cache.db-api_cache: one month
Example:
>>> from eve_tools import search_system_id
>>> print(search_system_id("Jita"))
30000240
"""
mapSolarSystems = pd.read_csv(os.path.join(SDE_DIR, "mapSolarSystems.csv.bz2"))
solarSystemName = mapSolarSystems["solarSystemName"]
if search not in solarSystemName.values:
raise ValueError(f"Invalid system name given: {search}.")
solarSystem = mapSolarSystems.loc[solarSystemName == search]
return int(solarSystem["solarSystemID"])
def search_system_region_id(system_id: int) -> int:
"""Searches for region_id given a system_id.
Finds which region_id (Vale of the Silent, etc.) the given system (4-HWWF, etc.) is located.
"""
"""Searches region_id given a system_id.
Args:
system_id: int
A valid system_id, e.g. 30000007
Returns:
A int for region_id.
Example:
>>> from eve_tools import search_system_region_id
>>> print(search_system_region_id(30000007))
10000001
"""
esi_system: SolarSystem = search_system(system_id)
return esi_system.region_id
@dataclass
class InvType:
type_id: int
type_name: str
published: bool
marketGroupID: int
def __init__(self, df: pd.DataFrame):
self.type_id = int(df["typeID"])
self.type_name = df["typeName"].values[0]
self.published = bool(int(df["published"]))
self.marketGroupID = int(df["marketGroupID"])
def __eq__(self, __o: object) -> bool:
if isinstance(__o, InvType):
return self.type_id == __o.type_id and self.type_name == __o.type_name
raise NotImplemented
@cache(expires=24 * 3600 * 30)
def search_type(type_id: int) -> InvType:
"""Searches for a type's info.
Args:
type_id: int
A valid type_id, e.g. 12005 (ishtar)
Returns:
A InvType instance with type_id.
Raises:
ValueError: Invalid type_id given: {type_id}
Cache:
cache.db-api_cache: one month
Example:
>>> from eve_tools import search_type
>>> invType = search_type(12005)
>>> print(invType)
InvType(type_id=12005, type_name='Ishtar', published=True, marketGroupID=451)
"""
invTypes = pd.read_csv(os.path.join(SDE_DIR, "invTypes.csv.bz2"))
typeIDs = invTypes["typeID"]
if type_id not in typeIDs.values:
raise ValueError(f"Invalid type_id given: {type_id}.")
invType = invTypes.loc[typeIDs == type_id]
return InvType(invType)
@cache(expires=24 * 3600 * 30)
def search_type_id(search: str) -> int:
"""Searches type_id given a type name.
Args:
search: str
A valid type name in precise form, e.g. "Ishtar"
Returns:
A int for type_id.
Raises:
ValueError: Invalid type name given: {search}
Caches:
cache.db-api_cache: one month
Note:
Using SDE needs more memory (15MB) but less time than ESI endpoint.
Considering most modern systems have adequate RAM, time is more sensitive.
Example:
>>> from eve_tools import search_type_id
>>> print(search_type_id("Ishtar"))
12005
"""
invTypes = pd.read_csv(os.path.join(SDE_DIR, "invTypes.csv.bz2"))
typeName = invTypes["typeName"]
if search not in typeName.values:
raise ValueError(f"Invalid type name given: {search}.")
invType = invTypes.loc[typeName == search]
return int(invType["typeID"])
@cache(expires=24 * 3600 * 30)
def search_station_by_name(system_id: int, search: str):
"""Uses system id input and station name/description to search all stations in that system for a match.
Then returns the station id and name/description. Use search_id function above to find ID """
"""
Args:
system_id: int, search: str
Requires knowing system id and at least a partical station description
Example, Jita system, search_station_by_name(system_id=30000142, search="Caldari Navy")
Returns:
A list of tupes in the format, [(system id, description),]
Raises:
ValueError: Invalid type name given: {search}
Caches:
cache.db-api_cache: one month
Note:
Using SDE needs more memory (15MB) but less time than ESI endpoint.
Considering most modern systems have adequate RAM, time is more sensitive.
Example:
>>> from eve_tools import search_type_id
>>> print(search_station_by_name(system_id=30000142, search="Caldari Navy"))
[('60003757', ' IV - Moon 5 - Caldari Navy Assembly Plant'), ('60003760', ' IV - Moon 4 - Caldari Navy Assembly Plant')]
"""
response = requests.get(f"https://esi.evetech.net/latest/universe/systems/{system_id}/?datasource=tranquility&language=en")
if response.status_code == 200:
resp = ESIClient.get(
"/universe/systems/{system_id}/", system_id=system_id,
).data
station_list_matching = []
station_description_list = []
station_information = []
for item in resp['stations']:
station_descriptions = str(search_station(item))
match = re.findall(search, station_descriptions)
if match:
station_descr = re.search(r"name=\'([A-ZA-z]+)(.+)'", station_descriptions)
station_list_matching.append(item)
station_description_list.append(station_descr.group(2))
for idx in range(len(station_list_matching)):
station_and_descr_grouped = (str(station_list_matching[idx]), station_description_list[idx])
station_information.append(station_and_descr_grouped)
return station_information
else:
print(f"Invalid Entry, Status Code: {response.status_code}, Reason: {response.reason}")
@cache(expires=24 * 3600 * 30)
def search_station_by_system_name(system_name: str, station_description: str):
"""Easily lookup all stations in a system by system name. Use description for a more specific search. """
"""
Args:
system_name: str, station_description: str
Search for stations in a system using system name with a station description.
Returns:
A list of tupes in the format, [(system id, description),]
Raises:
Caches:
cache.db-api_cache: one month
Note:
Using SDE needs more memory (15MB) but less time than ESI endpoint.
Considering most modern systems have adequate RAM, time is more sensitive.
Example:
>>> from eve_tools import search_type_id
>>> print(search_station_by_system_name("Jita", "Caldari Navy"))
[('60003757', ' IV - Moon 5 - Caldari Navy Assembly Plant'), ('60003760', ' IV - Moon 4 - Caldari Navy Assembly Plant')]
"""
system_id = search_id(search=system_name, category="system")
all_stations_in_system = search_station_by_name(system_id, station_description)
return all_stations_in_system