File size: 2,126 Bytes
4131620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import Request,APIRouter
import requests
from controllers import ner_ai_controller as ai
from services.chat_client_NER import ChatClient
import logging
router = APIRouter(prefix="/gmail")

@router.post("/total_messages")
async def get_total_messages(request:Request):
    body = await request.json()
    access_token = body.get('access_token',None)
    if access_token is None : return {"message":"Access token Invalid ! Try Again!"}

    user_query = body.get('brand_name') if body.get('brand_name') is not None else None

            # access_token = await websocket.receive_text()
    brand_name = None
    logging.info(f"brand_name: {user_query}")
    logging.info(f"access_token : {access_token}")
    if user_query is not None:
        chat = ChatClient().create(conversation=[])
        response = chat.send_message(content=f"{user_query}", stream=False)
        if response.text == 'others':
            brand_name = None
        else:
            brand_name = response.text

    search_query = f'(subject:"your order" OR subject:receipts OR subject:receipt OR subject:aankoopbon OR subject:reçu OR subject:invoice OR subject:invoices OR category:purchases) has:attachment'
    if brand_name is not None:
        search_query = f'(subject:"your order" OR subject:receipts OR subject:receipt OR  subject: aankoopbon  OR subject:reçu OR subject:invoice OR subject:invoices OR category:purchases) AND ({brand_name}) has:attachment'
    total_messages = 0
    page_token = None

    while True:
        gmail_url = f"https://www.googleapis.com/gmail/v1/users/me/messages?q={search_query}"
        if page_token:
            gmail_url += f"&pageToken={page_token}"
        
        gmail_response = requests.get(gmail_url, headers={"Authorization": f"Bearer {access_token}"})
        gmail_data = gmail_response.json()
        if "messages" in gmail_data:
            total_messages += len(gmail_data["messages"])
        
        if "nextPageToken" in gmail_data:
            page_token = gmail_data["nextPageToken"]
        else:
            break
        pass

    return {"total_messages":total_messages}