mirror of
https://github.com/Casvt/MIND.git
synced 2026-04-25 03:00:20 -04:00
Backend Refactor
This commit is contained in:
@@ -2,21 +2,28 @@
|
||||
|
||||
import logging
|
||||
from sqlite3 import IntegrityError
|
||||
from typing import List, Literal
|
||||
from typing import List, Union
|
||||
|
||||
from backend.custom_exceptions import (NotificationServiceNotFound,
|
||||
TemplateNotFound)
|
||||
from backend.db import get_db
|
||||
from backend.helpers import TimelessSortingMethod, search_filter
|
||||
|
||||
filter_function = lambda query, p: (
|
||||
query in p["title"].lower()
|
||||
or query in p["text"].lower()
|
||||
)
|
||||
|
||||
class Template:
|
||||
"""Represents a template
|
||||
"""
|
||||
def __init__(self, user_id: int, template_id: int):
|
||||
def __init__(self, user_id: int, template_id: int) -> None:
|
||||
"""Create instance of class.
|
||||
|
||||
Args:
|
||||
user_id (int): The ID of the user.
|
||||
template_id (int): The ID of the template.
|
||||
|
||||
Raises:
|
||||
TemplateNotFound: Template with given ID does not exist or is not
|
||||
owned by user.
|
||||
"""
|
||||
self.id = template_id
|
||||
|
||||
exists = get_db().execute(
|
||||
@@ -25,7 +32,26 @@ class Template:
|
||||
).fetchone()
|
||||
if not exists:
|
||||
raise TemplateNotFound
|
||||
|
||||
return
|
||||
|
||||
def _get_notification_services(self) -> List[int]:
|
||||
"""Get ID's of notification services linked to the template.
|
||||
|
||||
Returns:
|
||||
List[int]: The list with ID's.
|
||||
"""
|
||||
result = [
|
||||
r[0]
|
||||
for r in get_db().execute("""
|
||||
SELECT notification_service_id
|
||||
FROM reminder_services
|
||||
WHERE template_id = ?;
|
||||
""",
|
||||
(self.id,)
|
||||
)
|
||||
]
|
||||
return result
|
||||
|
||||
def get(self) -> dict:
|
||||
"""Get info about the template
|
||||
|
||||
@@ -45,27 +71,35 @@ class Template:
|
||||
).fetchone()
|
||||
template = dict(template)
|
||||
|
||||
template['notification_services'] = list(map(lambda r: r[0], get_db().execute("""
|
||||
SELECT notification_service_id
|
||||
FROM reminder_services
|
||||
WHERE template_id = ?;
|
||||
""", (self.id,))))
|
||||
template['notification_services'] = self._get_notification_services()
|
||||
|
||||
return template
|
||||
|
||||
def update(self,
|
||||
title: str = None,
|
||||
notification_services: List[int] = None,
|
||||
text: str = None,
|
||||
color: str = None
|
||||
title: Union[str, None] = None,
|
||||
notification_services: Union[List[int], None] = None,
|
||||
text: Union[str, None] = None,
|
||||
color: Union[str, None] = None
|
||||
) -> dict:
|
||||
"""Edit the template
|
||||
|
||||
Args:
|
||||
title (str): The new title of the entry. Defaults to None.
|
||||
notification_services (List[int]): The new id's of the notification services to use to send the reminder. Defaults to None.
|
||||
text (str, optional): The new body of the template. Defaults to None.
|
||||
color (str, optional): The new hex code of the color of the template, which is shown in the web-ui. Defaults to None.
|
||||
title (Union[str, None]): The new title of the entry.
|
||||
Defaults to None.
|
||||
|
||||
notification_services (Union[List[int], None]): The new id's of the
|
||||
notification services to use to send the reminder.
|
||||
Defaults to None.
|
||||
|
||||
text (Union[str, None], optional): The new body of the template.
|
||||
Defaults to None.
|
||||
|
||||
color (Union[str, None], optional): The new hex code of the color of the template,
|
||||
which is shown in the web-ui.
|
||||
Defaults to None.
|
||||
|
||||
Raises:
|
||||
NotificationServiceNotFound: One of the notification services was not found
|
||||
|
||||
Returns:
|
||||
dict: The new template info
|
||||
@@ -101,16 +135,27 @@ class Template:
|
||||
if notification_services:
|
||||
cursor.connection.isolation_level = None
|
||||
cursor.execute("BEGIN TRANSACTION;")
|
||||
cursor.execute("DELETE FROM reminder_services WHERE template_id = ?", (self.id,))
|
||||
cursor.execute(
|
||||
"DELETE FROM reminder_services WHERE template_id = ?",
|
||||
(self.id,)
|
||||
)
|
||||
try:
|
||||
cursor.executemany(
|
||||
"INSERT INTO reminder_services(template_id, notification_service_id) VALUES (?,?)",
|
||||
cursor.executemany("""
|
||||
INSERT INTO reminder_services(
|
||||
template_id,
|
||||
notification_service_id
|
||||
)
|
||||
VALUES (?,?);
|
||||
""",
|
||||
((self.id, s) for s in notification_services)
|
||||
)
|
||||
cursor.execute("COMMIT;")
|
||||
|
||||
except IntegrityError:
|
||||
raise NotificationServiceNotFound
|
||||
cursor.connection.isolation_level = ""
|
||||
|
||||
finally:
|
||||
cursor.connection.isolation_level = ""
|
||||
|
||||
return self.get()
|
||||
|
||||
@@ -124,63 +169,72 @@ class Template:
|
||||
class Templates:
|
||||
"""Represents the template library of the user account
|
||||
"""
|
||||
sort_functions = {
|
||||
'title': (lambda r: (r['title'], r['text'], r['color']), False),
|
||||
'title_reversed': (lambda r: (r['title'], r['text'], r['color']), True),
|
||||
'date_added': (lambda r: r['id'], False),
|
||||
'date_added_reversed': (lambda r: r['id'], True)
|
||||
}
|
||||
|
||||
def __init__(self, user_id: int):
|
||||
self.user_id = user_id
|
||||
|
||||
def fetchall(self, sort_by: Literal["title", "title_reversed", "date_added", "date_added_reversed"] = "title") -> List[dict]:
|
||||
"""Get all templates
|
||||
def __init__(self, user_id: int) -> None:
|
||||
"""Create an instance.
|
||||
|
||||
Args:
|
||||
sort_by (Literal["title", "title_reversed", "date_added", "date_added_reversed"], optional): How to sort the result. Defaults to "title".
|
||||
user_id (int): The ID of the user.
|
||||
"""
|
||||
self.user_id = user_id
|
||||
return
|
||||
|
||||
def fetchall(
|
||||
self,
|
||||
sort_by: TimelessSortingMethod = TimelessSortingMethod.TITLE
|
||||
) -> List[dict]:
|
||||
"""Get all templates of the user.
|
||||
|
||||
Args:
|
||||
sort_by (TimelessSortingMethod, optional): The sorting method of
|
||||
the resulting list.
|
||||
Defaults to TimelessSortingMethod.TITLE.
|
||||
|
||||
Returns:
|
||||
List[dict]: The id, title, text and color
|
||||
List[dict]: The id, title, text and color of each template.
|
||||
"""
|
||||
sort_function = self.sort_functions.get(
|
||||
sort_by,
|
||||
self.sort_functions['title']
|
||||
)
|
||||
|
||||
templates: list = list(map(dict, get_db(dict).execute("""
|
||||
SELECT
|
||||
id,
|
||||
title, text,
|
||||
color
|
||||
FROM templates
|
||||
WHERE user_id = ?
|
||||
ORDER BY title, id;
|
||||
""",
|
||||
(self.user_id,)
|
||||
)))
|
||||
templates = [
|
||||
dict(r)
|
||||
for r in get_db(dict).execute("""
|
||||
SELECT
|
||||
id,
|
||||
title, text,
|
||||
color
|
||||
FROM templates
|
||||
WHERE user_id = ?
|
||||
ORDER BY title, id;
|
||||
""",
|
||||
(self.user_id,)
|
||||
)
|
||||
]
|
||||
|
||||
# Sort result
|
||||
templates.sort(key=sort_function[0], reverse=sort_function[1])
|
||||
templates.sort(key=sort_by.value[0], reverse=sort_by.value[1])
|
||||
|
||||
return templates
|
||||
|
||||
def search(self, query: str, sort_by: Literal["title", "title_reversed", "date_added", "date_added_reversed"] = "title") -> List[dict]:
|
||||
def search(
|
||||
self,
|
||||
query: str,
|
||||
sort_by: TimelessSortingMethod = TimelessSortingMethod.TITLE
|
||||
) -> List[dict]:
|
||||
"""Search for templates
|
||||
|
||||
Args:
|
||||
query (str): The term to search for
|
||||
sort_by (Literal["title", "title_reversed", "date_added", "date_added_reversed"], optional): How to sort the result. Defaults to "title".
|
||||
query (str): The term to search for.
|
||||
|
||||
sort_by (TimelessSortingMethod, optional): The sorting method of
|
||||
the resulting list.
|
||||
Defaults to TimelessSortingMethod.TITLE.
|
||||
|
||||
Returns:
|
||||
List[dict]: All templates that match. Similar output to self.fetchall
|
||||
List[dict]: All templates that match. Similar output to `self.fetchall`
|
||||
"""
|
||||
query = query.lower()
|
||||
reminders = list(filter(
|
||||
lambda p: filter_function(query, p),
|
||||
self.fetchall(sort_by)
|
||||
))
|
||||
return reminders
|
||||
templates = [
|
||||
r for r in self.fetchall(sort_by)
|
||||
if search_filter(query, r)
|
||||
]
|
||||
return templates
|
||||
|
||||
def fetchone(self, id: int) -> Template:
|
||||
"""Get one template
|
||||
@@ -203,10 +257,20 @@ class Templates:
|
||||
"""Add a template
|
||||
|
||||
Args:
|
||||
title (str): The title of the entry
|
||||
notification_services (List[int]): The id's of the notification services to use to send the reminder.
|
||||
text (str, optional): The body of the reminder. Defaults to ''.
|
||||
color (str, optional): The hex code of the color of the template, which is shown in the web-ui. Defaults to None.
|
||||
title (str): The title of the entry.
|
||||
|
||||
notification_services (List[int]): The id's of the
|
||||
notification services to use to send the reminder.
|
||||
|
||||
text (str, optional): The body of the reminder.
|
||||
Defaults to ''.
|
||||
|
||||
color (str, optional): The hex code of the color of the template,
|
||||
which is shown in the web-ui.
|
||||
Defaults to None.
|
||||
|
||||
Raises:
|
||||
NotificationServiceNotFound: One of the notification services was not found
|
||||
|
||||
Returns:
|
||||
Template: The info about the template
|
||||
@@ -216,19 +280,32 @@ class Templates:
|
||||
)
|
||||
|
||||
cursor = get_db()
|
||||
cursor.connection.isolation_level = None
|
||||
cursor.execute("BEGIN TRANSACTION;")
|
||||
|
||||
id = cursor.execute("""
|
||||
INSERT INTO templates(user_id, title, text, color)
|
||||
VALUES (?,?,?,?);
|
||||
""",
|
||||
(self.user_id, title, text, color)
|
||||
).lastrowid
|
||||
|
||||
|
||||
try:
|
||||
cursor.executemany(
|
||||
"INSERT INTO reminder_services(template_id, notification_service_id) VALUES (?, ?);",
|
||||
cursor.executemany("""
|
||||
INSERT INTO reminder_services(
|
||||
template_id,
|
||||
notification_service_id
|
||||
)
|
||||
VALUES (?, ?);
|
||||
""",
|
||||
((id, service) for service in notification_services)
|
||||
)
|
||||
cursor.execute("COMMIT;")
|
||||
|
||||
except IntegrityError:
|
||||
raise NotificationServiceNotFound
|
||||
|
||||
finally:
|
||||
cursor.connection.isolation_level = ""
|
||||
|
||||
return self.fetchone(id)
|
||||
|
||||
Reference in New Issue
Block a user