-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathitemdb_tool.py
More file actions
executable file
·1401 lines (1053 loc) · 47 KB
/
itemdb_tool.py
File metadata and controls
executable file
·1401 lines (1053 loc) · 47 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/bin/python
from __future__ import print_function
import collections
from collections import OrderedDict
import ConfigParser
import inspect
import io
import json
import mysql.connector
from mysql.connector import errorcode
from optparse import OptionParser, BadOptionError
import os.path
import re
import sys
DEBUG_OUTPUT = True
LEGACY_CATEGORY_NAME = "Legacy Equipment"
LEGACY_CATEGORY_DESCRIPTION = "Legacy and refund equipment which is no longer available"
# TODO:
# - Add transactions. We don't want to die halfway through a massive import and break stuff
# Non-whiny OptionParser, stolen from http://stackoverflow.com/a/13870300
class PassThroughOptionParser(OptionParser):
def _process_long_opt(self, rargs, values):
try:
OptionParser._process_long_opt(self, rargs, values)
except BadOptionError, err:
self.largs.append(err.opt_str)
def _process_short_opts(self, rargs, values):
try:
OptionParser._process_short_opts(self, rargs, values)
except BadOptionError, err:
self.largs.append(err.opt_str)
def debug(message):
if DEBUG_OUTPUT:
print(message)
def printerr(message):
print(message, file=sys.stderr)
def safe_bool(input, default=False):
try:
return input.lower() in ['true', 't', 'yes', 'y', '1'] if isinstance(input, basestring) else bool(input)
except ValueError:
return default
except TypeError:
return default
def safe_int(input, default=0):
try:
return int(input)
except ValueError:
return default
except TypeError:
return default
def safe_str(input, default=None):
try:
return str(input) if input is not None else default
except ValueError:
return default
except TypeError:
return default
def safe_case_haskey(map, value):
for ikey, ival in map.items():
if (ikey.lower() == key.lower() if isinstance(ikey, basestring) and isinstance(key, basestring) else ikey == key):
return True
return False
def safe_case_get(map, key, func=None, default=None):
for ikey, ival in map.items():
if (ikey.lower() == key.lower() if isinstance(ikey, basestring) and isinstance(key, basestring) else ikey == key):
return func(ival, default) if func is not None else ival
return default
def safe_case_remove(map, key):
for ikey, ival in map.items():
if (ikey.lower() == key.lower() if isinstance(ikey, basestring) and isinstance(key, basestring) else ikey == key):
del map[ikey]
return ival
return None
def safe_case_contains(list, value):
for ival in list:
if (value.lower() == ival.lower() if isinstance(ival, basestring) and isinstance(value, basestring) else value == ival):
return True
return False
def rcomp(source, update):
def rcomp_impl(source, update):
if isinstance(source, collections.Mapping):
if not isinstance(update, collections.Mapping):
return False
for skey, sval in source.items():
found = False
for ukey, uval in update.items():
if skey == ukey:
found = True
if not rcomp_impl(sval, uval):
return False
break
if not found:
return False
elif isinstance(source, collections.Sequence) and not isinstance(source, basestring):
if not (isinstance(update, collections.Sequence) and not isinstance(update, basestring)):
return False
for sval in source:
found = False
for uval in update:
if rcomp_impl(sval, uval):
found = True
break
if not found:
return False
else:
return source == update
return True
return rcomp_impl(source, update) and rcomp_impl(update, source)
def standardize_types(types):
if not isinstance(types, collections.Mapping):
return None
stdtypes = OrderedDict()
for type, max in sorted(types.items()):
type = safe_str(type)
max = safe_int(max, None)
if type is not None and max is not None:
stdtypes[type] = max
return stdtypes
def standardize_item(item):
if not isinstance(item, collections.Mapping):
return None
stditem = OrderedDict()
stditem["name"] = safe_case_get(item, "name", safe_str, None)
stditem["short_description"] = safe_case_get(item, "short_description", safe_str, None)
stditem["long_description"] = safe_case_get(item, "long_description", safe_str, None)
stditem["buy_price"] = safe_case_get(item, "buy_price", safe_int, 0)
stditem["sell_price"] = safe_case_get(item, "sell_price", safe_int, 0)
stditem["exp_required"] = safe_case_get(item, "exp_required", safe_int, 0)
stditem["ships_allowed"] = []
stditem["max"] = safe_case_get(item, "max", safe_int, 0)
stditem["delay_write"] = int(safe_case_get(item, "delay_write", safe_bool, False))
stditem["ammo"] = safe_case_get(item, "ammo", safe_str, None)
stditem["needs_ammo"] = int(safe_case_get(item, "needs_ammo", safe_bool, False))
stditem["min_ammo"] = safe_case_get(item, "min_ammo", safe_int, 0)
stditem["affects_sets"] = int(safe_case_get(item, "affects_sets", safe_bool, False))
stditem["resend_sets"] = int(safe_case_get(item, "resend_sets", safe_bool, False))
stditem["types"] = OrderedDict()
stditem["properties"] = OrderedDict()
stditem["events"] = []
stditem["categories"] = OrderedDict()
stditem["stores"] = []
ships_allowed = safe_case_get(item, "ships_allowed")
if isinstance(ships_allowed, collections.Sequence):
for ship in ships_allowed:
ship = safe_int(ship)
if ship > 0 and ship < 9:
stditem["ships_allowed"].append(ship)
stditem["ships_allowed"].sort()
else:
ships_allowed = safe_int(ships_allowed)
if ships_allowed is not None:
# convert bit field to friendly numbers for allowed ship types
for ship in range(0, 8):
if ships_allowed & (1 << ship):
stditem["ships_allowed"].append(ship + 1)
item_types = safe_case_get(item, "types")
if isinstance(item_types, collections.Mapping):
for key, val in item_types.items():
val = safe_int(val, None)
if isinstance(key, basestring) and val is not None:
stditem["types"][key] = val
item_properties = safe_case_get(item, "properties")
if isinstance(item_properties, collections.Mapping):
for key, val in item_properties.items():
val = safe_int(val, None) if not isinstance(val, basestring) else val
if isinstance(key, basestring) and val is not None:
stditem["properties"][key] = val
item_events = safe_case_get(item, "events")
if isinstance(item_events, collections.Sequence):
for event in item_events:
if isinstance(event, collections.Mapping):
stdevent = OrderedDict()
stdevent["event"] = safe_case_get(event, "event", safe_str)
stdevent["action"] = safe_case_get(event, "action", safe_int)
stdevent["data"] = safe_case_get(event, "data", safe_int)
stdevent["message"] = safe_case_get(event, "message", safe_str)
if stdevent["event"] is not None:
stditem["events"].append(stdevent)
item_categories = safe_case_get(item, "categories")
if isinstance(item_categories, collections.Mapping):
for key, val in item_categories.items():
val = safe_int(val, None)
if isinstance(key, basestring) and val is not None:
stditem["categories"][key] = val
item_stores = safe_case_get(item, "stores")
if isinstance(item_stores, collections.Sequence):
for store in item_stores:
if isinstance(store, basestring):
stditem["stores"].append(store)
stditem["stores"].sort()
return stditem
class ItemDB:
def __init__(self, dbc, arena_id):
self.dbc = dbc
self.arena_id = arena_id
def _start_transaction(self):
pass
def _commit_transaction(self):
pass
def _rollback_transaction(self):
pass
def help(self, method_name):
"""
Displays documentation for the specified method
"""
if isinstance(method_name, basestring) and hasattr(self, method_name):
method = getattr(self, method_name)
help(method)
else:
print("No such method: %s" % method_name, file=sys.stderr)
def execute_query(self, query, params=None):
cursor = self.dbc.cursor()
cursor.execute(query, params)
results = cursor.fetchall()
cursor.close()
return results
def execute_update(self, statement, params=None):
cursor = self.dbc.cursor()
cursor.execute(statement, params)
results = cursor.rowcount
cursor.close()
return results
def execute_insert(self, statement, params=None):
cursor = self.dbc.cursor()
cursor.execute(statement, params)
results = cursor.lastrowid
cursor.close()
return results
def get_item_id(self, item_name, include_orphans=False):
query = """
SELECT i.id
FROM hs_items i
LEFT JOIN hs_category_items ci ON i.id = ci.item_id
LEFT JOIN hs_categories c ON ci.category_id = c.id
WHERE i.name = %s AND
"""
if safe_bool(include_orphans):
query += " (c.arena = %s OR c.arena IS NULL)"
else:
query += " c.arena = %s"
for (id,) in self.execute_query(query, (safe_str(item_name), self.arena_id)):
return id
return None
def get_item_ids(self, include_orphans=False):
query = """
SELECT i.id
FROM hs_items i
LEFT JOIN hs_category_items ci ON i.id = ci.item_id
LEFT JOIN hs_categories c ON ci.category_id = c.id
WHERE c.arena = %s
"""
if safe_bool(include_orphans):
query += " OR c.arena IS NULL"
item_ids = []
for (id,) in self.execute_query(query, (self.arena_id,)):
item_ids.append(id)
item_ids.sort()
return item_ids
def get_type_id(self, type):
for (id,) in self.execute_query("SELECT id FROM hs_item_types WHERE name = %s", (safe_str(type),)):
return id
return None
def create_type(self, type, max=0):
type = safe_str(type)
max = safe_int(max, 0)
result = False
if type is not None:
if len(self.execute_query("SELECT id FROM hs_item_types WHERE name = %s", (type,))) == 0:
result = bool(self.execute_update("INSERT INTO hs_item_types(name, max) VALUES(%s, %s)", (type, max)))
else:
result = bool(self.execute_update("UPDATE hs_item_types SET max = %s WHERE name = %s", (max, type)))
return result
def delete_type(self, type_id):
if isinstance(type_id, basestring) and not type_id.isdigit():
type_id = self.get_type_id(type_id)
else:
type_id = safe_str(type_id)
result = False
if type_id is not None:
result = bool(self.execute_update("DELETE FROM hs_item_types WHERE id = %s", (type_id,)))
if result:
self.execute_update("DELETE FROM hs_item_type_assoc WHERE type_id = %s", (type_id,))
return result
def get_types(self):
types = {}
for (type, max) in self.execute_query("SELECT name, max FROM hs_item_types"):
types[type] = max
return OrderedDict(sorted(types.items()))
def get_item_types(self, item_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
query = """
SELECT t.name, it.qty
FROM hs_item_types t
INNER JOIN hs_item_type_assoc it ON it.type_id = t.id
WHERE it.item_id = %s
"""
types = {}
for (type, quantity) in self.execute_query(query, (item_id,)):
types[type] = quantity
return OrderedDict(sorted(types.items()))
def add_type_to_item(self, item_id, type_id, count=1):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
if isinstance(type_id, basestring) and not type_id.isdigit():
type_id = self.get_type_id(type_id)
count = safe_int(count, 1)
result = False
if item_id is not None and type_id is not None:
if len(self.execute_query("SELECT qty FROM hs_item_type_assoc WHERE item_id = %s AND type_id = %s", (item_id, type_id))) > 0:
result = bool(self.execute_update(
"UPDATE hs_item_type_assoc SET qty = %s WHERE item_id = %s AND type_id = %s",
(count, item_id, type_id)
))
else:
result = bool(self.execute_update(
"INSERT INTO hs_item_type_assoc(item_id, type_id, qty) VALUES(%s, %s, %s)",
(item_id, type_id, count)
))
return result
def remove_type_from_item(self, item_id, type_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
if isinstance(type_id, basestring) and not type_id.isdigit():
type_id = self.get_type_id(type_id)
result = False
if item_id is not None and type_id is not None:
result = bool(self.execute_update("DELETE FROM hs_item_type_assoc WHERE item_id = %s AND type_id = %s", (item_id, type_id)))
return result
def get_item_properties(self, item_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
query = """
SELECT name, value, absolute, ignore_count
FROM hs_item_properties WHERE item_id = %s
"""
properties = {}
for (name, value, absolute, ignore_count) in self.execute_query(query, (item_id,)):
if ignore_count:
value = "!" + str(value)
if absolute:
value = "=" + str(value)
properties[name] = value
return properties
def add_item_property(self, item_id, property, value, absolute=False, ignore_count=False):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
property = safe_str(property)
value = safe_str(value)
result = False
if item_id is not None and property is not None:
absolute = int(safe_bool(absolute))
ignore_count = int(safe_bool(ignore_count))
# Process inline property updates
while len(value) > 0:
if value[0] == '=':
absolute = True
value = value[1:]
elif value[0] == '!':
ignore_count = True
value = value[1:]
else:
break
value = safe_int(value)
# if the property already exists, we should update it instead
if len(self.execute_query("SELECT value FROM hs_item_properties WHERE item_id = %s AND name = %s", (item_id, property))) > 0:
result = bool(self.execute_update("""
UPDATE hs_item_properties
SET value = %s, absolute = %s, ignore_count = %s
WHERE item_id = %s AND name = %s
""", (value, absolute, ignore_count, item_id, property)))
else:
result = bool(self.execute_update(
"INSERT INTO hs_item_properties(item_id, name, value, absolute, ignore_count) VALUES(%s, %s, %s, %s, %s)",
(item_id, property, value, absolute, ignore_count)
))
return result
def remove_item_property(self, item_id, property):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
property = safe_str(property)
removed = False
if item_id is not None and property:
removed = bool(self.execute_update("DELETE FROM hs_item_properties WHERE item_id = %s AND name = %s", (item_id, property)))
return removed
def get_item_events(self, item_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
query = """
SELECT event, action, data, message
FROM hs_item_events WHERE item_id = %s
"""
events = []
for (name, action, data, message) in self.execute_query(query, (item_id,)):
event = OrderedDict()
event["event"] = name
event["action"] = action
event["data"] = data
event["message"] = message
events.append(event)
return events
def add_item_event(self, item_id, event, action_id, data, message=None):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
event = safe_str(event)
action_id = safe_int(action_id)
data = safe_int(data)
message = safe_str(message)
result = False
if item_id is not None and event:
if len(self.execute_query("SELECT data FROM hs_item_events WHERE item_id = %s AND event = %s AND action = %s", (item_id, event, action_id))) > 0:
result = bool(self.execute_update("""
UPDATE hs_item_events
SET data = %s, message = %s
WHERE item_id = %s AND event = %s AND action = %s
""", (data, message, item_id, event, action_id)))
else:
result = bool(self.execute_update(
"INSERT INTO hs_item_events (item_id, event, action, data, message) VALUES (%s, %s, %s, %s, %s)",
(item_id, event, action_id, data, message)
))
return result
def delete_item_event(self, item_id, event, action_id=None):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
event = safe_str(event)
action_id = safe_int(action_id, None)
result = False
if item_id is not None and event:
if action_id is not None:
result = bool(self.execute_update("DELETE FROM hs_item_events WHERE item_id = %s AND event = %s AND action = %s", (item_id, event, action_id)))
else:
result = bool(self.execute_update("DELETE FROM hs_item_events WHERE item_id = %s AND event = %s", (item_id, event)))
return result
def get_category_id(self, category):
for (id,) in self.execute_query("SELECT id FROM hs_categories WHERE name = %s AND arena = %s", (safe_str(category), self.arena_id)):
return id
return None
def get_category_item_ids(self, category_id):
if isinstance(category_id, basestring) and not category_id.isdigit():
category_id = self.get_category_id(category_id)
items = []
for (item_id,) in self.execute_query("SELECT item_id FROM hs_category_items WHERE category_id = %s ORDER BY `order` ASC", (category_id,)):
items.append(item_id)
return items
def get_category_items(self, category_id):
if isinstance(category_id, basestring) and not category_id.isdigit():
category_id = self.get_category_id(category_id)
items = []
for (item_id,) in self.execute_query("SELECT item_id FROM hs_category_items WHERE category_id = %s ORDER BY `order` ASC", (category_id,)):
items.append(self.get_item(item_id))
return items
def add_category(self, category, description=None, hidden=False, order=None):
category = safe_str(category)
description = safe_str(description, "")
hidden = safe_bool(hidden)
result = False
if category:
current = self.execute_query("SELECT `order` FROM hs_categories WHERE arena = %s AND name = %s", (self.arena_id, category))
if order is not None:
order_exists = len(self.execute_query("SELECT name FROM hs_categories WHERE arena = %s AND `order` = %s", (self.arena_id, order))) > 0
if len(current) > 0:
# shift indexes about to deal with the repositioning
self.execute_update("UPDATE hs_categories SET `order` = `order` - 1 WHERE arena = %s AND `order` > %s", (self.arena_id, current[0][0]))
if order_exists:
self.execute_update("UPDATE hs_categories SET `order` = `order` + 1 WHERE arena = %s AND `order` >= %s", (self.arena_id, order))
result = bool(self.execute_update("UPDATE hs_categories SET `order` = %s WHERE arena = %s AND name = %s", (order, self.arena_id, category)))
else:
if order_exists:
self.execute_update("UPDATE hs_categories SET `order` = `order` + 1 WHERE arena = %s AND `order` >= %s", (self.arena_id, order))
result = bool(self.execute_update(
"INSERT INTO hs_categories (name, description, arena, order, hidden) VALUES (%s, %s, %s, %s, %s)",
(category, description, self.arena_id, order, int(hidden))
))
else:
if len(current) > 0:
# impl note: this is lazy and could be improved
self.execute_update("DELETE FROM hs_categories WHERE arena = %s AND category = %s", (self.arena_id, category))
self.execute_update("UPDATE hs_categories SET `order` = `order` - 1 WHERE arena = %s AND `order` > %s", (self.arena_id, current[0][0]))
# Get the highest index
max_order = self.execute_query("SELECT MAX(`order`) FROM hs_categories WHERE arena = %s", (self.arena_id,))
result = bool(self.execute_update(
"INSERT INTO hs_categories (name, description, arena, `order`, hidden) VALUES (%s, %s, %s, %s, %s)",
(category, description, self.arena_id, safe_int(max_order[0][0], -1) + 1, int(hidden))
))
return result
def get_item_categories(self, item_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
query = """
SELECT c.name, ci.order
FROM hs_categories c
INNER JOIN hs_category_items ci ON ci.category_id = c.id
WHERE ci.item_id = %s
"""
categories = {}
for (category, order) in self.execute_query(query, (item_id,)):
categories[category] = order
return OrderedDict(sorted(categories.items()))
def add_item_to_category(self, item_id, category_id, order=None):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
if isinstance(category_id, basestring) and not category_id.isdigit():
category_id = self.get_category_id(category_id)
order = safe_int(order, None)
result = False
if item_id is not None and category_id is not None:
current = self.execute_query("SELECT `order` FROM hs_category_items WHERE category_id = %s AND item_id = %s", (category_id, item_id))
if order is not None:
order_exists = len(self.execute_query("SELECT item_id FROM hs_category_items WHERE category_id = %s AND `order` = %s", (category_id, order))) > 0
if len(current) > 0:
# shift indexes about to deal with the repositioning
self.execute_update("UPDATE hs_category_items SET `order` = `order` - 1 WHERE category_id = %s AND `order` > %s", (category_id, current[0][0]))
if order_exists:
self.execute_update("UPDATE hs_category_items SET `order` = `order` + 1 WHERE category_id = %s AND `order` >= %s", (category_id, order))
result = bool(self.execute_update(
"UPDATE hs_category_items SET `order` = %s WHERE category_id = %s AND item_id = %s",
(order, category_id, item_id)
))
else:
if order_exists:
self.execute_update("UPDATE hs_category_items SET `order` = `order` + 1 WHERE category_id = %s AND `order` >= %s", (category_id, order))
result = bool(self.execute_update("INSERT INTO hs_category_items (category_id, item_id, `order`) VALUES (%s, %s, %s)", (category_id, item_id, order)))
else:
if len(current) > 0:
# impl note: this is lazy and could be improved
self.execute_update("DELETE FROM hs_category_items WHERE category_id = %s AND item_id = %s", (category_id, item_id))
self.execute_update("UPDATE hs_category_items SET `order` = `order` - 1 WHERE category_id = %s AND `order` > %s", (category_id, current[0][0]))
# Get the highest index
max_order = self.execute_query("SELECT MAX(`order`) FROM hs_category_items WHERE category_id = %s", (category_id,))
result = bool(self.execute_update(
"INSERT INTO hs_category_items (category_id, item_id, `order`) VALUES (%s, %s, %s)",
(category_id, item_id, safe_int(max_order[0][0], -1) + 1)
))
return result
def remove_item_from_category(self, item_id, category_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
if isinstance(category_id, basestring) and not category_id.isdigit():
category_id = self.get_category_id(category_id)
result = False
if item_id is not None and category_id is not None:
current = self.execute_query("SELECT `order` FROM hs_category_items WHERE category_id = %s and item_id = %s", (category_id, item_id))
if len(current) > 0:
self.execute_update("UPDATE hs_category_items SET `order` = `order` - 1 WHERE category_id = %s and `order` > %s", (category_id, current[0][0]))
result = bool(self.execute_update("DELETE FROM hs_category_items WHERE category_id = %s and item_id = %s", (category_id, item_id)))
return result
def get_store_id(self, store):
for (id,) in self.execute_query("SELECT id FROM hs_stores WHERE name = %s AND arena = %s", (safe_str(store), self.arena_id)):
return id
return None
def get_item_stores(self, item_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
query = """
SELECT s.name
FROM hs_stores s
INNER JOIN hs_store_items si ON si.store_id = s.id
WHERE si.item_id = %s
"""
stores = []
for (name,) in self.execute_query(query, (item_id,)):
stores.append(name)
return sorted(stores)
def add_item_to_store(self, item_id, store_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
if isinstance(store_id, basestring) and not store_id.isdigit():
store_id = self.get_store_id(safe_str(store_id))
result = False
if item_id is not None and store_id is not None:
if len(self.execute_query("SELECT store_id FROM hs_store_items WHERE store_id = %s AND item_id = %s", (store_id, item_id))) == 0:
result = bool(self.execute_update("INSERT INTO hs_store_items (store_id, item_id) VALUES (%s, %s)", (store_id, item_id)))
return result
def remove_item_from_store(self, item_id, store_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
if isinstance(store_id, basestring) and not store_id.isdigit():
store_id = self.get_store_id(safe_str(store_id))
result = False
if item_id is not None and store_id is not None:
result = bool(self.execute_update("DELETE FROM hs_store_items WHERE store_id = %s AND item_id = %s", (store_id, item_id)))
return result
def get_item(self, item_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
query = """
SELECT i.id, i.name, i.short_description, i.long_description, i.buy_price, i.sell_price,
i.exp_required, i.ships_allowed, i.max, i.delay_write, i.ammo, i.needs_ammo, i.min_ammo,
i.affects_sets, i.resend_sets
FROM hs_items i
INNER JOIN hs_category_items ci ON i.id = ci.item_id
INNER JOIN hs_categories c ON ci.category_id = c.id
WHERE c.arena = %s AND i.id = %s
"""
item = None
for (id, name, short_description, long_description, buy_price, sell_price, exp_required, \
ships_allowed, max, delay_write, ammo, needs_ammo, min_ammo, affects_sets, resend_sets) \
in self.execute_query(query, (self.arena_id, item_id)):
# We have to create these in a specific order if we want them to output logically:
item = OrderedDict()
item["name"] = name
item["short_description"] = short_description
item["long_description"] = long_description
item["buy_price"] = buy_price
item["sell_price"] = sell_price
item["exp_required"] = exp_required
item["ships_allowed"] = []
item["max"] = max
item["delay_write"] = safe_bool(delay_write, False)
item["ammo"] = None
item["needs_ammo"] = safe_bool(needs_ammo, False)
item["min_ammo"] = min_ammo
item["affects_sets"] = safe_bool(affects_sets, False)
item["resend_sets"] = safe_bool(resend_sets, False)
# Convert ammo to an item name
ammo_item = self.get_item(ammo)
if ammo_item is not None:
item["ammo"] = ammo_item["name"]
# convert bit field to friendly numbers for allowed ship types
for ship in range(0, 8):
if ships_allowed & (1 << ship):
item["ships_allowed"].append(ship + 1)
item["types"] = self.get_item_types(item_id)
item["properties"] = self.get_item_properties(item_id)
item["events"] = self.get_item_events(item_id)
item["categories"] = self.get_item_categories(item_id)
item["stores"] = self.get_item_stores(item_id)
break
return item
def get_item_player_count(self, item_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
query = """
SELECT COUNT(DISTINCT ps.player_id)
FROM hs_player_ships ps
INNER JOIN hs_player_ship_items psi ON ps.id = psi.ship_id
WHERE psi.item_id = %s
"""
for (count,) in self.execute_query(query, (item_id,)):
return count
return 0
def get_item_ship_count(self, item_id):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
query = """
SELECT COUNT(ship_id)
FROM hs_player_ship_items
WHERE item_id = %s
"""
for (count,) in self.execute_query(query, (item_id,)):
return count
return 0
def insert_item(self, item):
item = standardize_item(item)
result = False
if item is not None and item["name"] is not None:
if self.get_item_id(item["name"]) is not None:
return False
self._start_transaction()
# build ship mask:
ships_mask = 0
for ship in item["ships_allowed"]:
ships_mask = ships_mask | (1 << (ship - 1))
# Convert ammo to item id
ammo_id = self.get_item_id(item["ammo"]) or 0
# insert base item info
item_id = self.execute_insert("""
INSERT INTO hs_items(name, short_description, long_description, buy_price, sell_price,
exp_required, ships_allowed, max, delay_write, ammo, needs_ammo, min_ammo, affects_sets,
resend_sets) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (item["name"], item["short_description"], item["long_description"], item["buy_price"],
item["sell_price"], item["exp_required"], ships_mask, item["max"], item["delay_write"],
ammo_id, item["needs_ammo"], item["min_ammo"], item["affects_sets"], item["resend_sets"])
)
if item_id is not None:
result = True
# add item types
for type, count in item["types"].items():
result = result and self.add_type_to_item(item_id, type, count)
if not result:
debug("failed to insert type: %s" % type)
break
# add item properties
if result:
for property, value in item["properties"].items():
result = result and self.add_item_property(item_id, property, value)
if not result:
debug("failed to insert property: %s" % property)
break
# add item events
if result:
for event in item["events"]:
result = result and self.add_item_event(item_id, event["event"], event["action"], event["data"], event["message"])
if not result:
debug("failed to insert event")
break
# add item to categories
if result:
for category, order in item["categories"].items():
result = result and self.add_item_to_category(item_id, category, order)
if not result:
debug("failed to insert category: %s" % category)
break
# add item to stores
if result:
for store in item["stores"]:
result = result and self.add_item_to_store(item_id, store)
if not result:
debug("failed to insert store: %s" % store)
break
if result:
self._commit_transaction()
else:
self._rollback_transaction()
return result
def update_item(self, item_id, item):
if isinstance(item_id, basestring) and not item_id.isdigit():
item_id = self.get_item_id(item_id) or self.get_item_id(item_id, True)
db_item = self.get_item(item_id)
item = standardize_item(item)
change_count = 0
if db_item is not None and item is not None and item["name"] is not None:
self._start_transaction()
# build ship mask:
ships_mask = 0
for ship in item["ships_allowed"]:
ships_mask = ships_mask | (1 << (ship - 1))
# Convert ammo to item id
ammo_id = self.get_item_id(item["ammo"]) or 0
# insert base item info
change_count += self.execute_update("""
UPDATE hs_items SET name = %s, short_description = %s, long_description = %s, buy_price = %s,
sell_price = %s, exp_required = %s, ships_allowed = %s, max = %s, delay_write = %s,
ammo = %s, needs_ammo = %s, min_ammo = %s, affects_sets = %s, resend_sets = %s
WHERE id = %s
""", (item["name"], item["short_description"], item["long_description"], item["buy_price"],
item["sell_price"], item["exp_required"], ships_mask, item["max"], item["delay_write"],
ammo_id, item["needs_ammo"], item["min_ammo"], item["affects_sets"], item["resend_sets"],
item_id)
)
# add item types
for type, count in item["types"].items():
change_count += int(self.add_type_to_item(item_id, type, count))
safe_case_remove(db_item["types"], type)
# remove absent types
for type, count in db_item["types"].items():