journal-bot/bot/models.py
Remy Moll 0dfb5f3134
All checks were successful
continuous-integration/drone/push Build is passing
use db contexts for better stability
2023-04-24 18:37:58 +02:00

60 lines
1.4 KiB
Python

from peewee import *
from pathlib import Path
import os
ID_MAPPINGS = {
"Lia": 5603036217,
"Rémy": 364520272,
}
ID_MAPPINGS_REV = dict((v, k) for k, v in ID_MAPPINGS.items())
MEDIA_DIR = Path(os.getenv("MEDIA_DIR"))
MEDIA_DIR.mkdir(parents=True, exist_ok=True)
db = DatabaseProxy()
class BaseModel(Model):
class Meta:
database = db
db_table = 'journal'
# model for a single journal entry
class JournalEntry(BaseModel):
date = DateField(unique=True)
author = TextField(null=True)
text = TextField(null=True)
media_path = TextField(null=True)
last_shown = DateField(null=True)
@property
def media(self):
return Path(self.media_path).open('rb')
def save_media(self, media: bytearray, file_name: str):
ext = Path(file_name).suffix
file_name = f"{self.date.isoformat()}-media{ext}"
self.media_path = MEDIA_DIR / file_name
self.media_path.write_bytes(media)
self.save()
@property
def author_id(self):
if self.author is None:
return None
else:
return ID_MAPPINGS[self.author]
@author_id.setter
def author_id(self, author_id):
self.author = ID_MAPPINGS_REV[author_id]
self.save()
def set_db(db_path):
db.initialize(SqliteDatabase(db_path))
db.connect()
db.create_tables([JournalEntry], safe=True)