Added UserMessageCountPerHour model #168

This commit is contained in:
Sven Heidemann 2023-01-11 19:08:00 +01:00
parent 3d01c9f798
commit a216506a37
12 changed files with 298 additions and 6 deletions

View File

@ -10,6 +10,7 @@ from bot_data.migration.auto_role_migration import AutoRoleMigration
from bot_data.migration.initial_migration import InitialMigration from bot_data.migration.initial_migration import InitialMigration
from bot_data.migration.level_migration import LevelMigration from bot_data.migration.level_migration import LevelMigration
from bot_data.migration.stats_migration import StatsMigration from bot_data.migration.stats_migration import StatsMigration
from bot_data.migration.user_message_count_per_hour_migration import UserMessageCountPerHourMigration
from bot_data.service.migration_service import MigrationService from bot_data.service.migration_service import MigrationService
@ -29,3 +30,4 @@ class StartupMigrationExtension(StartupExtensionABC):
services.add_transient(MigrationABC, LevelMigration) # 06.11.2022 #25 - 0.3.0 services.add_transient(MigrationABC, LevelMigration) # 06.11.2022 #25 - 0.3.0
services.add_transient(MigrationABC, StatsMigration) # 09.11.2022 #46 - 0.3.0 services.add_transient(MigrationABC, StatsMigration) # 09.11.2022 #46 - 0.3.0
services.add_transient(MigrationABC, AutoRoleFix1Migration) # 30.12.2022 #151 - 0.3.0 services.add_transient(MigrationABC, AutoRoleFix1Migration) # 30.12.2022 #151 - 0.3.0
services.add_transient(MigrationABC, UserMessageCountPerHourMigration) # 11.01.2023 #168 - 0.3.1

View File

@ -0,0 +1,33 @@
from abc import ABC, abstractmethod
from typing import Optional
from cpl_query.extension import List
from bot_data.model.user_message_count_per_hour import UserMessageCountPerHour
class UserMessageCountPerHourRepositoryABC(ABC):
@abstractmethod
def __init__(self): pass
@abstractmethod
def get_user_message_count_per_hours(self) -> List[UserMessageCountPerHour]: pass
@abstractmethod
def find_user_message_count_per_hours_by_user_id(self, user_id: int) -> List[Optional[UserMessageCountPerHour]]: pass
@abstractmethod
def find_user_message_count_per_hours_by_user_id_and_active_hour(self, user_id: int) -> List[Optional[UserMessageCountPerHour]]: pass
@abstractmethod
def add_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): pass
@abstractmethod
def update_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): pass
@abstractmethod
def delete_user_message_count_per_hour(self, umcph: UserMessageCountPerHour): pass
@abstractmethod
def delete_user_message_count_per_hour_by_user_id(self, user_id: int): pass

View File

@ -13,7 +13,8 @@ from bot_data.abc.level_repository_abc import LevelRepositoryABC
from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC
from bot_data.abc.statistic_repository_abc import StatisticRepositoryABC from bot_data.abc.statistic_repository_abc import StatisticRepositoryABC
from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC
from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC
from bot_data.abc.user_message_count_per_hour_repository_abc import UserMessageCountPerHourRepositoryABC
from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.service.auth_user_repository_service import AuthUserRepositoryService from bot_data.service.auth_user_repository_service import AuthUserRepositoryService
from bot_data.service.auto_role_repository_service import AutoRoleRepositoryService from bot_data.service.auto_role_repository_service import AutoRoleRepositoryService
@ -24,6 +25,7 @@ from bot_data.service.seeder_service import SeederService
from bot_data.service.server_repository_service import ServerRepositoryService from bot_data.service.server_repository_service import ServerRepositoryService
from bot_data.service.statistic_repository_service import StatisticRepositoryService from bot_data.service.statistic_repository_service import StatisticRepositoryService
from bot_data.service.user_joined_server_repository_service import UserJoinedServerRepositoryService from bot_data.service.user_joined_server_repository_service import UserJoinedServerRepositoryService
from bot_data.service.user_joined_voice_channel_repository_service import UserMessageCountPerHourRepositoryService
from bot_data.service.user_joined_voice_channel_service import UserJoinedVoiceChannelRepositoryService from bot_data.service.user_joined_voice_channel_service import UserJoinedVoiceChannelRepositoryService
from bot_data.service.user_repository_service import UserRepositoryService from bot_data.service.user_repository_service import UserRepositoryService
@ -47,5 +49,6 @@ class DataModule(ModuleABC):
services.add_transient(AutoRoleRepositoryABC, AutoRoleRepositoryService) services.add_transient(AutoRoleRepositoryABC, AutoRoleRepositoryService)
services.add_transient(LevelRepositoryABC, LevelRepositoryService) services.add_transient(LevelRepositoryABC, LevelRepositoryService)
services.add_transient(StatisticRepositoryABC, StatisticRepositoryService) services.add_transient(StatisticRepositoryABC, StatisticRepositoryService)
services.add_transient(UserMessageCountPerHourRepositoryABC, UserMessageCountPerHourRepositoryService)
services.add_transient(SeederService) services.add_transient(SeederService)

