-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAuthBackloader.py
More file actions
280 lines (213 loc) · 7.77 KB
/
AuthBackloader.py
File metadata and controls
280 lines (213 loc) · 7.77 KB
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/python3
import logging, time, traceback, os, sys
from datetime import datetime
from datetime import timedelta
from dateutil import tz
import urllib
import configparser
#import MySQLdb
from wildapricot_api import WaApiClient
from mailer import MailBot
#from Database import Database
#os.chdir(config.get('files', 'installDirectory'))
WA_API = WaApiClient()
tzlocal = tz.gettz('CST')
class AuthConv():
def __init__(self, api_key):
self.options = {"API_key":api_key}
while(not WA_API.ConnectAPI(self.options["API_key"])):
time.sleep(5)
self.working_file_name = 'unprocessed_id_list.txt'
def SendEmail(self, to_address, template, replacements):
template.seek(0)
t = template.read().format(**replacements)
subject = t.split('----')[0]
message = t.split('----')[1]
mb.send(to_address, subject , message)
# db.AddLogEntry(event['Name'].strip(), registrant_first_name +' '+ registrant_last_name, registrantEmail[0],
# action="Send email with subject `%s`" %(subject.strip()))
def WriteUnprocessedIDs(self, id_list):
with open(self.working_file_name, 'w') as f:
for _id in id_list:
f.write(str(_id) + '\n')
def ReadUnprocessedIDs(self):
with open(self.working_file_name, 'r') as f:
id_list = [int(line.rstrip('\n')) for line in f]
return id_list
script_start_time = datetime.now()
#db = Database()
#current_db = db.GetAll()
#for entry in current_db:
# print (entry)
config = configparser.ConfigParser()
config.read('config.ini')
print(config.items('api'))
print(config.items('thresholds'))
converter = AuthConv(config.get('api','key'))
mb = MailBot(config.get('email','username'), config.get('email','password'))
mb.setDisplayName(config.get('email', 'displayName'))
mb.setAdminAddress(config.get('email', 'adminAddress'))
if False:
pass
else:
try:
valid_authorizations = ['Woodshop','Metalshop','Forge','LaserCutter',\
'Mig welding', 'Tig welding', 'Stick welding', 'Manual mill',\
'Plasma', 'Metal lathes', 'CNC Plasma', 'Intro Tormach', 'Full Tormach',
'FDM 3D Printers']
auth_groups = [group['Name'] for group in WA_API.GetMemberGroups() if group['Name'].strip().split('_')[0] == 'auth']
print(auth_groups)
total_class_auths = 0
unauthorized_attendees = 0
#WA_API.SetAuthorizations(38657966,['Forge'],['2018-01-01'])
events = WA_API.GetPastEvents()
# contacts = WA_API.GetAllContacts()
# for contact in contacts:
# print(contact['FieldValues'])
# authorization = 'CNC Plasma'
authorization = 'FDM 3D Printers'
# authorization = 'LaserCutter'
assert authorization in valid_authorizations, "Not a valid authorization"
if authorization == 'LaserCutter':
search_strings = ['laser cutter certification', 'laser cutter authorization class', 'laser cutting basics', 'laser cutting quick authorization']
elif authorization == 'CNC Plasma':
search_strings = ['cnc plasma cutting basics', 'cnc plasma with jeremiah burian']
elif authorization == 'FDM 3D Printers':
search_strings = ['3d printing basics']
for event in events:
match = False
# print(event['Name'])
for string in search_strings:
if event['Name'].lower().find(string) == 0:
match = True
break
if match:
print(event['Name'], event['StartDate'])
registrants = WA_API.GetRegistrantsByEventID(event['Id'])
time.sleep(2)
for registrant in registrants:
if registrant['IsCheckedIn']:
total_class_auths += 1
current_authorizations = WA_API.GetAuthorizations(registrant['Contact']['Id'])
time.sleep(2)
if current_authorizations:
already_authorized = True if current_authorizations.find(authorization)>=0 else False
else:
already_authorized = False
if not already_authorized:
unauthorized_attendees += 1
WA_API.SetAuthorizations(registrant['Contact']['Id'],[authorization],[event["StartDate"].split('T')[0]])
time.sleep(2)
print(registrant["DisplayName"], event["StartDate"].split('T')[0], already_authorized)
time.sleep(5)
print("\n\n")
else:
pass
#print(event['Name'], event['StartDate'])
print(str(unauthorized_attendees)+'/'+str(total_class_auths))
sys.exit()
try:
contactIDs = converter.ReadUnprocessedIDs()
print('Continuing previous id list')
if not contactIDs:
contactIDs = WA_API.GetAllContactIDs()
except:
contactIDs = WA_API.GetAllContactIDs()
#contactIDs = [42705673,38657966,38043528,32777335,42819834]
while contactIDs:
converter.WriteUnprocessedIDs(contactIDs)
contactID = contactIDs.pop()
contactIDs.append(contactID)
try:
has_authorizations=False
user_authorizations=[]
while(1):
contact = WA_API.GetContactById(contactID)
if contact:
break
time.sleep(5)
print('\n\n',contact["FirstName"], contact["LastName"])
#if contact["FirstName"] != "Testy":
# continue
for field in contact["FieldValues"]:
if field["FieldName"] == "authorizations":
if field["Value"] == '' or field["Value"] == None:
print("No authorizations")
else:
for authorization in field["Value"].split('\n'):
authorization_name = authorization[0:-11].strip()
if authorization_name != '':
if authorization_name in valid_authorizations:
has_authorizations=True
user_authorizations.append(authorization_name)
else:
#print(contact["FirstName"], contact["LastName"],'>')
print("ANOMALY FOUND:")
print(authorization_name)
print(authorization)
is_member = True
try:
contact["MembershipEnabled"]
except KeyError:
is_member = False
if is_member:
if contact['Status'] == "Lapsed":
print('changing lapsed member Non-Member')
while(1):
if WA_API.SetContactMembership(contact['Id'],'813239'):
break
time.sleep(5)
#print("Member:True")
else:
pass
#print("Member:False")
#check if contact has authorizations
#if contact has authorizations
if not has_authorizations:
contactIDs.pop()
continue
if has_authorizations:
print("Has authorizations:", user_authorizations)
#if contact is not member
if not is_member:
#add contact to Non-Member membership level
while(1):
if WA_API.SetContactMembership(contact['Id'],'813239'):
break
time.sleep(5)
#TODO:approve membership
auth_group_list = []
for auth in user_authorizations:
auth_group_list.append(auth_map[auth])
print(auth_group_list)
while(1):
if WA_API.SetMemberGroups(contact['Id'], auth_group_list):
break
time.sleep(5)
#read list of authorizations from contact membership field
#add contact to appropriate groups according to authorizations
contactIDs.pop()
time.sleep(1)
except KeyboardInterrupt:
raise
except:
raise
print('CAUGHT EXCEPTION; CONTINUING')
print(contactIDs)
converter.WriteUnprocessedIDs(contactIDs)
#result = WA_API.GetContactById(test_user_id)
#print(result)
#WA_API.SetContactMembership(test_user_id)
#WA_API.SetEventAccessControl(test_event_id, restricted=True, any_group=False, group_ids=[130906])
#WA_API.SetContactGroups(test_user_id)
# WA_API.ProcessUnpaidRegistrants(upcoming_events)
# WA_API.SendEventReminders(upcoming_events)
# print(config.get('email', 'adminAddress'))
# message = "Registration Monitor completed successfully"
# mb.send([config.get('email', 'adminAddress')], "Registration Monitor Success", message)
except Exception as e:
message = "The following exception was thrown:\r\n\r\n" + str(e) + "\r\n\r\n" + traceback.format_exc()
mb.send([config.get('email', 'adminAddress')], "Authorization Backloader Crash", message)
raise
# if datetime.now() - script_start_time > timedelta(minutes=60):
# exit()