didier/database/crud/ufora_announcements.py

36 lines
1.4 KiB
Python
Raw Normal View History

2022-06-19 00:51:24 +02:00
import datetime
2022-06-19 00:36:38 +02:00
2022-06-19 00:51:24 +02:00
from sqlalchemy import select, delete
2022-06-19 00:23:25 +02:00
from sqlalchemy.ext.asyncio import AsyncSession
from database.models import UforaCourse, UforaAnnouncement
async def get_courses_with_announcements(session: AsyncSession) -> list[UforaCourse]:
"""Get all courses where announcements are enabled"""
2022-06-19 00:51:24 +02:00
statement = select(UforaCourse).where(UforaCourse.log_announcements)
return (await session.execute(statement)).scalars().all()
2022-06-19 00:23:25 +02:00
2022-06-19 00:36:38 +02:00
async def create_new_announcement(
session: AsyncSession, announcement_id: int, course: UforaCourse, publication_date: datetime.datetime
2022-06-19 00:36:38 +02:00
) -> UforaAnnouncement:
2022-06-19 00:23:25 +02:00
"""Add a new announcement to the database"""
2022-06-19 00:36:38 +02:00
new_announcement = UforaAnnouncement(
announcement_id=announcement_id, course=course, publication_date=publication_date
)
2022-06-19 00:23:25 +02:00
session.add(new_announcement)
await session.commit()
2022-06-19 00:36:38 +02:00
return new_announcement
2022-06-19 00:51:24 +02:00
async def remove_old_announcements(session: AsyncSession):
"""Delete all announcements that are > 8 days old
The RSS feed only goes back 7 days, so all of these old announcements never have to
be checked again when checking if an announcement is fresh or not.
"""
limit = datetime.datetime.utcnow() - datetime.timedelta(days=8)
statement = delete(UforaAnnouncement).where(UforaAnnouncement.publication_date < limit)
await session.execute(statement)
await session.commit()