reworking of file structure
[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, url='https://dl.dropboxusercontent.com/u/32733446/cards.json'):
19 logging.debug('init card database')
20
21 json_path = 'cards.json'
22
23 for name, id in CardDb.set_ids.iteritems():
24 CardDb.set_names[id] = name
25
26 if not os.path.isfile(json_path) or time.time() - os.path.getmtime(json_path) >= 24 * 60 * 60:
27 self.download_cards_json(json_path, url)
28
29 self._db = self.parse_cards_json(json_path)
30 self._by_name = {}
31 self._by_id = {}
32
33 for card in self._db:
34 self._by_name[(card['title'] + (', ' + card['subtitle'] if card.get('subtitle') is not None else '')).lower()] = card
35 self._by_id[card['id'].lower()] = card
36 if card.has_key('allIds'):
37 for alt_id in card['allIds']:
38 self._by_id['%s%s' % (CardDb.set_ids[card['set']], alt_id.lower())] = card
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 download_cards_json(self, json_path, url):
59 logging.debug('downloading %s from %s', json_path, url)
60 try:
61 urllib.urlretrieve(url, json_path)
62 except:
63 logging.exception('failed')
64
65 CARDDB = CardDb()