-
Notifications
You must be signed in to change notification settings - Fork 0
/
univFuncs.py
338 lines (313 loc) · 12.3 KB
/
univFuncs.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
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
from bson.objectid import ObjectId
import datetime
from app import session, app
import pytz
from aggrFunctions import *
from twilio.twiml.voice_response import VoiceResponse, Connect, Gather
from twilio.rest import Client
import random
import config
import requests
def unsetCompanyID():
try:
session['user']['company_id'] = None
session.modified = True
except:
pass
def validateLogin():
try:
if session['user']:
return True
else:
return False
except:
return False
def validateCompany(companyID):
try:
if str(companyID) in session['companies']:
return True
except:
pass
return False
def simpleUpdateRow(collection, data, post_type, remote_addr):
try:
user_company_id = ObjectId(session['company']['id'])
except:
user_company_id = None
if post_type == 'POST':
try:
if isinstance(data, list):
for x in data:
for key in x:
if '_id' in key:
try:
x[key] = ObjectId(x[key])
except:
x[key] = x[key]
else:
x[key] = x[key]
x['created_at'] = str(datetime.datetime.utcnow())[:-3]
x['updated_at'] = str(datetime.datetime.utcnow())[:-3]
try:
x['updated_by'] = ObjectId(session['user']['user_id'])
except:
x['updated_by'] = ObjectId('613b8a785a2cd24ac1a33bc0')
_id = collection.insert(x)
try:
mongoDB = app.mongo_client['logs']
collections_log_col = mongoDB['collections']
insert_query = {
'user_id':ObjectId(session['user']['user_id']),
'company_id':user_company_id,
'query':x,
'type':'INSERT',
'collection':collection.__dict__['_Collection__name'],
'ip': remote_addr[0],
'created_at':str(datetime.datetime.utcnow())[:-3]
}
collections_log_col.insert(insert_query)
except:
pass
else:
for key in data:
if '_id' in key:
try:
data[key] = ObjectId(data[key])
except:
data[key] = data[key]
data['created_at'] = str(datetime.datetime.utcnow())[:-3]
data['updated_at'] = str(datetime.datetime.utcnow())[:-3]
try:
data['updated_by'] = ObjectId(session['user']['user_id'])
except:
data['updated_by'] = ObjectId('613b8a785a2cd24ac1a33bc0')
_id = collection.insert(data)
try:
mongoDB = app.mongo_client['logs']
collections_log_col = mongoDB['collections']
insert_query = {
'user_id':ObjectId(session['user']['user_id']),
'company_id':user_company_id,
'query':data,
'type':'INSERT',
'collection':collection.__dict__['_Collection__name'],
'ip': remote_addr[0],
'created_at':str(datetime.datetime.utcnow())[:-3]
}
collections_log_col.insert(insert_query)
except:
pass
return {
'Message':'Success',
'id':str(_id)
}
except:
return {'Message':'Failure'}
elif post_type == 'PUT':
try:
try:
if data['updated_at'] == None:
data['updated_at'] = str(datetime.datetime.utcnow())[:-3]
except:
data['updated_at'] = str(datetime.datetime.utcnow())[:-3]
try:
data['updated_by'] = ObjectId(session['user']['user_id'])
except:
data['updated_by'] = ObjectId('613b8a785a2cd24ac1a33bc0')
updateQuery = {
"$set":{}
}
for key in data:
if '_id' in key:
try:
updateQuery["$set"][key] = ObjectId(data[key])
except:
updateQuery["$set"][key] = data[key]
elif key != 'id':
updateQuery["$set"][key] = data[key]
else:
updateQuery["$set"][key] = data[key]
search_query = {
"_id":ObjectId(data['id'])
}
collection.update_one(search_query, updateQuery)
try:
mongoDB = app.mongo_client['logs']
collections_log_col = mongoDB['collections']
insert_query = {
'user_id':ObjectId(session['user']['user_id']),
'company_id':user_company_id,
'query':data,
'type':'UPDATE',
'collection':collection.__dict__['_Collection__name'],
'ip': remote_addr[0],
'created_at':str(datetime.datetime.utcnow())[:-3]
}
collections_log_col.insert(insert_query)
except:
pass
return {
'Message':'Success',
'id':data['id']
}
except:
return {'Message':'Failure'}
elif post_type == 'DELETE':
try:
collection.delete_one({"_id":ObjectId(data['id'])})
try:
mongoDB = app.mongo_client['logs']
collections_log_col = mongoDB['collections']
insert_query = {
'user_id':ObjectId(session['user']['user_id']),
'company_id':user_company_id,
'query':data,
'type':'DELETE',
'collection':collection.__dict__['_Collection__name'],
'ip': remote_addr[0],
'created_at':str(datetime.datetime.utcnow())[:-3]
}
collections_log_col.insert(insert_query)
except:
pass
return {
'Message':'Success',
'id':data['id']
}
except:
return {'Message':'Failure'}
return {'Message':'Failure'}
def convertToJSON(obj):
objData = {}
for key in obj:
if key != 'password':
if isinstance(obj[key], list):
objData[key] = []
thisList = []
for x in range(0, len(obj[key])):
thisDict = {}
for listKey in obj[key][x]:
if isinstance(obj[key][x][listKey], str):
thisDict[listKey] = str(obj[key][x][listKey])
elif isinstance(obj[key][x][listKey], bytes):
thisDict[listKey] = str(obj[key][x][listKey])
elif isinstance(obj[key][x][listKey], bool):
thisDict[listKey] = obj[key][x][listKey]
elif isinstance(obj[key][x][listKey], int):
thisDict[listKey] = getInt(obj[key][x][listKey])
elif isinstance(obj[key][x][listKey], float):
thisDict[listKey] = getDecimal(obj[key][x][listKey])
elif isinstance(obj[key][x][listKey], ObjectId):
thisDict[listKey] = str(obj[key][x][listKey])
else:
thisDict[listKey] = obj[key][x][listKey]
thisList.append(thisDict)
objData[key] = thisList
else:
if isinstance(obj[key], str):
objData[key] = str(obj[key])
elif isinstance(obj[key], bytes):
objData[key] = str(obj[key])
elif isinstance(obj[key], bool):
objData[key] = obj[key]
elif isinstance(obj[key], int):
objData[key] = getInt(obj[key])
elif isinstance(obj[key], float):
objData[key] = getDecimal(obj[key])
elif isinstance(obj[key], ObjectId):
objData[key] = str(obj[key])
else:
objData[key] = obj[key]
try:
objData['id'] = objData['_id']
objData.pop('_id')
except:
pass
return objData
def tz_diff(home):
utcnow = pytz.timezone('utc').localize(datetime.datetime.utcnow()) # generic time
here = utcnow.astimezone(pytz.timezone(home)).replace(tzinfo=None)
there = utcnow.astimezone(pytz.timezone('UTC')).replace(tzinfo=None)
offset = relativedelta(there,here)
return(offset.hours)
## THIS FUNCTION WORKS BY REFERENCING TWO DICTIONARIES WE HAVE SAVED
## ONE IS FOR STORING ALL AREA CODES AND WHICH TIMEZONE AND STATE THEY BELONG TO
## THE OTHER IS FOR STORING STATE LAWS ABOUT AUTO DIAL TIMES
## WE GRAB THE PHONE NUMBER AND TAKE THE AREA CODE OUT OF THAT
## THEN WE FIND WHAT STATE IT BELONGS TO
## LASTLY WE CHECK THE LAWS FOR WHAT TIME WE CAN CALL FOR THAT STATE AND WHAT DAY IT IS NOW IN THAT TIMEZONE
## WE RETURN TRUE OR FALSE OF WHETHER OR NOT WE CAN MAKE THE CALL
def phone_tz_check(phoneNumber):
try:
utcnow = pytz.timezone('utc').localize(datetime.datetime.utcnow()) # generic time
areaCode = phoneNumber[2:5]
state = None
tz = None
startTime = None
endTime = None
for area in areaCodeTZ:
if str(area['area_code']) == areaCode:
state = area['state']
tz = area['time_zone']
break
here = utcnow.astimezone(pytz.timezone(tz)).replace(tzinfo=None)
day = here.weekday()
for law in stateLaws:
if law['State'] == state:
enabled = law['days'][day]['allowed']
startTime = law['days'][day]['start_full']
endTime = law['days'][day]['end_full']
break
if enabled == 0:
return False
startHour = startTime.split(':')[0]
startMin = startTime.split(':')[1]
endHour = endTime.split(':')[0]
endMin = endTime.split(':')[1]
startTime = here.replace(hour=int(startHour), minute=int(startMin))
endTime = here.replace(hour=int(endHour), minute=int(endMin))
if here >= startTime and here < endTime:
return True
return False
except:
return True
def formatDate(myDate):
return myDate.strftime("%Y/%m/%d")
def formatNiceDate(myDate):
return myDate.strftime("%m/%d/%Y")
def formatDateStd(myDate):
return myDate.strftime("%Y-%m-%d")
def getDecimal(x):
try:
#return Decimal(x.quantize(Decimal('.01'), rounding=ROUND_HALF_UP))
return float(x)
except:
x = 0
#return Decimal(x.quantize(Decimal('.01'), rounding=ROUND_HALF_UP))
return float(x)
def getInt(x):
try:
#return Decimal(x.quantize(Decimal('.01'), rounding=ROUND_HALF_UP))
return int(x)
except:
x = 0
#return Decimal(x.quantize(Decimal('.01'), rounding=ROUND_HALF_UP))
return int(x)
def formatStringToJSON(x):
x = str((x).decode("utf-8"))
leadData = None
try:
leadData = json.loads(x)
print('Properly Loaded')
return json.loads(leadData)
except:
try:
leadData = str(x).replace("'\"", "'\\\"")
leadData = str(leadData).replace("\"'", "\\\"'")
leadData = str(leadData).replace("'", '"')
return json.loads(leadData)
except:
leadData = str(x).replace("'\"", "'\\\"")
leadData = str(leadData).replace("\"'", "\\\"'")
leadData = str(leadData).replace("'", '"')
return None