from datetime import datetime, timezone from sqlalchemy import ARRAY, DateTime, ForeignKey, Index, Integer, Text, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column, relationship from fabledassistant.models import Base class RssFeed(Base): __tablename__ = "rss_feeds" id: Mapped[int] = mapped_column(primary_key=True) user_id: Mapped[int] = mapped_column(Integer, ForeignKey("users.id", ondelete="CASCADE")) url: Mapped[str] = mapped_column(Text) title: Mapped[str] = mapped_column(Text, default="") category: Mapped[str | None] = mapped_column(Text, nullable=True) last_fetched_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) items: Mapped[list["RssItem"]] = relationship( back_populates="feed", cascade="all, delete-orphan" ) __table_args__ = ( UniqueConstraint("user_id", "url", name="uq_rss_feeds_user_url"), Index("ix_rss_feeds_user_id", "user_id"), ) def to_dict(self) -> dict: return { "id": self.id, "url": self.url, "title": self.title, "category": self.category, "last_fetched_at": self.last_fetched_at.isoformat() if self.last_fetched_at else None, } class RssItem(Base): __tablename__ = "rss_items" id: Mapped[int] = mapped_column(primary_key=True) feed_id: Mapped[int] = mapped_column(Integer, ForeignKey("rss_feeds.id", ondelete="CASCADE")) guid: Mapped[str] = mapped_column(Text) title: Mapped[str] = mapped_column(Text, default="") url: Mapped[str] = mapped_column(Text, default="") published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) # Truncated to 2000 chars to keep DB size reasonable content: Mapped[str] = mapped_column(Text, default="") fetched_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), default=lambda: datetime.now(timezone.utc) ) topics: Mapped[list[str]] = mapped_column( ARRAY(Text), nullable=False, default=list, server_default="{}" ) classified_at: Mapped[datetime | None] = mapped_column( DateTime(timezone=True), nullable=True ) feed: Mapped["RssFeed"] = relationship(back_populates="items") __table_args__ = ( UniqueConstraint("feed_id", "guid", name="uq_rss_items_feed_guid"), Index("ix_rss_items_feed_id", "feed_id"), Index("ix_rss_items_published_at", "published_at"), ) def to_dict(self) -> dict: return { "id": self.id, "feed_id": self.feed_id, "guid": self.guid, "title": self.title, "url": self.url, "published_at": self.published_at.isoformat() if self.published_at else None, "content": self.content, "topics": self.topics or [], "classified_at": self.classified_at.isoformat() if self.classified_at else None, }