import httpx,os,uuid from fastapi import HTTPException from inbox.models import Inbox_Messages from inbox.file_decoder import decode_attachment, AttachmentDecodeError from inbox.serializers import serialize_message from dotenv import load_dotenv load_dotenv() from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import func,or_ from sqlmodel import select from pydantic import BaseModel class Email: def __init__(self,session:AsyncSession,token=None): self.session=session self.get_url=os.getenv("EMAIL_URL") self.token=token async def service_email(self,top,skip): async with httpx.AsyncClient() as client: try: response=await client.get(f"{self.get_url}/emails", params={"skip":skip,"top":top}, headers={"Authorization":f"Bearer {self.token}"} ) if response.status_code==200: return response.json() else: raise HTTPException(status_code=response.status_code,detail=response.text) except Exception as e: raise HTTPException(status_code=500,detail=str(e)) async def get_email_by_id(self,message_id): async with httpx.AsyncClient() as client: try: response=await client.get(f"{self.get_url}/emails/{message_id}", headers={"Authorization":f"Bearer {self.token}"} ) if response.status_code==200: data=response.json() re_create_file=await decode_attachment(data.get("attachments")) insert_func=await Inbox_Messages.insert_email(session=self.session,email_data=data,file_path=re_create_file) return response.json() else: raise HTTPException(status_code=response.status_code,detail=response.text) except Exception as e: raise HTTPException(status_code=500,detail=str(e)) async def get_inbox_messages(self,top,skip,search=None): messages=await Inbox_Messages.get_inbox_messages(self.session,top,skip,search) return [serialize_message(m) for m in messages] async def get_inbox_message_by_id(self,record_id): message=await Inbox_Messages.get_inbox_message_by_id(self.session,record_id) if not message: raise HTTPException(status_code=404,detail="Message not found") return serialize_message(message) async def count_inbox_messages(self,search=None): return await Inbox_Messages.count_inbox_messages(self.session,search)