2026-06-07 21:51:01 +08:00
|
|
|
"""/subscriptions 关键词订阅。"""
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
|
|
|
from sqlalchemy import select
|
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
|
|
|
|
from app.core.deps import get_current_user
|
|
|
|
|
from app.database import get_session
|
|
|
|
|
from app.models.subscription import Subscription
|
|
|
|
|
from app.models.user import User
|
|
|
|
|
from app.schemas.misc import SubscriptionIn, SubscriptionOut
|
|
|
|
|
|
|
|
|
|
router = APIRouter(prefix="/subscriptions", tags=["subscriptions"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.post("", response_model=SubscriptionOut, status_code=status.HTTP_201_CREATED)
|
|
|
|
|
async def create(
|
|
|
|
|
body: SubscriptionIn,
|
|
|
|
|
user: User = Depends(get_current_user),
|
|
|
|
|
session: AsyncSession = Depends(get_session),
|
|
|
|
|
):
|
|
|
|
|
sub = Subscription(
|
|
|
|
|
user_id=user.id,
|
|
|
|
|
keyword=body.keyword,
|
|
|
|
|
match_in=body.match_in,
|
|
|
|
|
channel=body.channel,
|
|
|
|
|
target=body.target,
|
|
|
|
|
)
|
|
|
|
|
session.add(sub)
|
|
|
|
|
await session.commit()
|
|
|
|
|
await session.refresh(sub)
|
|
|
|
|
return SubscriptionOut.model_validate(sub)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get("", response_model=list[SubscriptionOut])
|
|
|
|
|
async def list_mine(
|
|
|
|
|
user: User = Depends(get_current_user),
|
|
|
|
|
session: AsyncSession = Depends(get_session),
|
|
|
|
|
):
|
2026-06-07 23:22:56 +08:00
|
|
|
result = await session.execute(
|
|
|
|
|
select(Subscription)
|
|
|
|
|
.where(Subscription.user_id == user.id)
|
|
|
|
|
.order_by(Subscription.created_at.desc())
|
|
|
|
|
)
|
|
|
|
|
rows = result.scalars()
|
2026-06-07 21:51:01 +08:00
|
|
|
return [SubscriptionOut.model_validate(s) for s in rows]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.delete("/{sub_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
|
|
|
async def delete(
|
|
|
|
|
sub_id: int,
|
|
|
|
|
user: User = Depends(get_current_user),
|
|
|
|
|
session: AsyncSession = Depends(get_session),
|
|
|
|
|
):
|
|
|
|
|
sub = (
|
|
|
|
|
await session.execute(
|
|
|
|
|
select(Subscription).where(
|
|
|
|
|
Subscription.id == sub_id, Subscription.user_id == user.id
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
).scalar_one_or_none()
|
|
|
|
|
if not sub:
|
|
|
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Subscription not found")
|
|
|
|
|
await session.delete(sub)
|
|
|
|
|
await session.commit()
|
|
|
|
|
return None
|