50 lines
2.0 KiB
Python
50 lines
2.0 KiB
Python
|
|
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey
|
|||
|
|
from sqlalchemy.orm import relationship
|
|||
|
|
from datetime import datetime
|
|||
|
|
import secrets
|
|||
|
|
|
|||
|
|
from . import Base
|
|||
|
|
|
|||
|
|
|
|||
|
|
class Mailbox(Base):
|
|||
|
|
"""邮箱模型"""
|
|||
|
|
__tablename__ = 'mailboxes'
|
|||
|
|
|
|||
|
|
id = Column(Integer, primary_key=True)
|
|||
|
|
address = Column(String(255), unique=True, nullable=False, index=True)
|
|||
|
|
domain_id = Column(Integer, ForeignKey('domains.id'), nullable=False)
|
|||
|
|
password_hash = Column(String(255), nullable=True)
|
|||
|
|
description = Column(String(500), nullable=True)
|
|||
|
|
active = Column(Boolean, default=True)
|
|||
|
|
api_key = Column(String(64), unique=True, default=lambda: secrets.token_hex(16))
|
|||
|
|
created_at = Column(DateTime, default=datetime.utcnow)
|
|||
|
|
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
|||
|
|
last_accessed = Column(DateTime, nullable=True)
|
|||
|
|
|
|||
|
|
# 关系
|
|||
|
|
domain = relationship("Domain", back_populates="mailboxes")
|
|||
|
|
emails = relationship("Email", back_populates="mailbox", cascade="all, delete-orphan")
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def full_address(self):
|
|||
|
|
"""获取完整邮箱地址 (包含域名)"""
|
|||
|
|
return f"{self.address}@{self.domain.name}"
|
|||
|
|
|
|||
|
|
def __repr__(self):
|
|||
|
|
return f"<Mailbox {self.full_address}>"
|
|||
|
|
|
|||
|
|
def to_dict(self):
|
|||
|
|
"""转换为字典,用于API响应"""
|
|||
|
|
return {
|
|||
|
|
"id": self.id,
|
|||
|
|
"address": self.address,
|
|||
|
|
"domain_id": self.domain_id,
|
|||
|
|
"domain_name": self.domain.name if self.domain else None,
|
|||
|
|
"full_address": self.full_address,
|
|||
|
|
"description": self.description,
|
|||
|
|
"active": self.active,
|
|||
|
|
"created_at": self.created_at.isoformat() if self.created_at else None,
|
|||
|
|
"updated_at": self.updated_at.isoformat() if self.updated_at else None,
|
|||
|
|
"last_accessed": self.last_accessed.isoformat() if self.last_accessed else None,
|
|||
|
|
"email_count": len(self.emails) if self.emails else 0
|
|||
|
|
}
|