HR-ATS-Portal/backend/inbox/views.py

44 lines
1.8 KiB
Python

import httpx,os
from fastapi import HTTPException
from inbox.models import Inbox_Messages
from inbox.file_decoder import decode_attachment, AttachmentDecodeError
from dotenv import load_dotenv
load_dotenv()
from sqlalchemy.ext.asyncio import AsyncSession
from pydantic import BaseModel
class Email:
def __init__(self,session:AsyncSession,token):
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)
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))