Ashok Kumar Bhati commited on
Commit
75ef0af
Β·
1 Parent(s): 64a2631

/refresh command

Browse files
Files changed (1) hide show
  1. src/controllers/_bot_controller.py +258 -4
src/controllers/_bot_controller.py CHANGED
@@ -1,12 +1,12 @@
1
  import os
2
-
 
3
  from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
4
  from fastapi.responses import JSONResponse, RedirectResponse
5
  from slack_sdk.web.async_client import AsyncWebClient
6
-
7
- from src.models import ContentDeliveryFrequency
8
  from src.services import FileService, SlackBotService, SlackTeamService, UserService
9
- from src.utils import logger
10
 
11
  file_set = set()
12
 
@@ -19,6 +19,7 @@ class BotController:
19
  self.router.add_api_route("/auth", self.authenticate, methods=["GET"])
20
  self.router.add_api_route("/frequency", self.update_frequency, methods=["POST"])
21
  self.router.add_api_route("/install", self.install, methods=["GET"])
 
22
 
23
  def get_welcome_message(self, firstname):
24
 
@@ -297,3 +298,256 @@ class BotController:
297
 
298
  def ephemeral_response(self, text):
299
  return {"response_type": "ephemeral", "text": text}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import traceback
3
+ import aiohttp
4
  from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
5
  from fastapi.responses import JSONResponse, RedirectResponse
6
  from slack_sdk.web.async_client import AsyncWebClient
7
+ from src.models import ContentDeliveryFrequency, User
 
8
  from src.services import FileService, SlackBotService, SlackTeamService, UserService
9
+ from src.utils import logger, Helper
10
 
11
  file_set = set()
12
 
 
19
  self.router.add_api_route("/auth", self.authenticate, methods=["GET"])
20
  self.router.add_api_route("/frequency", self.update_frequency, methods=["POST"])
21
  self.router.add_api_route("/install", self.install, methods=["GET"])
22
+ self.router.add_api_route("/refresh", self.refreshContent, methods=["POST"])
23
 
24
  def get_welcome_message(self, firstname):
25
 
 
298
 
299
  def ephemeral_response(self, text):
300
  return {"response_type": "ephemeral", "text": text}
