-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlisten.py
381 lines (318 loc) · 12.1 KB
/
listen.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
import json
import logging
import os
import sys
import time
from pprint import pprint
from typing import Any, Literal
import requests
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack_sdk.web.client import WebClient # for typing
from slack_sdk.web.slack_response import SlackResponse # for typing
from rsc import auth, fileOperators, formatters, slackUtils, strings, util, validators
# Load config
with open("config.json") as config_file:
config = json.load(config_file)
# Set up root logger
root_logger = logging.getLogger()
if "-v" in sys.argv:
root_logger.setLevel(logging.DEBUG)
else:
root_logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter("%(levelname)s:%(name)s:%(message)s"))
root_logger.addHandler(ch)
# Set up loop logging
logger = logging.getLogger("main loop")
# Changing logging level for slack_bolt to info
slack_logger = logging.getLogger("slack_bolt")
slack_logger.setLevel(logging.INFO)
# Connect to Slack
app = App(token=config["slack"]["bot_token"], logger=slack_logger)
# Update the app home in certain circumstances
@app.event("app_home_opened") # type: ignore
def app_home_opened(event: dict[str, Any], client: WebClient, ack) -> None:
ack()
slackUtils.updateHome(user=event["user"], client=client, config=config, authed_slack_users=authed_slack_users, contacts=contacts, current_members=current_members) # type: ignore
@app.event("message")
def handle_message_events(body, logger, event, client): # type: ignore
if event["type"] == "message" and not event.get("subtype", None):
# Strip ts from the event so the message isn't sent in a thread
event.pop("ts")
slackUtils.send(app=app, event=event, message=strings.dm, dm=True)
return
# Discard message types we don't care about
if event.get("subtype", "") != "file_share":
logger.debug("Discarding message event of wrong type")
return
user: str = event["user"]
notification_ts = None
entitlements = util.check_entitlements(
user=user,
config=config,
authed_slack_users_LOCAL=authed_slack_users,
current_members_LOCAL=current_members,
contacts=contacts,
client=client,
)
# Users with no entitlements are given info on how to get them
if not entitlements["folder"]:
slackUtils.send(
app=app,
event=event,
message=strings.not_authed.format(signup_url=config["tidyhq"]["signup_url"])
+ strings.not_authed_msg_addon,
)
# Let the notification channel know
ts = slackUtils.send(
app=app,
event=event,
message=strings.not_authed_admin.format(user=user),
channel=config["slack"]["notification_channel"],
ts=notification_ts,
)
if not notification_ts:
notification_ts = ts
return
# Check if the butler folder exists
if not os.path.exists(entitlements["folder"]):
slackUtils.send(
app=app,
event=event,
message=strings.no_butler_directory.format(
folder=config["download"]["folder_name"]
),
)
# Create the folder if it doesn't exist
if not os.path.exists(entitlements["folder"]):
os.makedirs(entitlements["folder"])
for file in event["files"]:
filename = formatters.clean_filename(file["name"])
# Check if the file is a duplicate
if os.path.exists(f'{entitlements["folder"]}/{filename}'):
slackUtils.send(
app=app,
event=event,
message=strings.duplicate_file.format(
folder=entitlements["folder"], file=filename
),
)
continue
# Check if the file is too large
if not validators.check_size(
file_object=file, config=config, multiplier=entitlements["multiplier"]
):
slackUtils.send(
app=app,
event=event,
message=strings.file_too_big.format(
file=filename,
size=formatters.file_size(file["size"]),
max_file_size=formatters.file_size(
num=(
1000000000
if config["download"]["max_file_size"]
* entitlements["multiplier"]
> 1000000000
else config["download"]["max_file_size"]
* entitlements["multiplier"]
)
),
),
)
continue
# Check if the folder is full
if not fileOperators.check_folder_eligibility(contacts=contacts, contact=authed_slack_users[user], config=config, user=user, multiplier=entitlements["multiplier"]): # type: ignore
slackUtils.send(
app=app,
event=event,
message=strings.over_folder_limit.format(
file=filename,
max_folder_size=formatters.file_size(
config["download"]["max_folder_size"]
* entitlements["multiplier"]
),
max_folder_files=config["download"]["max_folder_files"]
* entitlements["multiplier"],
butler_folder=config["download"]["folder_name"],
),
)
# Let the notification channel know
ts = slackUtils.send(
app=app,
event=event,
message=strings.over_folder_limit_admin.format(
file=filename,
max_folder_size=formatters.file_size(
config["download"]["max_folder_size"]
* entitlements["multiplier"]
),
max_folder_files=config["download"]["max_folder_files"]
* entitlements["multiplier"],
butler_folder=config["download"]["folder_name"],
user=user,
),
channel=config["slack"]["notification_channel"],
ts=notification_ts,
broadcast=True,
)
if not notification_ts:
notification_ts = ts
# Since the folder is full we can stop processing files
return
# Download the file
file_data = requests.get(
file["url_private"],
headers={"Authorization": f'Bearer {config["slack"]["bot_token"]}'},
)
# Check the file with VirusTotal
virus_check = util.is_virus(content=file_data.content, config=config)
if virus_check:
# Explicitly warn the notification channel
ts = slackUtils.send(
app=app,
event=event,
message=strings.virus_found.format(
user=user, file=filename, virus_name=virus_check
),
channel=config["slack"]["notification_channel"],
ts=notification_ts,
broadcast=True,
)
if not notification_ts:
notification_ts = ts
# Let the user know there was a problem
slackUtils.send(
app=app,
event=event,
message=strings.virus_found,
)
# If one of the files is a virus stop processing files
return
# Save the file
with open(f'{entitlements["folder"]}/{filename}', "wb") as f:
f.write(file_data.content)
# Let the user know the file was saved
slackUtils.send(
app=app,
event=event,
message=strings.file_saved.format(
file=filename, folder=entitlements["folder"]
),
)
# Send a message to the notification channel
ts = slackUtils.send(
app=app,
event=event,
message=strings.file_saved_admin.format(
file=filename, folder=entitlements["folder"], user=user
),
channel=config["slack"]["notification_channel"],
ts=notification_ts,
)
# Update the app home
slackUtils.updateHome(
user=user,
client=app.client,
config=config,
authed_slack_users=authed_slack_users,
contacts=contacts,
current_members=current_members,
)
if not notification_ts:
notification_ts = ts
@app.action("purge_folder")
def delete_folder(ack, body, client):
ack()
user = body["user"]["id"]
entitlements = util.check_entitlements(
user=user,
config=config,
authed_slack_users_LOCAL=authed_slack_users,
current_members_LOCAL=current_members,
contacts=contacts,
client=client,
)
# Delete the folder contents
if fileOperators.delete_folder_contents(folder=entitlements["folder"]):
slackUtils.send(app=app, event=body, message=strings.delete_success, dm=True)
# Send a message to the notification channel
slackUtils.send(
app=app,
event=body,
message=strings.delete_success_admin.format(user=user),
channel=config["slack"]["notification_channel"],
)
# Update the app home
slackUtils.updateHome(
user=user,
client=app.client,
config=config,
authed_slack_users=authed_slack_users,
contacts=contacts,
current_members=current_members,
)
@app.action("refresh_home")
def refresh_home(ack, body, client):
ack()
slackUtils.updateHome(user=body["user"]["id"], client=client, config=config, authed_slack_users=authed_slack_users, contacts=contacts, current_members=current_members) # type: ignore
@app.action("requesting_auth")
def user_off_requesting_auth(ack, body, logger):
ack()
user = body["user"]["id"]
count = 0
while count < 100 and not auth.check_auth(id=user, config=config):
time.sleep(0.1)
count += 1
# Did the user manage to authenticate in time?
if auth.check_auth(id=user, config=config):
slackUtils.updateHome(
user=user,
client=app.client,
config=config,
authed_slack_users=authed_slack_users,
contacts=contacts,
current_members=current_members,
)
else:
# Update the app home with a refresh button
slackUtils.updateHome(
user=user,
client=app.client,
config=config,
authed_slack_users=authed_slack_users,
contacts=contacts,
current_members=current_members,
auth_step=2,
)
# Validate auth server config
if not auth.validate_config(config=config):
logging.critical("Auth server config is invalid, exiting...")
sys.exit(1)
with open("config.json") as config_file:
config = json.load(config_file)
# Start the auth server
logger.info("Starting auth server...")
# Launch auth_server.py as a forked subprocess
auth.start_server(config=config, verbose="-v" in sys.argv)
# Get all linked users from TidyHQ
logger.info("Pulling TidyHQ contacts...")
contacts: list[dict[str, Any]] = requests.get(
"https://api.tidyhq.com/v1/contacts/",
params={"access_token": config["tidyhq"]["token"]},
).json()
logger.debug(f"Received {len(contacts)} contacts")
# Get info from TidyHQ
authed_slack_users, current_members = util.get_tidy_info(config=config)
# Get our user ID
info = app.client.auth_test()
logger.debug(f'Connected as @{info["user"]} to {info["team"]}')
# Check if the auth server came up while we were getting data
while not auth.check_server(config=config):
logging.warning("Auth server is not up, waiting 5 seconds...")
time.sleep(5)
logger.info("Auth server is running")
if __name__ == "__main__":
handler = SocketModeHandler(app, config["slack"]["app_token"])
handler.start()