-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
386 lines (331 loc) · 10 KB
/
utils.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import html
import os
import re
from datetime import datetime
from typing import List
import fiscalyear
import pytz
import requests
from db import eventsdb
inter_communication_secret = os.getenv("INTER_COMMUNICATION_SECRET")
# start month of financial year
FISCAL_START_MONTH = 4
# fiscalyear config
fiscalyear.START_MONTH = FISCAL_START_MONTH
def getMember(cid, uid, cookies=None):
"""
Function to call the member query
"""
try:
query = """
query Member($memberInput: SimpleMemberInput!) {
member(memberInput: $memberInput) {
_id
cid
poc
uid
}
}
"""
variables = {"memberInput": {"cid": cid, "uid": uid, "rid": None}}
if cookies:
request = requests.post(
"http://gateway/graphql",
json={"query": query, "variables": variables},
cookies=cookies,
)
else:
request = requests.post(
"http://gateway/graphql",
json={"query": query, "variables": variables},
)
return request.json()["data"]["member"]
except Exception:
return None
def getUser(uid, cookies=None):
"""
Function to get a particular user details
"""
try:
query = """
query GetUserProfile($userInput: UserInput!) {
userProfile(userInput: $userInput) {
firstName
lastName
email
rollno
}
userMeta(userInput: $userInput) {
phone
}
}
"""
variable = {"userInput": {"uid": uid}}
if cookies:
request = requests.post(
"http://gateway/graphql",
json={"query": query, "variables": variable},
cookies=cookies,
)
else:
request = requests.post(
"http://gateway/graphql",
json={"query": query, "variables": variable},
)
return request.json()["data"]["userProfile"], request.json()["data"][
"userMeta"
]
except Exception:
return None
def getClubs(cookies=None):
"""
Function to call the all clubs query
"""
try:
query = """
query AllClubs {
allClubs {
cid
name
code
email
}
}
"""
if cookies:
request = requests.post(
"http://gateway/graphql",
json={"query": query},
cookies=cookies,
)
else:
request = requests.post(
"http://gateway/graphql", json={"query": query}
)
return request.json()["data"]["allClubs"]
except Exception:
return []
# get club code from club id
def getClubCode(clubid: str) -> str | None:
allclubs = getClubs()
for club in allclubs:
if club["cid"] == clubid:
return club["code"]
return None
# get club name from club id
def getClubDetails(
clubid: str,
cookies,
) -> dict:
try:
query = """
query Club($clubInput: SimpleClubInput!) {
club(clubInput: $clubInput) {
cid
name
email
category
}
}
"""
variable = {"clubInput": {"cid": clubid}}
request = requests.post(
"http://gateway/graphql",
json={"query": query, "variables": variable},
cookies=cookies,
)
return request.json()["data"]["club"]
except Exception:
return {}
# generate event code based on time and club
def getEventCode(clubid, starttime) -> str:
club_code = getClubCode(clubid)
if club_code is None:
raise ValueError("Invalid clubid")
year = fiscalyear.FiscalYear(
fiscalyear.FiscalDateTime.fromisoformat(
str(starttime).split("+")[0]
).fiscal_year
)
start = year.start
end = year.end
club_events = eventsdb.find(
{
"clubid": clubid,
"datetimeperiod": {
"$gte": start.isoformat(),
"$lte": end.isoformat(),
},
}
)
max_code = 0
for i in list(club_events):
code = i["code"]
code = int(code[-3:])
if code > max_code:
max_code = code
event_count = max_code + 1
code_year = str(year.fiscal_year - 1)[-2:] + str(year.fiscal_year)[-2:]
return f"{club_code}{code_year}{event_count:03d}" # format: CODE20XX00Y
# get link to event (based on code)
def getEventLink(code) -> str:
host = os.environ.get("HOST", "http://localhost")
return f"{host}/manage/events/code/{code}"
# get email IDs of all members belonging to a role
def getRoleEmails(role: str) -> List[str]:
try:
query = """
query Query($role: String!, $interCommunicationSecret: String) {
usersByRole(role: $role, interCommunicationSecret: $interCommunicationSecret) {
uid
}
}
""" # noqa: E501
variables = {
"role": role,
"interCommunicationSecret": inter_communication_secret,
}
request = requests.post(
"http://gateway/graphql",
json={"query": query, "variables": variables},
)
# extract UIDs
uids = list(
map(lambda o: o["uid"], request.json()["data"]["usersByRole"])
)
# get emails of each UID
emails = []
for uid in uids:
query = """
query UserProfile($userInput: UserInput) {
userProfile(userInput: $userInput) {
email
}
}
"""
variables = {"userInput": {"uid": uid}}
request = requests.post(
"http://gateway/graphql",
json={"query": query, "variables": variables},
)
emails.append(request.json()["data"]["userProfile"]["email"])
return emails
except Exception:
return []
def eventsWithSorting(
searchspace,
name: str | None = None,
date_filter=False,
pagination=False,
skip=0,
limit: int | None = None,
):
"""
Custom sorting of events based on
datetimeperiod with
ongoing events first in ascending order of end time
then
upcoming events first in ascending order of start time
and then
past events in descending order of end time
"""
utc = pytz.timezone("UTC")
current_datetime = datetime.now(utc).strftime("%Y-%m-%dT%H:%M:%S+00:00")
if date_filter:
required_events_query = {
**searchspace,
}
events = list(
eventsdb.find(required_events_query).sort("datetimeperiod.0", -1)
)
return events
if name is not None and pagination:
searchspace["name"] = {"$regex": name, "$options": "i"}
ongoing_events_query = {
**searchspace,
"datetimeperiod.0": {"$lte": current_datetime},
"datetimeperiod.1": {"$gte": current_datetime},
}
upcoming_events_query = {
**searchspace,
"datetimeperiod.0": {"$gt": current_datetime},
}
past_events_query = {
**searchspace,
"datetimeperiod.1": {"$lt": current_datetime},
}
if pagination:
if skip < 0:
ongoing_events = list(
eventsdb.find(ongoing_events_query).sort(
"datetimeperiod.0", -1
)
)
upcoming_events = list(
eventsdb.find(upcoming_events_query).sort(
"datetimeperiod.0", 1
)
)
events = ongoing_events + upcoming_events
else:
past_events = list(
eventsdb.find(past_events_query)
.sort("datetimeperiod.1", -1)
.skip(skip)
.limit(limit)
)
events = past_events
else:
ongoing_events = list(
eventsdb.find(ongoing_events_query).sort("datetimeperiod.0", -1)
)
upcoming_events = list(
eventsdb.find(upcoming_events_query).sort("datetimeperiod.0", 1)
)
past_events = list(
eventsdb.find(past_events_query).sort("datetimeperiod.1", -1)
)
events = ongoing_events + upcoming_events + past_events
if limit:
events = events[:limit]
return events
def trim_public_events(event: dict):
delete_keys = [
"equipment",
"additional",
"population",
"poc",
"budget",
"bills_status",
]
for key in delete_keys:
if key in event:
del event[key]
status = event["status"]
del event["status"]
event["status"] = {
"state": status["state"],
}
return event
def convert_to_html(text):
# Escape HTML special characters
text = html.escape(text)
# Replace URLs with HTML link tags
url_pattern = r"(http[s]?://\S+)"
text = re.sub(url_pattern, r'<a href="\1">\1</a>', text)
# Replace newlines with <br> tags
text = re.sub(r"\n", "<br>", text)
# Replace multiple spaces with (non-breaking space)
text = re.sub(r" {2,}", lambda m: " " * len(m.group(0)), text)
return f"<pre>{text}</pre>"
def delete_file(filename):
response = requests.post(
"http://files/delete-file",
params={
"filename": filename,
"inter_communication_secret": inter_communication_secret,
},
)
if response.status_code != 200:
raise Exception(response.text)
return response.text