bacon
[mlpccg-meta.git] / mlpccg / CardDb.py
1 import json
2 import os
3 import urllib
4 import logging
5
6 class CardDb:
7 set_ids = {
8 'Premiere': 'pr',
9 'Canterlot Nights': 'cn',
10 'Rock \'n Rave': 'rr',
11 'Celestial Solstice': 'cs',
12 'Crystal Games': 'cg'
13 }
14
15 set_names = {} # generated
16
17 def __init__(self, json_path='cards.json', extra_path='cards_extra.json'):
18 logging.debug('init card database')
19
20 for name, id in CardDb.set_ids.iteritems():
21 CardDb.set_names[id] = name
22
23 if not os.path.isfile(json_path) or time.time() - os.path.getmtime(json_path) >= 24 * 60 * 60:
24 self.download_cards_json(json_path)
25
26 self._db = self.parse_cards_json(json_path)
27 self._by_name = {}
28 self._by_id = {}
29
30 for card in self._db:
31 self._by_name[(card['title'] + (', ' + card['subtitle'] if card.get('subtitle') is not None else '')).lower()] = card
32 self._by_id[card['id'].lower()] = card
33 if card.has_key('allIds'):
34 for alt_id in card['allIds']:
35 self._by_id['%s%s' % (CardDb.set_ids[card['set']], alt_id.lower())] = card
36
37 self.integrate_cards_extra_json(extra_path)
38
39 def all(self):
40 return self._db
41
42 def by_id(self, id):
43 return self._by_id[id.lower()]
44
45 def by_name(self, name):
46 return self._by_name[name.lower()]
47
48 def parse_cards_json(self, json_path):
49 logging.debug('parsing %s', json_path)
50 try:
51 with open(json_path) as f:
52 return json.load(f)
53 except:
54 logging.exception('failed')
55 return []
56
57 def integrate_cards_extra_json(self, extra_path):
58 logging.debug('parsing %s', extra_path)
59 try:
60 with open(extra_path) as f:
61 extra = json.load(f)
62 for card_id, data in extra.items():
63 try:
64 self._by_id[card_id.lower()].update(data)
65 except:
66 logging.exception('failed extra data for %s', card_id)
67
68 except IOError:
69 logging.exception('failed')
70
71 def download_cards_json(self, json_path='cards.json', url='https://dl.dropboxusercontent.com/u/32733446/cards.json'):
72 logging.debug('downloading %s from %s', json_path, url)
73 try:
74 urllib.urlretrieve(url, json_path)
75 except:
76 logging.exception('failed')
77
78 CARDDB = CardDb()