This repository has been archived by the owner on Jul 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcardDB.py
189 lines (146 loc) · 5.97 KB
/
cardDB.py
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
import logging as log
import itertools
import json
import os
import string
import time
import requests
import formatter
class CardDB:
"""Wrapper around a PRAW reddit instance."""
DUELS_CMD = 'd!'
VANILLA_CMD = 'c!'
def __init__(self, *,
constants,
cardJSON='data/cards.json',
duelsJSON='data/duels.json',
vanillaJSON='data/vanilla.json',
tokenJSON='data/tokens.json',
tempJSON='data/tempinfo.json',
tempJSONUrl=None):
"""Initialize an instance of CardDB.
:param cardJSON: file containing cards
:param tokenJSON: file containing tokens
:param tempJSON: optional file containing more cards
"""
self.constants = constants
self.cardJSON = cardJSON
self.duelsJSON = duelsJSON
self.vanillaJSON = vanillaJSON
self.tokenJSON = tokenJSON
self.tempJSON = tempJSON
self.tempJSONUrl = tempJSONUrl
self.tokens = []
self.__db = {}
self.__tempDate = 0
self.__nextUrlRefresh = 0
self.__etag = None
self.__load()
def __load(self):
# load cards
with open(self.cardJSON, 'r', encoding='utf8') as file:
cards = json.load(file)
with open(self.tokenJSON, 'r', encoding='utf8') as file:
tokens = json.load(file)
# json to db full of text
for name, card in itertools.chain(cards.items(), tokens.items()):
clean = CardDB.cleanName(name)
if clean in self.__db:
log.error("load() duplicate name, already in the db: %s",
clean)
raise Exception('duplicate card: ' + clean)
self.__db[clean] = formatter.createCardText(card, self.constants)
self.tokens = [CardDB.cleanName(name) for name in tokens.keys()]
# add duels cards as with command prefix
with open(self.duelsJSON, 'r', encoding='utf8') as file:
duels = json.load(file)
for name, card in duels.items():
clean = self.DUELS_CMD + CardDB.cleanName(name)
if clean in self.__db:
log.error("load() duplicate name, already in the db: %s", clean)
raise Exception('duplicate card: ' + clean)
self.__db[clean] = formatter.createCardText(card, self.constants)
# add vanilla cards as with command prefix
with open(self.vanillaJSON, 'r', encoding='utf8') as file:
duels = json.load(file)
for name, card in duels.items():
clean = self.VANILLA_CMD + CardDB.cleanName(name)
if clean in self.__db:
log.error("load() duplicate name, already in the db: %s", clean)
raise Exception('duplicate card: ' + clean)
self.__db[clean] = formatter.createCardText(card, self.constants)
# finally load temp file
self.refreshTemp()
def refreshTemp(self):
"""Reload cards from tempJSON and overwrite existing."""
if self.tempJSONUrl:
# online file
# throttle to check every ten minutes
if time.time() < self.__nextUrlRefresh:
return
self.__nextUrlRefresh = time.time() + (10 * 60)
try:
headers = {}
if self.__etag:
headers = { 'If-None-Match' : self.__etag }
res = requests.get(self.tempJSONUrl, headers=headers)
if res.status_code == 200:
log.debug("refreshTemp() online: 200, refreshing")
self.__etag = res.headers.get("etag")
for name, card in res.json().items():
clean = CardDB.cleanName(name)
self.__db[clean] = formatter.createCardText(card,
self.constants)
if res.status_code == 304:
log.debug("refreshTemp() online: 304 no changes")
return
except Exception as e:
log.debug("refreshTemp() failed online: %s", e)
# offline file
if not os.path.isfile(self.tempJSON):
return
currentDate = os.path.getmtime(self.tempJSON)
if currentDate == self.__tempDate:
return
self.__tempDate = currentDate
try:
with open(self.tempJSON, 'r', encoding='utf8') as file:
for name, card in json.load(file).items():
clean = CardDB.cleanName(name)
self.__db[clean] = formatter.createCardText(card,
self.constants)
except Exception as e:
log.debug("refreshTemp() failed: %s", e)
def cleanName(name):
"""ignore all special characters, numbers, whitespace, case"""
return ''.join(c for c in name.lower() if c in string.ascii_lowercase)
def cardNames(self):
"""all cards currently in db"""
allNames = set()
for name in self.__db.keys():
if name.startswith(self.DUELS_CMD):
name = name[len(self.DUELS_CMD):]
elif name.startswith(self.VANILLA_CMD):
name = name[len(self.VANILLA_CMD):]
allNames.add(name)
return list(allNames)
def __contains__(self, item):
# direct hit or duels hit
return item in self.__db \
or (self.DUELS_CMD + item) in self.__db \
or (self.VANILLA_CMD + item) in self.__db
def __getitem__(self, key):
try:
# get direct hit first (might be with hd!)
return self.__db[key]
except Exception as e:
# try vanilla as fallback
card = self.__db.get(self.VANILLA_CMD + key)
if card:
return card
# try duels as fallback
card = self.__db.get(self.DUELS_CMD + key)
if card:
return card
# raise original key error
raise e