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