301
+
302
+ async def refreshContent(
303
+ self, request: Request, background_tasks: BackgroundTasks
304
+ ):
305
+ print(">>>>>>>>>>>>>>>>>>>>>")
306
+ form_data = await request.form()
307
+ payload = dict(form_data)
308
+ print(">>>>>>>>>>>>>>>>>>>>>",payload, payload.get("command") )
309
+ if payload.get("command") != "/refresh":
310
+ return {
311
+ "response_type": "ephemeral",
312
+ "text": "Invalid command. Please use /refresh command.",
313
+ }
314
+ file_url = payload.get("text", "").strip()
315
+
316
+ if not file_url:
317
+ return {
318
+ "response_type": "ephemeral",
319
+ "text": "Please provide a valid file URL with the /refresh command.",
320
+ }
321
+ async with Helper as helper:
322
+ if not helper.is_valid_url(file_url):
323
+ return {
324
+ "response_type": "ephemeral",
325
+ "text": "Please provide a valid URL (e.g., https://example.com/file.pdf).",
326
+ }
327
+ background_tasks.add_task(self.refreshUserContent, payload)
328
+ return {
329
+ "response_type": "ephemeral",
330
+ "text": "You're very welcome! πŸŽ‰ We'll be sharing these insights with you gradually over the next few weeks. 😊"
331
+ }
332
+
333
+ async def refreshUserContent(self, payload: dict):
334
+ try:
335
+ user_id = payload.get("user_id")
336
+ async with UserService() as user_service:
337
+ user = await user_service.get_user_by_slack_id(user_id)
338
+ if not user:
339
+ return {
340
+ "response_type": "ephemeral",
341
+ "text": "User not found. Please make sure you're registered.",
342
+ }
343
+
344
+ async with SlackTeamService() as slack_team_service:
345
+ team = await slack_team_service.get_team_by_slack_team_id(
346
+ payload.get("team_id")
347
+ )
348
+ if not team:
349
+ return {
350
+ "response_type": "ephemeral",
351
+ "text": "Team not found",
352
+ }
353
+
354
+ async with FileService() as file_service:
355
+ try:
356
+ # Download file from URL with timeout
357
+ file_url = payload.get("text", "").strip()
358
+ async with aiohttp.ClientSession() as session:
359
+ try:
360
+ async with session.get(file_url, timeout=30) as response:
361
+ if response.status != 200:
362
+ return {
363
+ "response_type": "ephemeral",
364
+ "text": f"Failed to download file. Server returned status code: {response.status}",
365
+ }
366
+
367
+ # Check content type
368
+ content_type = response.headers.get("content-type", "")
369
+ if not any(supported_type in content_type.lower()
370
+ for supported_type in ['pdf', 'powerpoint', 'document', 'application']):
371
+ return {
372
+ "response_type": "ephemeral",
373
+ "text": "Invalid file type. Please provide a valid document file URL.",
374
+ }
375
+
376
+ file_content = await response.read()
377
+ if not file_content:
378
+ return {
379
+ "response_type": "ephemeral",
380
+ "text": "The file appears to be empty. Please check the URL and try again.",
381
+ }
382
+
383
+ file_name = file_url.split('/')[-1]
384
+
385
+ uploaded_file = {
386
+ "filename": file_name,
387
+ "content": file_content,
388
+ "mimetype": content_type
389
+ }
390
+
391
+ except aiohttp.ClientTimeout:
392
+ return {
393
+ "response_type": "ephemeral",
394
+ "text": "Request timed out. Please check the URL and try again.",
395
+ }
396
+ except aiohttp.ClientError as e:
397
+ logger.error(f"Error downloading file: {e}")
398
+ return {
399
+ "response_type": "ephemeral",
400
+ "text": "Failed to download file. Please check the URL and try again.",
401
+ }
402
+
403
+ # Process the file
404
+ await file_service.process_file(
405
+ file=uploaded_file,
406
+ user=user,
407
+ slack_file_id=None,
408
+ slack_token=team.token,
409
+ )
410
+
411
+ await user_service.send_message(
412
+ user.id,
413
+ "You're very welcome! πŸŽ‰ We'll be refreshing your insights based on the new file. You'll receive updated content in your next scheduled delivery. 😊",
414
+ )
415
+
416
+ except Exception as e:
417
+ logger.error(f"Error processing file: {e}")
418
+ return {
419
+ "response_type": "ephemeral",
420
+ "text": "Failed to process the file. Please check the URL and try again.",
421
+ }
422
+
423
+ except Exception as e:
424
+ logger.error(f"Error processing refresh command: {e}")
425
+ traceback.print_exc()
426
+
427
+ async def refreshContent(
428
+ self, request: Request, background_tasks: BackgroundTasks
429
+ ):
430
+ print(">>>>>>>>>>>>>>>>>>>>>")
431
+ form_data = await request.form()
432
+ payload = dict(form_data)
433
+ print(">>>>>>>>>>>>>>>>>>>>>",payload, payload.get("command") )
434
+ if payload.get("command") != "/refresh":
435
+ return {
436
+ "response_type": "ephemeral",
437
+ "text": "Invalid command. Please use /refresh command.",
438
+ }
439
+ file_url = payload.get("text", "").strip()
440
+
441
+ if not file_url:
442
+ return {
443
+ "response_type": "ephemeral",
444
+ "text": "Please provide a valid file URL with the /refresh command.",
445
+ }
446
+ async with Helper as helper:
447
+ if not helper.is_valid_url(file_url):
448
+ return {
449
+ "response_type": "ephemeral",
450
+ "text": "Please provide a valid URL (e.g., https://example.com/file.pdf).",
451
+ }
452
+ background_tasks.add_task(self.refreshUserContent, payload)
453
+ return {
454
+ "response_type": "ephemeral",
455
+ "text": "You're very welcome! πŸŽ‰ We'll be sharing these insights with you gradually over the next few weeks. 😊"
456
+ }
457
+
458
+ async def refreshUserContent(self, payload: dict):
459
+ try:
460
+ async with UserService() as user_service:
461
+ user = await user_service.get_user_by_slack_id(user_id)
462
+ if not user:
463
+ return {
464
+ "response_type": "ephemeral",
465
+ "text": "User not found. Please make sure you're registered.",
466
+ }
467
+
468
+ async with SlackTeamService() as slack_team_service:
469
+ team = await slack_team_service.get_team_by_slack_team_id(
470
+ payload.get("team_id")
471
+ )
472
+ if not team:
473
+ return {
474
+ "response_type": "ephemeral",
475
+ "text": "Team not found",
476
+ }
477
+
478
+ async with FileService() as file_service:
479
+ try:
480
+ # Download file from URL with timeout
481
+ file_url = payload.get("text", "").strip()
482
+ async with aiohttp.ClientSession() as session:
483
+ try:
484
+ async with session.get(file_url, timeout=30) as response:
485
+ if response.status != 200:
486
+ return {
487
+ "response_type": "ephemeral",
488
+ "text": f"Failed to download file. Server returned status code: {response.status}",
489
+ }
490
+
491
+ # Check content type
492
+ content_type = response.headers.get("content-type", "")
493
+ if not any(supported_type in content_type.lower()
494
+ for supported_type in ['pdf', 'powerpoint', 'document', 'application']):
495
+ return {
496
+ "response_type": "ephemeral",
497
+ "text": "Invalid file type. Please provide a valid document file URL.",
498
+ }
499
+
500
+ file_content = await response.read()
501
+ if not file_content:
502
+ return {
503
+ "response_type": "ephemeral",
504
+ "text": "The file appears to be empty. Please check the URL and try again.",
505
+ }
506
+
507
+ file_name = file_url.split('/')[-1]
508
+
509
+ uploaded_file = {
510
+ "filename": file_name,
511
+ "content": file_content,
512
+ "mimetype": content_type
513
+ }
514
+
515
+ except aiohttp.ClientTimeout:
516
+ return {
517
+ "response_type": "ephemeral",
518
+ "text": "Request timed out. Please check the URL and try again.",
519
+ }
520
+ except aiohttp.ClientError as e:
521
+ logger.error(f"Error downloading file: {e}")
522
+ return {
523
+ "response_type": "ephemeral",
524
+ "text": "Failed to download file. Please check the URL and try again.",
525
+ }
526
+
527
+ # Process the file
528
+ await file_service.process_file(
529
+ file=uploaded_file,
530
+ user=user,
531
+ slack_file_id=None,
532
+ slack_token=team.token,
533
+ )
534
+
535
+ await user_service.send_message(
536
+ user.id,
537
+ "You're very welcome! πŸŽ‰ We'll be refreshing your insights based on the new file. You'll receive updated content in your next scheduled delivery. 😊",
538
+ )
539
+
540
+ except Exception as e:
541
+ logger.error(f"Error processing file: {e}")
542
+ return {
543
+ "response_type": "ephemeral",
544
+ "text": "Failed to process the file. Please check the URL and try again.",
545
+ }
546
+
547
+ except Exception as e:
548
+ logger.error(f"Error processing refresh command: {e}")
549
+ traceback.print_exc()
550
+ return {
551
+ "response_type": "ephemeral",
552
+ "text": "An error occurred while processing your request. Please try again.",
553
+ }