View File

@ -0,0 +1,36 @@
from bot_core.logging.database_logger import DatabaseLogger
from bot_data.abc.migration_abc import MigrationABC
from bot_data.db_context import DBContext
class UserMessageCountPerHourMigration(MigrationABC):
name = '0.3.1_UserMessageCountPerHourMigration'
def __init__(self, logger: DatabaseLogger, db: DBContext):
MigrationABC.__init__(self)
self._logger = logger
self._db = db
self._cursor = db.cursor
def upgrade(self):
self._logger.debug(__name__, 'Running upgrade')
self._cursor.execute(
str(f"""
CREATE TABLE IF NOT EXISTS `UserMessageCountPerHour` (
`Id` BIGINT NOT NULL AUTO_INCREMENT,
`Date` DATETIME(6) NOT NULL,
`Hour` BIGINT,
`Count` BIGINT,
`UserId` BIGINT,
`CreatedAt` DATETIME(6),
`LastModifiedAt` DATETIME(6),
PRIMARY KEY(`Id`),
FOREIGN KEY (`UserId`) REFERENCES `Users`(`UserId`)
);
""")
)
def downgrade(self):
self._cursor.execute('DROP TABLE `UserMessageCountPerHour`;')

View File

@ -0,0 +1,117 @@
from datetime import datetime
from cpl_core.database import TableABC
from bot_data.model.user import User
class UserMessageCountPerHour(TableABC):
def __init__(
self,
date: datetime,
hour: int,
count: int,
user: User,
created_at: datetime = None,
modified_at: datetime = None,
id=0):
self._id = id
self._date = date
self._hour = hour
self._count = count
self._user = user
TableABC.__init__(self)
self._created_at = created_at if created_at is not None else self._created_at
self._modified_at = modified_at if modified_at is not None else self._modified_at
@property
def id(self) -> int:
return self._id
@property
def date(self) -> datetime:
return self._date
@property
def hour(self) -> int:
return self._hour
@property
def count(self) -> int:
return self._count
@property
def user(self) -> User:
return self._user
@staticmethod
def get_select_all_string() -> str:
return str(f"""
SELECT * FROM `UserMessageCountPerHour`;
""")
@staticmethod
def get_select_by_id_string(id: int) -> str:
return str(f"""
SELECT * FROM `UserMessageCountPerHour`
WHERE `Id` = {id};
""")
@staticmethod
def get_select_by_user_id_string(id: int) -> str:
return str(f"""
SELECT * FROM `UserMessageCountPerHour`
WHERE `UserId` = {id};
""")
@staticmethod
def get_select_by_user_id_and_current_hour_string(id: int) -> str:
now = datetime.now()
date = f'{now.year}-{now.month}-{now.day}%'
return str(f"""
SELECT * FROM `UserMessageCountPerHour`
WHERE `UserId` = {id}
AND `Date` LIKE '{date}'
AND `Hour` = {now.hour};
""")
@property
def insert_string(self) -> str:
return str(f"""
INSERT INTO `UserMessageCountPerHour` (
`UserId`, `Date`, `JoinedOn`, `Count`, `CreatedAt`, `LastModifiedAt`
) VALUES (
{self._user.user_id},
'{self._date}',
{self._hour},
{self._count},
'{self._created_at}',
'{self._modified_at}'
);
""")
@property
def udpate_string(self) -> str:
return str(f"""
UPDATE `UserMessageCountPerHour`
SET `Count` = '{self._count}',
`LastModifiedAt` = '{self._modified_at}'
WHERE `Id` = {self._id};
""")
@property
def delete_string(self) -> str:
return str(f"""
DELETE FROM `UserMessageCountPerHour`
WHERE `Id` = {self._id};
""")
@staticmethod
def delete_by_user_id_string(id: int) -> str:
return str(f"""
DELETE FROM `UserMessageCountPerHour`
WHERE `UserId` = {id}
""")

View File

