forked from madcowfred/evething
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_updater.py
More file actions
executable file
·1306 lines (1076 loc) · 48 KB
/
Copy pathapi_updater.py
File metadata and controls
executable file
·1306 lines (1076 loc) · 48 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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/local/bin/python
import datetime
import logging
import os
import requests
import sys
import threading
import time
try:
import xml.etree.cElementTree as ET
except:
import xml.etree.ElementTree as ET
from Queue import Queue
from collections import OrderedDict
from decimal import *
# Aurgh
os.environ['DJANGO_SETTINGS_MODULE'] = 'evething.settings'
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import connection
from thing.models import *
# base headers
HEADERS = {
'User-Agent': 'EVEthing-api-updater',
}
ACCOUNT_INFO_URL = '%s/account/AccountStatus.xml.aspx' % (settings.API_HOST)
API_INFO_URL = '%s/account/APIKeyInfo.xml.aspx' % (settings.API_HOST)
ASSETS_CHAR_URL = '%s/char/AssetList.xml.aspx' % (settings.API_HOST)
ASSETS_CORP_URL = '%s/corp/AssetList.xml.aspx' % (settings.API_HOST)
BALANCE_URL = '%s/corp/AccountBalance.xml.aspx' % (settings.API_HOST)
CHAR_SHEET_URL = '%s/char/CharacterSheet.xml.aspx' % (settings.API_HOST)
CORP_SHEET_URL = '%s/corp/CorporationSheet.xml.aspx' % (settings.API_HOST)
LOCATIONS_CHAR_URL = '%s/char/Locations.xml.aspx' % (settings.API_HOST)
ORDERS_CHAR_URL = '%s/char/MarketOrders.xml.aspx' % (settings.API_HOST)
ORDERS_CORP_URL = '%s/corp/MarketOrders.xml.aspx' % (settings.API_HOST)
SKILL_QUEUE_URL = '%s/char/SkillQueue.xml.aspx' % (settings.API_HOST)
TRANSACTIONS_CHAR_URL = '%s/char/WalletTransactions.xml.aspx' % (settings.API_HOST)
TRANSACTIONS_CORP_URL = '%s/corp/WalletTransactions.xml.aspx' % (settings.API_HOST)
# number of rows to request per WalletTransactions call, max is 2560
TRANSACTION_ROWS = 2560
# ---------------------------------------------------------------------------
# Simple job-consuming worker thread
class APIWorker(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
logging.info('%s: started', self.name)
while True:
job = self.queue.get()
# die die die
if job is None:
self.queue.task_done()
return
else:
try:
job.run()
except:
logging.error('Trapped exception!', exc_info=sys.exc_info())
self.queue.task_done()
# ---------------------------------------------------------------------------
class APIJob:
def __init__(self, apikey, character=None):
self._apikey = apikey
self._character = character
# ---------------------------------------------------------------------------
# Perform an API request and parse the returned XML via ElementTree
def fetch_api(self, url, params):
start = time.time()
# Add the API key information
params['keyID'] = self._apikey.id
params['vCode'] = self._apikey.vcode
# Check the API cache for this URL/params combo
now = datetime.datetime.utcnow()
params_repr = repr(sorted(params.items()))
try:
apicache = APICache.objects.get(url=url, parameters=params_repr, cached_until__gt=now)
# Data is not cached, fetch new data
except APICache.DoesNotExist:
apicache = None
logging.info('Fetching URL %s', url)
# Fetch the URL
r = requests.post(url, params, headers=HEADERS, config={ 'max_retries': 1 })
data = r.text
logging.info('URL retrieved in %s', datetime.datetime.utcnow() - now)
# If the status code is bad return None
if not r.status_code == requests.codes.ok:
#self._total_api += (time.time() - start)
return (None, {}, None)
# Data is cached, use that
else:
logging.info('Cached URL %s', url)
data = apicache.text
# Parse the XML
root = ET.fromstring(data)
times = {
'current': parse_api_date(root.find('currentTime').text),
'until': parse_api_date(root.find('cachedUntil').text),
}
# If the data wasn't cached, cache it now
if apicache is None:
apicache = APICache(
url=url,
parameters=params_repr,
cached_until=times['until'],
text=data,
completed_ok=False,
)
apicache.save()
#self._total_api += (time.time() - start)
return (root, times, apicache)
# ---------------------------------------------------------------------------
# Do various API key things
class APICheck(APIJob):
def run(self):
root, times, apicache = self.fetch_api(API_INFO_URL, {})
if root is None:
#show_error('api_check', 'HTTP error', times)
return
# cached and completed ok? pass.
if apicache and apicache.completed_ok:
return
# Check for errors
err = root.find('error')
if err is not None:
# 202/203/204/205/210/212 Authentication failure
# 207 Not available for NPC corporations
# 220 Invalid corporate key
# 222 Key has expired
# 223 Legacy API key
if err.attrib['code'] in ('202', '203', '204', '205', '210', '212', '207', '220', '222', '223'):
self._apikey.valid = False
self._apikey.save()
return
# Find the key node
key_node = root.find('result/key')
# Update access mask
self._apikey.access_mask = int(key_node.attrib['accessMask'])
# Update expiry date
expires = key_node.attrib['expires']
if expires:
self._apikey.expires = parse_api_date(expires)
# Update key type
self._apikey.key_type = key_node.attrib['type']
# Save
self._apikey.save()
# Handle character key type keys
if key_node.attrib['type'] in (APIKey.ACCOUNT_TYPE, APIKey.CHARACTER_TYPE):
seen_chars = []
for row in key_node.findall('rowset/row'):
characterID = row.attrib['characterID']
seen_chars.append(characterID)
# Get a corporation object
corp = get_corporation(row.attrib['corporationID'], row.attrib['corporationName'])
characters = Character.objects.filter(id=characterID)
# Character doesn't exist, make a new one and save it
if characters.count() == 0:
character = Character(
id=characterID,
apikey=self._apikey,
name=row.attrib['characterName'],
corporation=corp,
wallet_balance=0,
cha_attribute=0,
cha_bonus=0,
int_attribute=0,
int_bonus=0,
mem_attribute=0,
mem_bonus=0,
per_attribute=0,
per_bonus=0,
wil_attribute=0,
wil_bonus=0,
clone_name='',
clone_skill_points=0,
)
# Character exists, update API key and corporation information
else:
character = characters[0]
character.apikey = self._apikey
character.corporation = corp
# Save the character
character.save()
# Unlink any characters that are no longer valid for this API key
for character in Character.objects.filter(apikey=self._apikey).exclude(pk__in=seen_chars):
character.apikey = None
character.save()
# Handle corporate key
elif key_node.attrib['type'] == APIKey.CORPORATION_TYPE:
row = key_node.find('rowset/row')
characterID = row.attrib['characterID']
# Get a corporation object
corp = get_corporation(row.attrib['corporationID'], row.attrib['corporationName'])
characters = Character.objects.filter(id=characterID)
# Character doesn't exist, make a new one and save it
if characters.count() == 0:
character = Character(
id=characterID,
name=row.attrib['characterName'],
corporation=corp,
)
else:
character = characters[0]
self._apikey.corp_character = character
self._apikey.save()
# completed ok
apicache.completed_ok = True
apicache.save()
# ---------------------------------------------------------------------------
# Fetch account status
class AccountStatus(APIJob):
def run(self):
# Don't check corporate keys
if self._apikey.corp_character:
return
# Make sure the access mask matches
if (self._apikey.access_mask & 33554432) == 0:
return
# Fetch the API data
root, times, apicache = self.fetch_api(ACCOUNT_INFO_URL, {})
if root is None:
#show_error('fetch_account_status', 'HTTP error', times)
return
# cached and completed ok? pass.
if apicache and apicache.completed_ok:
return
err = root.find('error')
if err is not None:
show_error('fetch_account_status', err, times)
return
# Update paid_until
self._apikey.paid_until = parse_api_date(root.findtext('result/paidUntil'))
self._apikey.save()
# completed ok
apicache.completed_ok = True
apicache.save()
# ---------------------------------------------------------------------------
class Assets(APIJob):
def run(self):
# Initialise for corporate query
if self._apikey.corp_character:
mask = 2
url = ASSETS_CORP_URL
a_filter = Asset.objects.filter(corporation=self._apikey.corp_character.corporation)
# Initialise for character query
else:
mask = 2
url = ASSETS_CHAR_URL
a_filter = Asset.objects.filter(character=self._character, corporation__isnull=True)
# Make sure the access mask matches
if (self._apikey.access_mask & mask) == 0:
return
# Fetch the API data
params = { 'characterID': self._character.id }
root, times, apicache = self.fetch_api(url, params)
if root is None:
#show_error('fetch_assets', 'HTTP error', times)
return
# cached and completed ok? pass.
if apicache and apicache.completed_ok:
return
err = root.find('error')
if err is not None:
show_error('fetch_assets', err, times)
return
#if self._apikey.corp_character:
# open('assets.xml', 'w').write(ET.tostring(root))
# return
# Generate an asset_id map
asset_ids = set()
asset_map = {}
for asset in a_filter:
asset_map[asset.id] = asset
# ACTIVATE RECURSION :siren:
rows = {}
self.assets_recurse(rows, root.find('result/rowset'), None)
# assetID - [0]system, [1]station, [2]container_id, [3]item, [4]flag, [5]quantiy, [6]rawQuantity, [7]singleton
errors = 0
last_count = 9999999999999999
while rows:
assets = list(rows.items())
# check for infinite loops
count = len(assets)
if count == last_count:
logging.warn('Infinite loop in assets, oops')
return
last_count = count
for id, data in assets:
# asset has a container_id...
if data[2] is not None:
# and the container_id doesn't exist, yet we have to do this later
try:
parent = Asset.objects.get(pk=data[2])
except Asset.DoesNotExist:
continue
# asset has no container_id
else:
parent = None
create = False
# if the asset already exists and has changed, delete it and create a new one
asset = asset_map.get(id, None)
if asset is not None:
if asset.system != data[0] or asset.station != data[1] or asset.parent != parent or \
asset.item != data[3] or asset.inv_flag_id != data[4] or asset.quantity != data[5] or \
asset.raw_quantity != data[6] or asset.singleton != data[7]:
asset.delete()
create = True
# doesn't exist, create a new one
else:
create = True
if create is True:
#print 'create!'
asset = Asset(
id=id,
character=self._character,
system=data[0],
station=data[1],
parent=parent,
item=data[3],
inv_flag_id=data[4],
quantity=data[5],
raw_quantity=data[6],
singleton=data[7],
)
if self._apikey.corp_character:
asset.corporation = self._apikey.corp_character.corporation
asset.save()
asset_map[id] = asset
asset_ids.add(id)
del rows[id]
# Delete any assets that we didn't see now
a_filter.exclude(pk__in=asset_ids).delete()
# completed ok
apicache.completed_ok = True
apicache.save()
# Recursively visit the assets tree and gather data
def assets_recurse(self, rows, rowset, container_id):
for row in rowset.findall('row'):
# No container_id (parent)
if 'locationID' in row.attrib:
location_id = int(row.attrib['locationID'])
# :ccp: as fuck
# http://wiki.eve-id.net/APIv2_Corp_AssetList_XML#officeID_to_stationID_conversion
if 66000000 <= location_id <= 66014933:
location_id -= 6000001
elif 66014934 <= location_id <= 67999999:
location_id -= 6000000
system = get_system(location_id)
station = get_station(location_id)
else:
system = None
station = None
try:
item = get_item(row.attrib['typeID'])
except Item.DoesNotExist:
logging.warn("Item #%s apparently doesn't exist", row.attrib['typeID'])
continue
asset_id = int(row.attrib['itemID'])
rows[asset_id] = [
system,
station,
container_id,
item,
int(row.attrib['flag']),
int(row.attrib.get('quantity', '0')),
int(row.attrib.get('rawQuantity', '0')),
int(row.attrib.get('singleton', '0')),
]
# Now we need to visit children rowsets
for rowset in row.findall('rowset'):
self.assets_recurse(rows, rowset, asset_id)
# ---------------------------------------------------------------------------
# Fetch and add/update character sheet data
class CharacterSheet(APIJob):
def run(self):
# Make sure the access mask matches
if (self._apikey.access_mask & 8) == 0:
return
# Fetch the API data
params = { 'characterID': self._character.id }
root, times, apicache = self.fetch_api(CHAR_SHEET_URL, params)
if root is None:
#show_error('fetch_char_sheet', 'HTTP error', times)
return
# cached and completed ok? pass.
if apicache and apicache.completed_ok:
return
err = root.find('error')
if err is not None:
show_error('fetch_char_sheet', err, times)
return
# Update wallet balance
self._character.wallet_balance = root.findtext('result/balance')
# Update attributes
self._character.cha_attribute = root.findtext('result/attributes/charisma')
self._character.int_attribute = root.findtext('result/attributes/intelligence')
self._character.mem_attribute = root.findtext('result/attributes/memory')
self._character.per_attribute = root.findtext('result/attributes/perception')
self._character.wil_attribute = root.findtext('result/attributes/willpower')
# Update attribute bonuses :ccp:
enh = root.find('result/attributeEnhancers')
val = enh.find('charismaBonus/augmentatorValue')
if val is None:
self._character.cha_bonus = 0
else:
self._character.cha_bonus = val.text
val = enh.find('intelligenceBonus/augmentatorValue')
if val is None:
self._character.int_bonus = 0
else:
self._character.int_bonus = val.text
val = enh.find('memoryBonus/augmentatorValue')
if val is None:
self._character.mem_bonus = 0
else:
self._character.mem_bonus = val.text
val = enh.find('perceptionBonus/augmentatorValue')
if val is None:
self._character.per_bonus = 0
else:
self._character.per_bonus = val.text
val = enh.find('willpowerBonus/augmentatorValue')
if val is None:
self._character.wil_bonus = 0
else:
self._character.wil_bonus = val.text
# Update clone information
self._character.clone_skill_points = root.findtext('result/cloneSkillPoints')
self._character.clone_name = root.findtext('result/cloneName')
# Get all of the rowsets
rowsets = root.findall('result/rowset')
# First rowset is skills
skills = {}
for row in rowsets[0]:
skills[int(row.attrib['typeID'])] = (int(row.attrib['skillpoints']), int(row.attrib['level']))
# Grab any already existing skills
for char_skill in CharacterSkill.objects.select_related('item', 'skill').filter(character=self._character, skill__in=skills.keys()):
points, level = skills[char_skill.skill.item_id]
if char_skill.points != points or char_skill.level != level:
char_skill.points = points
char_skill.level = level
char_skill.save()
del skills[char_skill.skill.item_id]
# Add any leftovers
for skill_id, (points, level) in skills.items():
char_skill = CharacterSkill(
character=self._character,
skill_id=skill_id,
points=points,
level=level,
)
char_skill.save()
# Save character
self._character.save()
# completed ok
apicache.completed_ok = True
apicache.save()
# ---------------------------------------------------------------------------
# Fetch and add/update character skill queue
class CharacterSkillQueue(APIJob):
def run(self):
# Make sure the access mask matches
if (self._apikey.access_mask & 262144) == 0:
return
# Fetch the API data
params = { 'characterID': self._character.id }
root, times, apicache = self.fetch_api(SKILL_QUEUE_URL, params)
if root is None:
#show_error('fetch_char_skill_queue', 'HTTP error', times)
return
# cached and completed ok? pass.
if apicache and apicache.completed_ok:
return
err = root.find('error')
if err is not None:
show_error('fetch_char_skill_queue', err, times)
return
# Delete the old queue
SkillQueue.objects.filter(character=self._character).delete()
# Add new skills
for row in root.findall('result/rowset/row'):
if row.attrib['startTime'] and row.attrib['endTime']:
sq = SkillQueue(
character=self._character,
skill_id=row.attrib['typeID'],
start_time=row.attrib['startTime'],
end_time=row.attrib['endTime'],
start_sp=row.attrib['startSP'],
end_sp=row.attrib['endSP'],
to_level=row.attrib['level'],
)
sq.save()
# completed ok
apicache.completed_ok = True
apicache.save()
# ---------------------------------------------------------------------------
# Fetch corporation sheet
class CorporationSheet(APIJob):
def run(self):
# Make sure the access mask matches
if (self._apikey.access_mask & 8) == 0:
return
params = { 'characterID': self._apikey.corp_character_id }
root, times, apicache = self.fetch_api(CORP_SHEET_URL, params)
if root is None:
#show_error('fetch_corp_sheet', 'HTTP error', times)
return
# cached and completed ok? pass.
if apicache and apicache.completed_ok:
return
err = root.find('error')
if err is not None:
show_error('fetch_corp_sheet', err, times)
return
corporation = self._apikey.corp_character.corporation
ticker = root.find('result/ticker')
corporation.ticker = ticker.text
corporation.save()
errors = 0
for rowset in root.findall('result/rowset'):
if rowset.attrib['name'] == 'divisions':
rows = rowset.findall('row')
corporation.division1 = rows[0].attrib['description']
corporation.division2 = rows[1].attrib['description']
corporation.division3 = rows[2].attrib['description']
corporation.division4 = rows[3].attrib['description']
corporation.division5 = rows[4].attrib['description']
corporation.division6 = rows[5].attrib['description']
corporation.division7 = rows[6].attrib['description']
corporation.save()
if rowset.attrib['name'] == 'walletDivisions':
wallet_map = {}
for cw in CorpWallet.objects.filter(corporation=corporation):
wallet_map[cw.account_key] = cw
for row in rowset.findall('row'):
wallet = wallet_map.get(int(row.attrib['accountKey']), None)
# If the wallet exists, update the description
if wallet is not None:
if wallet.description != row.attrib['description']:
wallet.description = row.attrib['description']
wallet.save()
# If it doesn't exist, wtf?
else:
logging.warn("No matching CorpWallet object for corpID=%s accountkey=%s", corporation.id, row.attrib['accountKey'])
errors += 1
# completed ok
if errors == 0:
apicache.completed_ok = True
apicache.save()
# ---------------------------------------------------------------------------
# Fetch corporation wallets
class CorporationWallets(APIJob):
def run(self):
# Make sure the access mask matches
if (self._apikey.access_mask & 1) == 0:
return
params = { 'characterID': self._apikey.corp_character_id }
root, times, apicache = self.fetch_api(BALANCE_URL, params)
if root is None:
#show_error('fetch_corp_wallets', 'HTTP error', times)
return
# cached and completed ok? pass.
if apicache and apicache.completed_ok:
return
err = root.find('error')
if err is not None:
show_error('fetch_corp_wallets', err, times)
return
corporation = self._apikey.corp_character.corporation
wallet_map = {}
for cw in CorpWallet.objects.filter(corporation=corporation):
wallet_map[cw.account_key] = cw
for row in root.findall('result/rowset/row'):
accountID = int(row.attrib['accountID'])
accountKey = int(row.attrib['accountKey'])
balance = Decimal(row.attrib['balance'])
wallet = wallet_map.get(accountKey, None)
# If the wallet exists, update the balance
if wallet is not None:
if balance != wallet.balance:
wallet.balance = balance
wallet.save()
# Otherwise just make a new one
else:
wallet = CorpWallet(
account_id=accountID,
corporation=corporation,
account_key=accountKey,
description='',
balance=balance,
)
wallet.save()
# completed ok
apicache.completed_ok = True
apicache.save()
# ---------------------------------------------------------------------------
# Fetch locations (and more importantly names) for assets
class Locations(APIJob):
def run(self):
# Initialise for character query
if not self._apikey.corp_character:
mask = 134217728
url = LOCATIONS_CHAR_URL
a_filter = Asset.objects.root_nodes().filter(character=self._character, corporation__isnull=True, singleton=True, item__item_group__category__name__in=('Celestial', 'Ship'))
# Make sure the access mask matches
if (self._apikey.access_mask & mask) == 0:
return
# Get ID list
ids = map(str, a_filter.values_list('id', flat=True))
if len(ids) == 0:
return
# Fetch the API data
params = {
'characterID': self._character.id,
'IDs': ','.join(map(str, a_filter.values_list('id', flat=True))),
}
root, times, apicache = self.fetch_api(url, params)
if root is None:
#show_error('fetch_asset_locations', 'HTTP error', times)
return
# cached and completed ok? pass.
if apicache and apicache.completed_ok:
return
err = root.find('error')
if err is not None:
show_error('fetch_asset_locations', err, times)
return
#open('locations.xml', 'w').write(ET.tostring(root))
for row in root.findall('result/rowset/row'):
ca = Asset.objects.get(character=self._character, id=row.attrib['itemID'])
if ca.name is None or ca.name != row.attrib['itemName']:
#print 'changing name to %r (%d)' % (row.attrib['itemName'], len(row.attrib['itemName']))
ca.name = row.attrib['itemName']
ca.save()
# completed ok
apicache.completed_ok = True
apicache.save()
# ---------------------------------------------------------------------------
# Fetch and add/update market orders
class MarketOrders(APIJob):
def run(self):
# Generate a character id map
self.char_id_map = {}
for character in Character.objects.all():
self.char_id_map[character.id] = character
# Initialise for corporate query
if self._apikey.corp_character:
mask = 4096
url = ORDERS_CORP_URL
o_filter = MarketOrder.objects.filter(corp_wallet__corporation=self._character.corporation)
wallet_map = {}
for cw in CorpWallet.objects.filter(corporation=self._character.corporation):
wallet_map[cw.account_key] = cw
# Initialise for character query
else:
mask = 4096
url = ORDERS_CHAR_URL
o_filter = MarketOrder.objects.filter(corp_wallet=None, character=self._character)
# Make sure the access mask matches
if (self._apikey.access_mask & mask) == 0:
return
# Fetch the API data
params = { 'characterID': self._character.id }
root, times, apicache = self.fetch_api(url, params)
if root is None:
#show_error('fetch_orders', 'HTTP error', times)
return
# cached and completed ok? pass.
if apicache and apicache.completed_ok:
return
err = root.find('error')
if err is not None:
show_error('fetch_orders', err, times)
return
# Generate an order_id map
order_map = {}
for mo in o_filter.select_related('item'):
order_map[mo.order_id] = mo
# Iterate over the returned result set
seen = []
for row in root.findall('result/rowset/row'):
order_id = int(row.attrib['orderID'])
#orders = MarketOrder.objects.filter(order_id=order_id, character=character)
# Order exists
order = order_map.get(order_id, None)
if order is not None:
# Order is still active, update relevant details
if row.attrib['orderState'] == '0':
issued = parse_api_date(row.attrib['issued'])
volRemaining = int(row.attrib['volRemaining'])
escrow = Decimal(row.attrib['escrow'])
price = Decimal(row.attrib['price'])
if issued > order.issued or \
volRemaining != order.volume_remaining or \
escrow != order.escrow or \
price != order.price:
order.issued = parse_api_date(row.attrib['issued'])
order.volume_remaining = int(row.attrib['volRemaining'])
order.escrow = Decimal(row.attrib['escrow'])
order.price = Decimal(row.attrib['price'])
order.total_price = order.volume_remaining * order.price
order.save()
seen.append(order_id)
# Not active, delete order
#else:
# order.delete()
# Doesn't exist and is active, make a new order
elif row.attrib['orderState'] == '0':
if row.attrib['bid'] == '0':
buy_order = False
else:
buy_order = True
# Make sure the character charID is valid
char = self.char_id_map.get(int(row.attrib['charID']))
if char is None:
logging.warn("No matching Character object for charID=%s", row.attrib['charID'])
continue
# Make sure the item typeID is valid
#items = Item.objects.filter(pk=row.attrib['typeID'])
#if items.count() == 0:
# print "ERROR: item with typeID '%s' does not exist, what the fuck?" % (row.attrib['typeID'])
# print '>> attrib = %r' % (row.attrib)
# continue
# Create a new order and save it
remaining = int(row.attrib['volRemaining'])
price = Decimal(row.attrib['price'])
issued = parse_api_date(row.attrib['issued'])
order = MarketOrder(
order_id=order_id,
station=get_station(int(row.attrib['stationID'])),
item=get_item(row.attrib['typeID']),
character=char,
escrow=Decimal(row.attrib['escrow']),
price=price,
total_price=remaining * price,
buy_order=buy_order,
volume_entered=int(row.attrib['volEntered']),
volume_remaining=remaining,
minimum_volume=int(row.attrib['minVolume']),
issued=issued,
expires=issued + datetime.timedelta(int(row.attrib['duration'])),
)
# Set the corp_wallet for corporation API requests
if self._apikey.corp_character:
#order.corp_wallet = CorpWallet.objects.get(corporation=character.corporation, account_key=row.attrib['accountKey'])
order.corp_wallet = wallet_map.get(int(row.attrib['accountKey']))
order.save()
seen.append(order_id)
# Any orders we didn't see need to be deleted - issue events first
to_delete = o_filter.exclude(pk__in=seen)
now = datetime.datetime.now()
for order in to_delete.select_related():
if order.buy_order:
buy_sell = 'buy'
else:
buy_sell = 'sell'
if order.corp_wallet:
order_type = 'corporate'
else:
order_type = 'personal'
url = reverse('transactions-all', args=[order.item.id, 'all'])
text = '%s: %s %s order for <a href="%s">%s</a> completed/expired (%s)' % (order.station.short_name, order_type, buy_sell, url,
order.item.name, order.character.name)
event = Event(
user_id=self._apikey.user.id,
issued=now,
text=text,
)
event.save()
# Then delete
to_delete.delete()
# completed ok
apicache.completed_ok = True
apicache.save()
# ---------------------------------------------------------------------------
# Fetch wallet transactions
class WalletTransactions(APIJob):
def run(self):
# Generate a character id map
self.char_id_map = {}
for character in Character.objects.all():
self.char_id_map[character.id] = character
# Initialise stuff
params = {
'characterID': self._character.id,
'rowCount': TRANSACTION_ROWS,
}
# Corporate key
if self._apikey.corp_character:
params['accountKey'] = self._corp_wallet.account_key
mask = 2097152
url = TRANSACTIONS_CORP_URL
t_filter = Transaction.objects.filter(corp_wallet__corporation=self._character.corporation)
# Character key
else:
mask = 4194304
url = TRANSACTIONS_CHAR_URL
t_filter = Transaction.objects.filter(corp_wallet=None, character=self._character)
# Make sure the access mask matches
if (self._apikey.access_mask & mask) == 0:
return
# Loop until we run out of transactions
errors = 0
one_week_ago = None
while True:
root, times, apicache = self.fetch_api(url, params)
if root is None:
#show_error('fetch_transactions', 'HTTP error', times)
return
# cached and completed ok? pass.
if apicache and apicache.completed_ok:
return
err = root.find('error')
if err is not None:
# Fuck it, the API flat out lies about cache times
if err.attrib['code'] not in ('101', '103'):
show_error('fetch_transactions', err, times)
break
# We need to stop asking for data if the oldest transaction entry is older
# than one week
if one_week_ago is None:
one_week_ago = times['current'] - datetime.timedelta(7)
rows = root.findall('result/rowset/row')
if not rows:
break
# Make a transaction id:row map
t_map = OrderedDict()
for row in rows:
transaction_id = int(row.attrib['transactionID'])
transaction_time = parse_api_date(row.attrib['transactionDateTime'])