-
Notifications
You must be signed in to change notification settings - Fork 3
/
passslot.py
198 lines (144 loc) · 6.79 KB
/
passslot.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
189
190
191
192
193
194
195
196
197
198
import os.path, logging, sys, time
try:
import ujson as json
except ImportError:
try:
import simplejson as json
except ImportError:
import json
try:
import requests
except ImportError:
pass
__version_info__ = ('0', '1')
__version__ = '.'.join(__version_info__)
__allowed_images__ = ['icon', 'logo', 'strip', 'thumbnail', 'background', 'footer']
logger = logging.getLogger('passslot')
class PassSlot(object):
app_key = None
base_url = None
debug = True
__instance = None
def __init__(self, app_key, base="https://api.passslot.com", version="v1", debug=False):
self.base_url = "%s/%s" % (base, version)
self.session = requests.session()
if app_key is None and 'PASSSLOT_APPKEY' in os.environ :
app_key = os.environ['PASSSLOT_APPKEY']
if app_key is None:
raise PassSlotException('You must provide a PassSlot App Key')
self.app_key = app_key
self.debug = debug
@classmethod
def start(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = cls(*args, **kwargs)
return cls.__instance
def create_pass_from_template(self, templateId, values=None, images=None):
resource = "/templates/%s/pass" % (templateId)
return self.__create_pass(resource, values, images)
def create_pass_from_template_with_name(self, templateName, values=None, images=None):
resource = "/templates/names/%s/pass" % (requests.compat.quote(templateName))
return self.__create_pass(resource, values, images)
def __create_pass(self, resource, values, images):
multipart = images != None and len(images) > 0
if multipart:
files = []
for type in images:
if type in __allowed_images__ or type + "2x" in __allowed_images__:
files.append((type, images[type]))
else:
logger.warn('Image type %s not available. Image will be ignored.' % type)
files.append(('values', json.dumps(values)))
content = files
else:
content = values
result = self.__call('post', resource, content, multipart)
return Pass(self, **result)
def download_pass(self, pspass):
resource = "/passes/%s/%s" % (pspass.passTypeIdentifier, pspass.serialNumber)
return self.__call('get', resource)
def get_pass_url(self, pspass):
if hasattr(pspass, 'url'):
return pspass.url
resource = "/passes/%s/%s/url" % (pspass.passTypeIdentifier, pspass.serialNumber)
json = self.__call('get', resource)
return json['url']
def email_pass(self, pspass, email):
resource = "/passes/%s/%s/email" % (pspass.passTypeIdentifier, pspass.serialNumber)
content = {'email': email}
self.__call('post', resource, content)
return True
def update_pass_values(self, pspass, values):
resource = "/passes/%s/%s/values" % (pspass.passTypeIdentifier, pspass.serialNumber)
return self.__call('put', resource, values)
def update_pass_value(self, pspass, placeholderName, value):
resource = "/passes/%s/%s/values/%s" % (pspass.passTypeIdentifier, pspass.serialNumber, placeholderName)
content = {'value': value}
return self.__call('put', resource, content)
def __call(self, method, resource, content=None, multipart=False):
headers = {
'User-Agent' : 'PassSlotSDK-Python/%s' % (__version__),
'Accept': 'application/json, */*; q=0.01',
'Authorization' : self.app_key
}
method = method.lower()
kwargs = {}
if method == 'post' or method == 'put':
if multipart:
kwargs['files'] = content
else:
headers['Content-Type'] = 'application/json';
kwargs['data'] = json.dumps(content)
if self.debug:
logger.debug(('> %s %s%s' % (method.upper(), self.base_url, resource)) + ((': %s' % content) if content else '' ))
response = self.session.request(method, self.base_url + resource, headers=headers, **kwargs)
if self.debug:
logger.debug('< %s: %s' % (response.status_code,
response.text if response.headers['content-type'].startswith('application/json')
else '%s (%s bytes)' % (response.headers['content-type'], response.headers['content-length'])
))
if response.status_code == requests.codes.unprocessable:
raise PassSlotApiValidationException(response.json())
if response.status_code == requests.codes.unauthorized:
raise PassSlotApiUnauthorizedException()
if response.status_code < 200 or response.status_code >= 300:
raise PassSlotApiException(response.status_code, response.content)
if response.headers['content-type'].startswith('application/json'):
return response.json()
else:
return response.content
def log(self, *args, **kwargs):
logger.log(self.level, *args, **kwargs)
def __repr__(self):
return '<PassSlot %s>' % self.app_key
class PassSlotObject(object):
def __init__(self, engine, **entries):
self.engine = engine
self.__dict__.update(entries)
class Pass(PassSlotObject):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
def download(self):
self.data = self.engine.download_pass(self)
return self.data
def __repr__(self, *args, **kwargs):
return '<Pass %s/%s>' % (self.passTypeIdentifier, self.serialNumber)
class PassSlotException(Exception):
pass
class PassSlotApiException(PassSlotException):
def __init__(self, status, msg=""):
self.status = status
self.msg = msg
def __str__(self):
return '[%s]: %s' % ( self.status, self.msg)
class PassSlotApiUnauthorizedException(PassSlotApiException):
def __init__(self):
super(self.__class__, self).__init__(401, "Unauthorized. Please check your app key and make sure it has access to the template and pass type id")
class PassSlotApiValidationException(PassSlotApiException):
def __init__(self, response):
msg = ''
if response:
msg = response['message']
for error in response['errors']:
msg += '; ' + error['field'] + ': ' + ', '.join(error['reasons'])
super(self.__class__, self).__init__(422, msg)