@ -0,0 +1,101 @@
from typing import Optional
from cpl_core.database.context import DatabaseContextABC
from cpl_query.extension import List
from bot_core.logging.database_logger import DatabaseLogger
from bot_data.abc.user_message_count_per_hour_repository_abc import UserMessageCountPerHourRepositoryABC
from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.model.user_message_count_per_hour import UserMessageCountPerHour
class UserMessageCountPerHourRepositoryService(UserMessageCountPerHourRepositoryABC):
def __init__(
self,
logger: DatabaseLogger,
db_context: DatabaseContextABC,
users: UserRepositoryABC,
umcphs: UserMessageCountPerHourRepositoryABC,
):
UserMessageCountPerHourRepositoryABC.__init__(self)
self._logger = logger
self._context = db_context
self._users = users
self._umcphs = umcphs
@staticmethod
def _get_value_from_result(value: any) -> Optional[any]:
if isinstance(value, str) and 'NULL' in value:
return None
return value
def _from_result(self, result: tuple) -> UserMessageCountPerHour:
return UserMessageCountPerHour(
self._get_value_from_result(result[1]),
self._get_value_from_result(result[2]),
self._get_value_from_result(result[3]),
self._users.get_user_by_id(self._get_value_from_result(result[4])),
self._get_value_from_result(result[5]),
self._get_value_from_result(result[6]),
id=self._get_value_from_result(result[0])
)
def get_user_message_count_per_hours(self) -> List[UserMessageCountPerHour]:
umcphs = List(UserMessageCountPerHour)
self._logger.trace(__name__, f'Send SQL command: {UserMessageCountPerHour.get_select_all_string()}')
results = self._context.select(UserMessageCountPerHour.get_select_all_string())
for result in results:
self._logger.trace(__name__, f'Get user message count per hour with id {result[0]}')
umcphs.append(self._from_result(result))
return umcphs
def find_user_message_count_per_hours_by_user_id(self, user_id: int) -> List[Optional[UserMessageCountPerHour]]:
umcphs = List(UserMessageCountPerHour)
sql = UserMessageCountPerHour.get_select_by_user_id_string(user_id)
self._logger.trace(__name__, f'Send SQL command: {sql}')
results = self._context.select(sql)
if results is None or len(results) == 0:
return umcphs
for result in results:
self._logger.trace(__name__, f'Get user message count per hour with id {result[0]}')
umcphs.append(self._from_result(result))
return umcphs
def find_user_message_count_per_hours_by_user_id_and_active_hour(self, user_id: int) -> List[
Optional[UserMessageCountPerHour]
]:
umcphs = List(UserMessageCountPerHour)
sql = UserMessageCountPerHour.get_select_by_user_id_and_current_hour_string(user_id)
self._logger.trace(__name__, f'Send SQL command: {sql}')
results = self._context.select(sql)
if results is None or len(results) == 0:
return umcphs
for result in results:
self._logger.trace(__name__, f'Get user message count per hour with id {result[0]}')
umcphs.append(self._from_result(result))
return umcphs
def add_user_message_count_per_hour(self, umcph: UserMessageCountPerHour):
self._logger.trace(__name__, f'Send SQL command: {umcph.insert_string}')
self._context.cursor.execute(umcph.insert_string)
def update_user_message_count_per_hour(self, umcph: UserMessageCountPerHour):
self._logger.trace(__name__, f'Send SQL command: {umcph.udpate_string}')
self._context.cursor.execute(umcph.udpate_string)
def delete_user_message_count_per_hour(self, umcph: UserMessageCountPerHour):
self._logger.trace(__name__, f'Send SQL command: {umcph.delete_string}')
self._context.cursor.execute(umcph.delete_string)
def delete_user_message_count_per_hour_by_user_id(self, user_id: int):
sql = UserMessageCountPerHour.delete_by_user_id_string(user_id)
self._logger.trace(__name__, f'Send SQL command: {sql}')
self._context.cursor.execute(sql)

View File

@ -4,7 +4,7 @@ from cpl_core.database.context import DatabaseContextABC
from cpl_query.extension import List from cpl_query.extension import List
from bot_core.logging.database_logger import DatabaseLogger from bot_core.logging.database_logger import DatabaseLogger
from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC
from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.model.user_joined_voice_channel import UserJoinedVoiceChannel from bot_data.model.user_joined_voice_channel import UserJoinedVoiceChannel

View File

@ -17,7 +17,7 @@ from bot_core.logging.command_logger import CommandLogger
from bot_core.pipes.date_time_offset_pipe import DateTimeOffsetPipe from bot_core.pipes.date_time_offset_pipe import DateTimeOffsetPipe
from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC
from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC
from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC
from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC
from modules.level.service.level_service import LevelService from modules.level.service.level_service import LevelService
from modules.permission.abc.permission_service_abc import PermissionServiceABC from modules.permission.abc.permission_service_abc import PermissionServiceABC

View File

@ -12,7 +12,7 @@ from bot_core.helper.event_checks import EventChecks
from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC
from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC
from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC
from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC
from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.model.server import Server from bot_data.model.server import Server
from bot_data.model.user import User from bot_data.model.user import User

View File

@ -12,7 +12,7 @@ from bot_core.pipes.date_time_offset_pipe import DateTimeOffsetPipe
from bot_data.abc.client_repository_abc import ClientRepositoryABC from bot_data.abc.client_repository_abc import ClientRepositoryABC
from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC
from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC
from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC
from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.model.client import Client from bot_data.model.client import Client
from bot_data.model.known_user import KnownUser from bot_data.model.known_user import KnownUser

View File

@ -10,7 +10,7 @@ from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC
from bot_data.abc.level_repository_abc import LevelRepositoryABC from bot_data.abc.level_repository_abc import LevelRepositoryABC
from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC
from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC
from bot_data.abc.user_joined_voice_channel_abc import UserJoinedVoiceChannelRepositoryABC from bot_data.abc.user_joined_voice_channel_repository_abc import UserJoinedVoiceChannelRepositoryABC
from bot_data.abc.user_repository_abc import UserRepositoryABC from bot_data.abc.user_repository_abc import UserRepositoryABC
from bot_data.model.auto_role import AutoRole from bot_data.model.auto_role import AutoRole
from bot_data.model.client import Client from bot_data.model.client import Client