diff --git a/bot/src/bot_core/abc/task_abc.py b/bot/src/bot_core/abc/task_abc.py index 5f578a99..9bbd3e54 100644 --- a/bot/src/bot_core/abc/task_abc.py +++ b/bot/src/bot_core/abc/task_abc.py @@ -21,7 +21,7 @@ class TaskABC(commands.Cog): @ServiceProviderABC.inject async def _wait_until_ready(self, config: ConfigurationABC, logger: TaskLogger, bot: DiscordBotServiceABC): - logger.debug(__name__, f"Waiting before {type(self).__name__}") + logger.debug(__name__, f"Waiting before ready {type(self).__name__}") await bot.wait_until_ready() async def wait(): diff --git a/bot/src/bot_core/configuration/feature_flags_enum.py b/bot/src/bot_core/configuration/feature_flags_enum.py index 6d051b0c..8506af95 100644 --- a/bot/src/bot_core/configuration/feature_flags_enum.py +++ b/bot/src/bot_core/configuration/feature_flags_enum.py @@ -27,3 +27,4 @@ class FeatureFlagsEnum(Enum): short_role_name = "ShortRoleName" technician_full_access = "TechnicianFullAccess" steam_special_offers = "SteamSpecialOffers" + scheduled_events = "ScheduledEvents" diff --git a/bot/src/bot_core/configuration/feature_flags_settings.py b/bot/src/bot_core/configuration/feature_flags_settings.py index 0ed95e71..3b994b17 100644 --- a/bot/src/bot_core/configuration/feature_flags_settings.py +++ b/bot/src/bot_core/configuration/feature_flags_settings.py @@ -29,6 +29,7 @@ class FeatureFlagsSettings(ConfigurationModelABC): FeatureFlagsEnum.short_role_name.value: False, # 28.09.2023 #378 FeatureFlagsEnum.technician_full_access.value: False, # 03.10.2023 #393 FeatureFlagsEnum.steam_special_offers.value: False, # 11.10.2023 #188 + FeatureFlagsEnum.scheduled_events.value: False, # 14.11.2023 #410 } def __init__(self, **kwargs: dict): diff --git a/bot/src/bot_data/abc/scheduled_event_repository_abc.py b/bot/src/bot_data/abc/scheduled_event_repository_abc.py new file mode 100644 index 00000000..ff0d54c2 --- /dev/null +++ b/bot/src/bot_data/abc/scheduled_event_repository_abc.py @@ -0,0 +1,35 @@ +from abc import ABC, abstractmethod + +from cpl_query.extension import List + +from bot_data.model.scheduled_event import ScheduledEvent + + +class ScheduledEventRepositoryABC(ABC): + @abstractmethod + def __init__(self): + pass + + @abstractmethod + def get_scheduled_events(self) -> List[ScheduledEvent]: + pass + + @abstractmethod + def get_scheduled_event_by_id(self, id: int) -> ScheduledEvent: + pass + + @abstractmethod + def get_scheduled_events_by_server_id(self, id: int) -> List[ScheduledEvent]: + pass + + @abstractmethod + def add_scheduled_event(self, scheduled_event: ScheduledEvent): + pass + + @abstractmethod + def update_scheduled_event(self, scheduled_event: ScheduledEvent): + pass + + @abstractmethod + def delete_scheduled_event(self, scheduled_event: ScheduledEvent): + pass diff --git a/bot/src/bot_data/data_module.py b/bot/src/bot_data/data_module.py index cec9cb37..5d20e874 100644 --- a/bot/src/bot_data/data_module.py +++ b/bot/src/bot_data/data_module.py @@ -14,6 +14,7 @@ from bot_data.abc.data_seeder_abc import DataSeederABC from bot_data.abc.game_server_repository_abc import GameServerRepositoryABC from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC from bot_data.abc.level_repository_abc import LevelRepositoryABC +from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC from bot_data.abc.server_config_repository_abc import ServerConfigRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.short_role_name_repository_abc import ShortRoleNameRepositoryABC @@ -45,6 +46,7 @@ from bot_data.service.client_repository_service import ClientRepositoryService from bot_data.service.game_server_repository_service import GameServerRepositoryService from bot_data.service.known_user_repository_service import KnownUserRepositoryService from bot_data.service.level_repository_service import LevelRepositoryService +from bot_data.service.scheduled_event_repository_service import ScheduledEventRepositoryService from bot_data.service.seeder_service import SeederService from bot_data.service.server_config_repository_service import ( ServerConfigRepositoryService, @@ -115,6 +117,7 @@ class DataModule(ModuleABC): services.add_transient(ServerConfigRepositoryABC, ServerConfigRepositoryService) services.add_transient(ShortRoleNameRepositoryABC, ShortRoleNameRepositoryService) services.add_transient(SteamSpecialOfferRepositoryABC, SteamSpecialOfferRepositoryService) + services.add_transient(ScheduledEventRepositoryABC, ScheduledEventRepositoryService) services.add_transient(SeederService) services.add_transient(DataSeederABC, TechnicianConfigSeeder) diff --git a/bot/src/bot_data/model/scheduled_event.py b/bot/src/bot_data/model/scheduled_event.py new file mode 100644 index 00000000..ca762eab --- /dev/null +++ b/bot/src/bot_data/model/scheduled_event.py @@ -0,0 +1,188 @@ +from datetime import datetime +from typing import Optional + +import discord +from cpl_core.database import TableABC + +from bot_data.model.scheduled_event_interval_enum import ScheduledEventIntervalEnum +from bot_data.model.server import Server + + +class ScheduledEvent(TableABC): + def __init__( + self, + interval: ScheduledEventIntervalEnum, + name: str, + description: str, + channel_id: int, + start_time: datetime, + end_time: Optional[datetime], + entity_type: discord.EntityType, + location: Optional[str], + server: Optional[Server], + created_at: datetime = None, + modified_at: datetime = None, + id=0, + ): + self._id = id + self._interval = interval + self._name = name + self._description = description + self._channel_id = channel_id + self._start_time = start_time + self._end_time = end_time + self._entity_type = entity_type + self._location = location + self._server = server + + 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 interval(self) -> ScheduledEventIntervalEnum: + return self._interval + + @interval.setter + def interval(self, value: ScheduledEventIntervalEnum): + self._interval = value + + @property + def name(self) -> str: + return self._name + + @name.setter + def name(self, value: str): + self._name = value + + @property + def description(self) -> str: + return self._description + + @description.setter + def description(self, value: str): + self._description = value + + @property + def channel_id(self) -> int: + return self._channel_id + + @channel_id.setter + def channel_id(self, value: int): + self._channel_id = value + + @property + def start_time(self) -> datetime: + return self._start_time + + @start_time.setter + def start_time(self, value: datetime): + self._start_time = value + + @property + def end_time(self) -> datetime: + return self._end_time + + @end_time.setter + def end_time(self, value: datetime): + self._end_time = value + + @property + def entity_type(self) -> discord.EntityType: + return self._entity_type + + @entity_type.setter + def entity_type(self, value: discord.EntityType): + self._entity_type = value + + @property + def location(self) -> str: + return self._location + + @location.setter + def location(self, value: str): + self._location = value + + @property + def server(self) -> Server: + return self._server + + @server.setter + def server(self, value: Server): + self._server = value + + @staticmethod + def get_select_all_string() -> str: + return str( + f""" + SELECT * FROM `ScheduledEvents`; + """ + ) + + @staticmethod + def get_select_by_id_string(id: int) -> str: + return str( + f""" + SELECT * FROM `ScheduledEvents` + WHERE `Id` = {id}; + """ + ) + + @staticmethod + def get_select_by_server_id_string(s_id: int) -> str: + return str( + f""" + SELECT * FROM `ScheduledEvents` + WHERE `ServerId` = {s_id}; + """ + ) + + @property + def insert_string(self) -> str: + return str( + f""" + INSERT INTO `ScheduledEvents` ( + `Interval`, `Name`, `Description`, `ChannelId`, `StartTime`, `EndTime`, `EntityType`, `Location`, `ServerId` + ) VALUES ( + '{self._interval.value}', + '{self._name}', + {"NULL" if self._description is None else f"'{self._description}'"}, + {"NULL" if self._channel_id is None else f"'{self._channel_id}'"}, + '{self._start_time}', + {"NULL" if self._end_time is None else f"'{self._end_time}'"}, + '{self._entity_type.value}', + {"NULL" if self._location is None else f"'{self._location}'"}, + {self._server.id} + ); + """ + ) + + @property + def udpate_string(self) -> str: + return str( + f""" + UPDATE `ScheduledEvents` + SET `Interval` = '{self._interval.value}', + `Name` = '{self._name}', + `Description` = {"NULL" if self._description is None else f"'{self._description}'"}, + `ChannelId` = {"NULL" if self._channel_id is None else f"'{self._channel_id}'"}, + `StartTime` = '{self._start_time}', + `EndTime` = {"NULL" if self._end_time is None else f"'{self._end_time}'"}, + `EntityType` = '{self._entity_type.value}', + `Location` = {"NULL" if self._location is None else f"'{self._location}'"} + WHERE `Id` = {self._id}; + """ + ) + + @property + def delete_string(self) -> str: + return str( + f""" + DELETE FROM `ScheduledEvents` + WHERE `Id` = {self._id}; + """ + ) diff --git a/bot/src/bot_data/model/scheduled_event_history.py b/bot/src/bot_data/model/scheduled_event_history.py new file mode 100644 index 00000000..b910e796 --- /dev/null +++ b/bot/src/bot_data/model/scheduled_event_history.py @@ -0,0 +1,118 @@ +from datetime import datetime +from typing import Optional + +import discord +from cpl_core.database import TableABC + +from bot_data.abc.history_table_abc import HistoryTableABC +from bot_data.model.server import Server + + +class ScheduledEventHistory(HistoryTableABC): + def __init__( + self, + interval: str, + name: str, + description: str, + channel_id: int, + start_time: datetime, + end_time: Optional[datetime], + entity_type: discord.EntityType, + location: Optional[str], + server: Optional[Server], + deleted: bool, + date_from: str, + date_to: str, + id=0, + ): + HistoryTableABC.__init__(self) + self._id = id + self._interval = interval + self._name = name + self._description = description + self._channel_id = channel_id + self._start_time = start_time + self._end_time = end_time + self._entity_type = entity_type + self._location = location + self._server = server + + self._deleted = deleted + self._date_from = date_from + self._date_to = date_to + + @property + def id(self) -> int: + return self._id + + @property + def interval(self) -> str: + return self._interval + + @interval.setter + def interval(self, value: str): + self._interval = value + + @property + def name(self) -> str: + return self._name + + @name.setter + def name(self, value: str): + self._name = value + + @property + def description(self) -> str: + return self._description + + @description.setter + def description(self, value: str): + self._description = value + + @property + def channel_id(self) -> int: + return self._channel_id + + @channel_id.setter + def channel_id(self, value: int): + self._channel_id = value + + @property + def start_time(self) -> datetime: + return self._start_time + + @start_time.setter + def start_time(self, value: datetime): + self._start_time = value + + @property + def end_time(self) -> datetime: + return self._end_time + + @end_time.setter + def end_time(self, value: datetime): + self._end_time = value + + @property + def entity_type(self) -> discord.EntityType: + return self._entity_type + + @entity_type.setter + def entity_type(self, value: discord.EntityType): + self._entity_type = value + + @property + def location(self) -> str: + return self._location + + @location.setter + def location(self, value: str): + self._location = value + + @property + def server(self) -> Server: + return self._server + + @server.setter + def server(self, value: Server): + self._server = value diff --git a/bot/src/bot_data/model/scheduled_event_interval_enum.py b/bot/src/bot_data/model/scheduled_event_interval_enum.py new file mode 100644 index 00000000..7f13c589 --- /dev/null +++ b/bot/src/bot_data/model/scheduled_event_interval_enum.py @@ -0,0 +1,8 @@ +from enum import Enum + + +class ScheduledEventIntervalEnum(Enum): + daily = "daily" + weekly = "weekly" + monthly = "monthly" + yearly = "yearly" diff --git a/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_down.sql b/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_down.sql new file mode 100644 index 00000000..d055ec13 --- /dev/null +++ b/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_down.sql @@ -0,0 +1,3 @@ +DROP TABLE `ShortRoleNames`; + +DROP TABLE `ShortRoleNamesHistory`; \ No newline at end of file diff --git a/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_up.sql b/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_up.sql new file mode 100644 index 00000000..843c21fc --- /dev/null +++ b/bot/src/bot_data/scripts/1.2.2/1_ScheduledEvents_up.sql @@ -0,0 +1,83 @@ +CREATE TABLE IF NOT EXISTS `ScheduledEvents` +( + `Id` BIGINT NOT NULL AUTO_INCREMENT, + `Interval` ENUM ('daily', 'weekly', 'monthly', 'yearly') NOT NULL, + `Name` VARCHAR(255) NOT NULL, + `Description` VARCHAR(255) NULL, + `ChannelId` BIGINT NULL, + `StartTime` DATETIME(6) NOT NULL, + `EndTime` DATETIME(6) NULL, + `EntityType` ENUM ('1','2','3') NOT NULL, + `Location` VARCHAR(255) NULL, + `ServerId` BIGINT, + `CreatedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6), + `LastModifiedAt` DATETIME(6) NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + PRIMARY KEY (`Id`), + FOREIGN KEY (`ServerId`) REFERENCES `Servers` (`ServerId`) +); + +CREATE TABLE IF NOT EXISTS `ScheduledEventsHistory` +( + `Id` BIGINT(20) NOT NULL, + `Interval` ENUM ('daily', 'weekly', 'monthly', 'yearly') NOT NULL, + `Name` VARCHAR(255) NOT NULL, + `Description` VARCHAR(255) NULL, + `ChannelId` BIGINT NULL, + `StartTime` DATETIME(6) NOT NULL, + `EndTime` DATETIME(6) NULL, + `EntityType` ENUM ('1','2','3') NOT NULL, + `Location` VARCHAR(255) NULL, + `ServerId` BIGINT(20) DEFAULT NULL, + `Deleted` BOOL DEFAULT FALSE, + `DateFrom` DATETIME(6) NOT NULL, + `DateTo` DATETIME(6) NOT NULL +); + +DROP TRIGGER IF EXISTS `TR_ScheduledEventsUpdate`; + +CREATE TRIGGER `TR_ScheduledEventsUpdate` + AFTER UPDATE + ON `ScheduledEvents` + FOR EACH ROW +BEGIN + INSERT INTO `ScheduledEventsHistory` (`Id`, + `Interval`, + `Name`, + `Description`, + `ChannelId`, + `StartTime`, + `EndTime`, + `EntityType`, + `Location`, + `ServerId`, + `DateFrom`, + `DateTo`) + VALUES (OLD.Id, OLD.Interval, OLD.Name, OLD.Description, OLD.ChannelId, OLD.StartTime, OLD.EndTime, OLD.EntityType, + OLD.Location, OLD.ServerId, OLD.LastModifiedAt, + CURRENT_TIMESTAMP(6)); +END; + +DROP TRIGGER IF EXISTS `TR_ScheduledEventsDelete`; + +CREATE TRIGGER `TR_ScheduledEventsDelete` + AFTER DELETE + ON `ScheduledEvents` + FOR EACH ROW +BEGIN + INSERT INTO `ScheduledEventsHistory` (`Id`, + `Interval`, + `Name`, + `Description`, + `ChannelId`, + `StartTime`, + `EndTime`, + `EntityType`, + `Location`, + `ServerId`, + `Deleted`, + `DateFrom`, + `DateTo`) + VALUES (OLD.Id, OLD.Interval, OLD.Name, OLD.Description, OLD.ChannelId, OLD.StartTime, OLD.EndTime, OLD.EntityType, + OLD.Location, OLD.ServerId, TRUE, OLD.LastModifiedAt, + CURRENT_TIMESTAMP(6)); +END; \ No newline at end of file diff --git a/bot/src/bot_data/service/scheduled_event_repository_service.py b/bot/src/bot_data/service/scheduled_event_repository_service.py new file mode 100644 index 00000000..dc394fdf --- /dev/null +++ b/bot/src/bot_data/service/scheduled_event_repository_service.py @@ -0,0 +1,91 @@ +from typing import Optional + +from cpl_core.database.context import DatabaseContextABC +from cpl_query.extension import List +from discord import EntityType + +from bot_core.logging.database_logger import DatabaseLogger +from bot_data.abc.server_repository_abc import ServerRepositoryABC +from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC +from bot_data.model.scheduled_event import ScheduledEvent +from bot_data.model.scheduled_event_interval_enum import ScheduledEventIntervalEnum + + +class ScheduledEventRepositoryService(ScheduledEventRepositoryABC): + def __init__( + self, + logger: DatabaseLogger, + db_context: DatabaseContextABC, + servers: ServerRepositoryABC, + ): + self._logger = logger + self._context = db_context + + self._servers = servers + + ScheduledEventRepositoryABC.__init__(self) + + @staticmethod + def _get_value_from_result(value: any) -> Optional[any]: + if isinstance(value, str) and "NULL" in value: + return None + + return value + + def _scheduled_event_from_result(self, sql_result: tuple) -> ScheduledEvent: + return ScheduledEvent( + self._get_value_from_result(ScheduledEventIntervalEnum(sql_result[1])), # interval + self._get_value_from_result(sql_result[2]), # name + self._get_value_from_result(sql_result[3]), # description + int(self._get_value_from_result(sql_result[4])), # channel_id + self._get_value_from_result(sql_result[5]), # start_time + self._get_value_from_result(sql_result[6]), # end_time + EntityType(int(self._get_value_from_result(sql_result[7]))), # entity_type + self._get_value_from_result(sql_result[8]), # location + self._servers.get_server_by_id((sql_result[9])), # server + self._get_value_from_result(sql_result[10]), # created_at + self._get_value_from_result(sql_result[11]), # modified_at + id=self._get_value_from_result(sql_result[0]), + ) + + def get_scheduled_events(self) -> List[ScheduledEvent]: + scheduled_events = List(ScheduledEvent) + self._logger.trace(__name__, f"Send SQL command: {ScheduledEvent.get_select_all_string()}") + results = self._context.select(ScheduledEvent.get_select_all_string()) + for result in results: + self._logger.trace(__name__, f"Get scheduled_event with id {result[0]}") + scheduled_events.append(self._scheduled_event_from_result(result)) + + return scheduled_events + + def get_scheduled_event_by_id(self, id: int) -> ScheduledEvent: + self._logger.trace(__name__, f"Send SQL command: {ScheduledEvent.get_select_by_id_string(id)}") + result = self._context.select(ScheduledEvent.get_select_by_id_string(id))[0] + + return self._scheduled_event_from_result(result) + + def get_scheduled_events_by_server_id(self, server_id: int) -> List[ScheduledEvent]: + scheduled_events = List(ScheduledEvent) + self._logger.trace( + __name__, + f"Send SQL command: {ScheduledEvent.get_select_by_server_id_string(server_id)}", + ) + results = self._context.select(ScheduledEvent.get_select_by_server_id_string(server_id)) + + for result in results: + self._logger.trace(__name__, f"Get scheduled_event with id {result[0]}") + scheduled_events.append(self._scheduled_event_from_result(result)) + + return scheduled_events + + def add_scheduled_event(self, scheduled_event: ScheduledEvent): + self._logger.trace(__name__, f"Send SQL command: {scheduled_event.insert_string}") + self._context.cursor.execute(scheduled_event.insert_string) + + def update_scheduled_event(self, scheduled_event: ScheduledEvent): + self._logger.trace(__name__, f"Send SQL command: {scheduled_event.udpate_string}") + self._context.cursor.execute(scheduled_event.udpate_string) + + def delete_scheduled_event(self, scheduled_event: ScheduledEvent): + self._logger.trace(__name__, f"Send SQL command: {scheduled_event.delete_string}") + self._context.cursor.execute(scheduled_event.delete_string) diff --git a/bot/src/bot_graphql/abc/filter_abc.py b/bot/src/bot_graphql/abc/filter_abc.py index e0d5ff8d..3067b075 100644 --- a/bot/src/bot_graphql/abc/filter_abc.py +++ b/bot/src/bot_graphql/abc/filter_abc.py @@ -1,8 +1,10 @@ import functools from abc import ABC, abstractmethod from inspect import signature, Parameter +from typing import Callable from cpl_core.dependency_injection import ServiceProviderABC +from cpl_core.type import R, T from cpl_query.extension import List @@ -52,3 +54,18 @@ class FilterABC(ABC): return f(*args, **kwargs) return decorator + + def _get_attributes_from_dict(self, attrs: list[tuple[str, type]], values: dict): + for key_pair in attrs: + attr = key_pair[0] + attr_type = key_pair[1] + if attr in values: + self.__setattr__(f"_{attr}", attr_type(values[attr])) + + @staticmethod + def _filter_by_attributes(attrs: list[dict], values: List[T]) -> List[R]: + for attr in attrs: + if attr["attr"] is None: + continue + values = values.where(attr["func"]) + return values diff --git a/bot/src/bot_graphql/abc/query_abc.py b/bot/src/bot_graphql/abc/query_abc.py index 506428fc..882a420d 100644 --- a/bot/src/bot_graphql/abc/query_abc.py +++ b/bot/src/bot_graphql/abc/query_abc.py @@ -20,6 +20,7 @@ from bot_data.model.auto_role_rule import AutoRoleRule from bot_data.model.client import Client from bot_data.model.known_user import KnownUser from bot_data.model.level import Level +from bot_data.model.scheduled_event import ScheduledEvent from bot_data.model.server import Server from bot_data.model.server_config import ServerConfig from bot_data.model.short_role_name import ShortRoleName @@ -213,6 +214,16 @@ class QueryABC(ObjectType): access = True break + elif type(element) == ScheduledEvent: + element: ScheduledEvent = element + for u in user.users: + u: User = u + guild = bot.get_guild(u.server.discord_id) + member = guild.get_member(u.discord_id) + if permissions.is_member_moderator(member) and u.server.id == element.server.id: + access = True + break + elif type(element) == dict and "key" in element and element["key"] in [e.value for e in FeatureFlagsEnum]: for u in user.users: u: User = u diff --git a/bot/src/bot_graphql/filter/scheduled_event_filter.py b/bot/src/bot_graphql/filter/scheduled_event_filter.py new file mode 100644 index 00000000..e98be02b --- /dev/null +++ b/bot/src/bot_graphql/filter/scheduled_event_filter.py @@ -0,0 +1,71 @@ +from cpl_core.dependency_injection import ServiceProviderABC +from cpl_discord.service import DiscordBotServiceABC +from cpl_query.extension import List + +from bot_data.model.scheduled_event import ScheduledEvent +from bot_graphql.abc.filter_abc import FilterABC + + +class ScheduledEventFilter(FilterABC): + def __init__(self, bot: DiscordBotServiceABC, services: ServiceProviderABC): + FilterABC.__init__(self) + self._bot = bot + self._services = services + + self._id = None + self._interval = None + self._name = None + self._description = None + self._channel_id = None + self._start_time = None + self._end_time = None + self._entity_type = None + self._location = None + self._server = None + + def from_dict(self, values: dict): + self._get_attributes_from_dict( + [ + ("id", int), + ("interval", str), + ("name", str), + ("description", str), + ("channel_id", str), + ("start_time", str), + ("end_time", str), + ("entity_type", str), + ("location", str), + ], + values, + ) + + if "server" in values: + from bot_graphql.filter.server_filter import ServerFilter + + self._server: ServerFilter = self._services.get_service(ServerFilter) + self._server.from_dict(values["server"]) + + def filter(self, query: List[ScheduledEvent]) -> List[ScheduledEvent]: + if self._id is not None: + query = query.where(lambda x: x.id == self._id) + + query = self._filter_by_attributes( + [ + {"attr": self._id, "func": lambda x: x.id == self._id}, + {"attr": self._interval, "func": lambda x: x.interval == self._interval}, + {"attr": self._name, "func": lambda x: x.name == self._name}, + {"attr": self._description, "func": lambda x: x.description == self._description}, + {"attr": self._channel_id, "func": lambda x: x.channel_id == self._channel_id}, + {"attr": self._start_time, "func": lambda x: x.start_time == self._start_time}, + {"attr": self._end_time, "func": lambda x: x.end_time == self._end_time}, + {"attr": self._entity_type, "func": lambda x: x.entity_type == self._entity_type}, + {"attr": self._location, "func": lambda x: x.location == self._location}, + ], + query, + ) + + if self._server is not None: + servers = self._server.filter(query.select(lambda x: x.server)).select(lambda x: x.id) + query = query.where(lambda x: x.server.id in servers) + + return query diff --git a/bot/src/bot_graphql/filter/short_role_name_filter.py b/bot/src/bot_graphql/filter/short_role_name_filter.py index 426e3630..ea5a8bba 100644 --- a/bot/src/bot_graphql/filter/short_role_name_filter.py +++ b/bot/src/bot_graphql/filter/short_role_name_filter.py @@ -1,3 +1,4 @@ +from cpl_core.dependency_injection import ServiceProviderABC from cpl_discord.service import DiscordBotServiceABC from cpl_query.extension import List @@ -8,9 +9,10 @@ from bot_graphql.abc.filter_abc import FilterABC class ShortRoleNameFilter(FilterABC): - def __init__(self, bot: DiscordBotServiceABC): + def __init__(self, bot: DiscordBotServiceABC, services: ServiceProviderABC): FilterABC.__init__(self) self._bot = bot + self._services = services self._id = None self._short_name = None diff --git a/bot/src/bot_graphql/graphql/mutation.gql b/bot/src/bot_graphql/graphql/mutation.gql index 9578fde0..56d6374f 100644 --- a/bot/src/bot_graphql/graphql/mutation.gql +++ b/bot/src/bot_graphql/graphql/mutation.gql @@ -6,6 +6,7 @@ type Mutation { userJoinedGameServer: UserJoinedGameServerMutation achievement: AchievementMutation shortRoleName: ShortRoleNameMutation + scheduledEvent: ScheduledEventMutation technicianConfig: TechnicianConfigMutation serverConfig: ServerConfigMutation } \ No newline at end of file diff --git a/bot/src/bot_graphql/graphql/query.gql b/bot/src/bot_graphql/graphql/query.gql index ffa3c21f..6892510d 100644 --- a/bot/src/bot_graphql/graphql/query.gql +++ b/bot/src/bot_graphql/graphql/query.gql @@ -41,6 +41,9 @@ type Query { shortRoleNames(filter: ShortRoleNameFilter, page: Page, sort: Sort): [ShortRoleName] shortRoleNamePositions: [String] + scheduledEventCount: Int + scheduledEvents(filter: ScheduledEventFilter, page: Page, sort: Sort): [ScheduledEvent] + userWarningCount: Int userWarnings(filter: UserWarningFilter, page: Page, sort: Sort): [UserWarning] diff --git a/bot/src/bot_graphql/graphql/scheduledEvent.gql b/bot/src/bot_graphql/graphql/scheduledEvent.gql new file mode 100644 index 00000000..586bbc92 --- /dev/null +++ b/bot/src/bot_graphql/graphql/scheduledEvent.gql @@ -0,0 +1,68 @@ +type ScheduledEvent implements TableWithHistoryQuery { + id: ID + interval: String + name: String + description: String + channelId: String + startTime: String + endTime: String + entityType: Int + location: String + + server: Server + + createdAt: String + modifiedAt: String + + history: [ScheduledEventHistory] +} + +type ScheduledEventHistory implements HistoryTableQuery { + id: ID + interval: String + name: String + description: String + channelId: String + startTime: String + endTime: String + entityType: Int + location: String + + server: ID + + deleted: Boolean + dateFrom: String + dateTo: String +} + +input ScheduledEventFilter { + id: ID + interval: String + name: String + description: String + channelId: String + startTime: String + endTime: String + entityType: Int + location: String + server: ServerFilter +} + +type ScheduledEventMutation { + createScheduledEvent(input: ScheduledEventInput!): ScheduledEvent + updateScheduledEvent(input: ScheduledEventInput!): ScheduledEvent + deleteScheduledEvent(id: ID): ScheduledEvent +} + +input ScheduledEventInput { + id: ID + interval: String + name: String + description: String + channelId: String + startTime: String + endTime: String + entityType: Int + location: String + serverId: ID +} \ No newline at end of file diff --git a/bot/src/bot_graphql/graphql/server.gql b/bot/src/bot_graphql/graphql/server.gql index be603f3a..4624ffca 100644 --- a/bot/src/bot_graphql/graphql/server.gql +++ b/bot/src/bot_graphql/graphql/server.gql @@ -35,6 +35,9 @@ type Server implements TableWithHistoryQuery { shortRoleNameCount: Int shortRoleNames(filter: ShortRoleNameFilter, page: Page, sort: Sort): [ShortRoleName] + scheduledEventCount: Int + scheduledEvents(filter: ScheduledEventFilter, page: Page, sort: Sort): [ScheduledEvent] + config: ServerConfig hasFeatureFlag(flag: String): FeatureFlag diff --git a/bot/src/bot_graphql/graphql_module.py b/bot/src/bot_graphql/graphql_module.py index 95d73f7b..21957e56 100644 --- a/bot/src/bot_graphql/graphql_module.py +++ b/bot/src/bot_graphql/graphql_module.py @@ -12,6 +12,7 @@ from bot_graphql.filter.auto_role_filter import AutoRoleFilter from bot_graphql.filter.auto_role_rule_filter import AutoRoleRuleFilter from bot_graphql.filter.client_filter import ClientFilter from bot_graphql.filter.level_filter import LevelFilter +from bot_graphql.filter.scheduled_event_filter import ScheduledEventFilter from bot_graphql.filter.server_filter import ServerFilter from bot_graphql.filter.short_role_name_filter import ShortRoleNameFilter from bot_graphql.filter.user_filter import UserFilter @@ -27,6 +28,7 @@ from bot_graphql.mutations.achievement_mutation import AchievementMutation from bot_graphql.mutations.auto_role_mutation import AutoRoleMutation from bot_graphql.mutations.auto_role_rule_mutation import AutoRoleRuleMutation from bot_graphql.mutations.level_mutation import LevelMutation +from bot_graphql.mutations.scheduled_event_mutation import ScheduledEventMutation from bot_graphql.mutations.server_config_mutation import ServerConfigMutation from bot_graphql.mutations.short_role_name_mutation import ShortRoleNameMutation from bot_graphql.mutations.technician_config_mutation import TechnicianConfigMutation @@ -54,6 +56,7 @@ from bot_graphql.queries.known_user_history_query import KnownUserHistoryQuery from bot_graphql.queries.known_user_query import KnownUserQuery from bot_graphql.queries.level_history_query import LevelHistoryQuery from bot_graphql.queries.level_query import LevelQuery +from bot_graphql.queries.scheduled_event_query import ScheduledEventQuery from bot_graphql.queries.server_config_query import ServerConfigQuery from bot_graphql.queries.server_history_query import ServerHistoryQuery from bot_graphql.queries.server_query import ServerQuery @@ -140,6 +143,7 @@ class GraphQLModule(ModuleABC): services.add_transient(QueryABC, UserWarningHistoryQuery) services.add_transient(QueryABC, UserWarningQuery) services.add_transient(QueryABC, ServerStatisticQuery) + services.add_transient(QueryABC, ScheduledEventQuery) services.add_transient(QueryABC, DiscordQuery) services.add_transient(QueryABC, GuildQuery) @@ -161,6 +165,7 @@ class GraphQLModule(ModuleABC): services.add_transient(FilterABC, UserJoinedGameServerFilter) services.add_transient(FilterABC, ShortRoleNameFilter) services.add_transient(FilterABC, UserWarningFilter) + services.add_transient(FilterABC, ScheduledEventFilter) # mutations services.add_transient(QueryABC, AutoRoleMutation) @@ -172,3 +177,4 @@ class GraphQLModule(ModuleABC): services.add_transient(QueryABC, UserJoinedGameServerMutation) services.add_transient(QueryABC, TechnicianConfigMutation) services.add_transient(QueryABC, ServerConfigMutation) + services.add_transient(QueryABC, ScheduledEventMutation) diff --git a/bot/src/bot_graphql/mutation.py b/bot/src/bot_graphql/mutation.py index 39e38cc5..86b269d0 100644 --- a/bot/src/bot_graphql/mutation.py +++ b/bot/src/bot_graphql/mutation.py @@ -4,6 +4,7 @@ from bot_graphql.mutations.achievement_mutation import AchievementMutation from bot_graphql.mutations.auto_role_mutation import AutoRoleMutation from bot_graphql.mutations.auto_role_rule_mutation import AutoRoleRuleMutation from bot_graphql.mutations.level_mutation import LevelMutation +from bot_graphql.mutations.scheduled_event_mutation import ScheduledEventMutation from bot_graphql.mutations.server_config_mutation import ServerConfigMutation from bot_graphql.mutations.short_role_name_mutation import ShortRoleNameMutation from bot_graphql.mutations.technician_config_mutation import TechnicianConfigMutation @@ -23,6 +24,7 @@ class Mutation(MutationType): achievement_mutation: AchievementMutation, user_joined_game_server: UserJoinedGameServerMutation, technician_config: TechnicianConfigMutation, + scheduled_event: ScheduledEventMutation, server_config: ServerConfigMutation, short_role_name_mutation: ShortRoleNameMutation, ): @@ -36,4 +38,5 @@ class Mutation(MutationType): self.set_field("userJoinedGameServer", lambda *_: user_joined_game_server) self.set_field("shortRoleName", lambda *_: short_role_name_mutation) self.set_field("technicianConfig", lambda *_: technician_config) + self.set_field("scheduledEvent", lambda *_: scheduled_event) self.set_field("serverConfig", lambda *_: server_config) diff --git a/bot/src/bot_graphql/mutations/scheduled_event_mutation.py b/bot/src/bot_graphql/mutations/scheduled_event_mutation.py new file mode 100644 index 00000000..c3e2dbbc --- /dev/null +++ b/bot/src/bot_graphql/mutations/scheduled_event_mutation.py @@ -0,0 +1,107 @@ +from datetime import datetime + +from cpl_core.database.context import DatabaseContextABC +from cpl_discord.service import DiscordBotServiceABC +from discord import EntityType + +from bot_data.abc.server_repository_abc import ServerRepositoryABC +from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC +from bot_data.model.scheduled_event import ScheduledEvent +from bot_data.model.scheduled_event_interval_enum import ScheduledEventIntervalEnum +from bot_data.model.user_role_enum import UserRoleEnum +from bot_graphql.abc.query_abc import QueryABC +from modules.permission.service.permission_service import PermissionService + + +class ScheduledEventMutation(QueryABC): + def __init__( + self, + servers: ServerRepositoryABC, + scheduled_events: ScheduledEventRepositoryABC, + bot: DiscordBotServiceABC, + db: DatabaseContextABC, + permissions: PermissionService, + ): + QueryABC.__init__(self, "ScheduledEventMutation") + + self._servers = servers + self._scheduled_events = scheduled_events + self._bot = bot + self._db = db + self._permissions = permissions + + self.set_field("createScheduledEvent", self.resolve_create_scheduled_event) + self.set_field("updateScheduledEvent", self.resolve_update_scheduled_event) + self.set_field("deleteScheduledEvent", self.resolve_delete_scheduled_event) + + def resolve_create_scheduled_event(self, *_, input: dict): + server = self._servers.get_server_by_id(input["serverId"]) + self._can_user_mutate_data(server, UserRoleEnum.moderator) + + scheduled_event = ScheduledEvent( + ScheduledEventIntervalEnum(input["interval"]), + input["name"], + input["description"] if "description" in input else None, + input["channelId"] if "channelId" in input else None, + datetime.strptime(input["startTime"], "%Y-%m-%dT%H:%M:%S.%fZ"), + datetime.strptime(input["endTime"], "%Y-%m-%dT%H:%M:%S.%fZ") if "endTime" in input else None, + input["entityType"], + input["location"] if "location" in input else None, + server, + ) + + self._scheduled_events.add_scheduled_event(scheduled_event) + self._db.save_changes() + + def get_new_scheduled_event(srn: ScheduledEvent): + return ( + srn.interval == scheduled_event.interval + and srn.name == scheduled_event.name + and srn.description == scheduled_event.description + ) + + return ( + self._scheduled_events.get_scheduled_events_by_server_id(scheduled_event.server.id) + .where(get_new_scheduled_event) + .last() + ) + + def resolve_update_scheduled_event(self, *_, input: dict): + scheduled_event = self._scheduled_events.get_scheduled_event_by_id(input["id"]) + self._can_user_mutate_data(scheduled_event.server, UserRoleEnum.moderator) + + scheduled_event.interval = ( + ScheduledEventIntervalEnum(input["interval"]) if "interval" in input else scheduled_event.interval + ) + scheduled_event.name = input["name"] if "name" in input else scheduled_event.name + scheduled_event.description = input["description"] if "description" in input else scheduled_event.description + scheduled_event.channel_id = input["channelId"] if "channelId" in input else scheduled_event.channel_id + scheduled_event.start_time = ( + datetime.strptime(input["startTime"], "%Y-%m-%dT%H:%M:%S.%fZ") + if "startTime" in input + else scheduled_event.start_time + ) + scheduled_event.end_time = ( + datetime.strptime(input["endTime"], "%Y-%m-%dT%H:%M:%S.%fZ") + if "endTime" in input + else scheduled_event.end_time + ) + scheduled_event.entity_type = ( + EntityType(int(input["entityType"])) if "entityType" in input else scheduled_event.entity_type + ) + scheduled_event.location = input["location"] if "location" in input else scheduled_event.location + + self._scheduled_events.update_scheduled_event(scheduled_event) + self._db.save_changes() + + scheduled_event = self._scheduled_events.get_scheduled_event_by_id(input["id"]) + return scheduled_event + + def resolve_delete_scheduled_event(self, *_, id: int): + scheduled_event = self._scheduled_events.get_scheduled_event_by_id(id) + self._can_user_mutate_data(scheduled_event.server, UserRoleEnum.admin) + + self._scheduled_events.delete_scheduled_event(scheduled_event) + self._db.save_changes() + + return scheduled_event diff --git a/bot/src/bot_graphql/queries/scheduled_event_history_query.py b/bot/src/bot_graphql/queries/scheduled_event_history_query.py new file mode 100644 index 00000000..f8fe921a --- /dev/null +++ b/bot/src/bot_graphql/queries/scheduled_event_history_query.py @@ -0,0 +1,24 @@ +from cpl_core.database.context import DatabaseContextABC + +from bot_data.model.scheduled_event_history import ScheduledEventHistory +from bot_graphql.abc.data_query_with_history_abc import DataQueryWithHistoryABC + + +class ScheduledEventHistoryQuery(DataQueryWithHistoryABC): + def __init__( + self, + db: DatabaseContextABC, + ): + DataQueryWithHistoryABC.__init__(self, "ScheduledEvent", "ScheduledEventsHistory", ScheduledEventHistory, db) + + self.set_field("id", lambda x, *_: x.id) + self.set_field("id", lambda x, *_: x.id) + self.set_field("interval", lambda x, *_: x.interval.value) + self.set_field("name", lambda x, *_: x.name) + self.set_field("description", lambda x, *_: x.description) + self.set_field("channel_id", lambda x, *_: x.channel_id) + self.set_field("start_time", lambda x, *_: x.start_time) + self.set_field("end_time", lambda x, *_: x.end_time) + self.set_field("entity_type", lambda x, *_: x.entity_type) + self.set_field("location", lambda x, *_: x.location) + self.set_field("server", lambda x, *_: x.server) diff --git a/bot/src/bot_graphql/queries/scheduled_event_query.py b/bot/src/bot_graphql/queries/scheduled_event_query.py new file mode 100644 index 00000000..d7a986be --- /dev/null +++ b/bot/src/bot_graphql/queries/scheduled_event_query.py @@ -0,0 +1,23 @@ +from cpl_core.database.context import DatabaseContextABC + +from bot_data.model.scheduled_event_history import ScheduledEventHistory +from bot_graphql.abc.data_query_with_history_abc import DataQueryWithHistoryABC + + +class ScheduledEventQuery(DataQueryWithHistoryABC): + def __init__( + self, + db: DatabaseContextABC, + ): + DataQueryWithHistoryABC.__init__(self, "ScheduledEvent", "ScheduledEventsHistory", ScheduledEventHistory, db) + + self.set_field("id", lambda x, *_: x.id) + self.set_field("interval", lambda x, *_: x.interval.value) + self.set_field("name", lambda x, *_: x.name) + self.set_field("description", lambda x, *_: x.description) + self.set_field("channelId", lambda x, *_: x.channel_id) + self.set_field("startTime", lambda x, *_: x.start_time) + self.set_field("endTime", lambda x, *_: x.end_time) + self.set_field("entityType", lambda x, *_: x.entity_type.value) + self.set_field("location", lambda x, *_: x.location) + self.set_field("server", lambda x, *_: x.server) diff --git a/bot/src/bot_graphql/queries/server_query.py b/bot/src/bot_graphql/queries/server_query.py index 14033101..3760db07 100644 --- a/bot/src/bot_graphql/queries/server_query.py +++ b/bot/src/bot_graphql/queries/server_query.py @@ -9,6 +9,7 @@ from bot_data.abc.auto_role_repository_abc import AutoRoleRepositoryABC from bot_data.abc.client_repository_abc import ClientRepositoryABC from bot_data.abc.game_server_repository_abc import GameServerRepositoryABC from bot_data.abc.level_repository_abc import LevelRepositoryABC +from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC from bot_data.abc.server_config_repository_abc import ServerConfigRepositoryABC from bot_data.abc.short_role_name_repository_abc import ShortRoleNameRepositoryABC from bot_data.abc.user_joined_server_repository_abc import UserJoinedServerRepositoryABC @@ -24,6 +25,7 @@ from bot_graphql.filter.achievement_filter import AchievementFilter from bot_graphql.filter.auto_role_filter import AutoRoleFilter from bot_graphql.filter.client_filter import ClientFilter from bot_graphql.filter.level_filter import LevelFilter +from bot_graphql.filter.scheduled_event_filter import ScheduledEventFilter from bot_graphql.filter.short_role_name_filter import ShortRoleNameFilter from bot_graphql.filter.user_filter import UserFilter from bot_graphql.model.server_statistics import ServerStatistics @@ -44,6 +46,7 @@ class ServerQuery(DataQueryWithHistoryABC): ujvs: UserJoinedVoiceChannelRepositoryABC, achievements: AchievementRepositoryABC, short_role_names: ShortRoleNameRepositoryABC, + scheduled_events: ScheduledEventRepositoryABC, server_configs: ServerConfigRepositoryABC, ): DataQueryWithHistoryABC.__init__(self, "Server", "ServersHistory", ServerHistory, db) @@ -100,6 +103,11 @@ class ServerQuery(DataQueryWithHistoryABC): lambda server, *_: short_role_names.get_short_role_names_by_server_id(server.id), ShortRoleNameFilter, ) + self.add_collection( + "scheduledEvent", + lambda server, *_: scheduled_events.get_scheduled_events_by_server_id(server.id), + ScheduledEventFilter, + ) self.set_field( "config", lambda server, *_: server_configs.get_server_config_by_server(server.id), diff --git a/bot/src/bot_graphql/query.py b/bot/src/bot_graphql/query.py index 41dafdf0..154079d9 100644 --- a/bot/src/bot_graphql/query.py +++ b/bot/src/bot_graphql/query.py @@ -8,6 +8,7 @@ from bot_data.abc.client_repository_abc import ClientRepositoryABC from bot_data.abc.game_server_repository_abc import GameServerRepositoryABC from bot_data.abc.known_user_repository_abc import KnownUserRepositoryABC from bot_data.abc.level_repository_abc import LevelRepositoryABC +from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC from bot_data.abc.server_repository_abc import ServerRepositoryABC from bot_data.abc.short_role_name_repository_abc import ShortRoleNameRepositoryABC from bot_data.abc.technician_config_repository_abc import TechnicianConfigRepositoryABC @@ -27,6 +28,7 @@ from bot_graphql.filter.auto_role_filter import AutoRoleFilter from bot_graphql.filter.auto_role_rule_filter import AutoRoleRuleFilter from bot_graphql.filter.client_filter import ClientFilter from bot_graphql.filter.level_filter import LevelFilter +from bot_graphql.filter.scheduled_event_filter import ScheduledEventFilter from bot_graphql.filter.server_filter import ServerFilter from bot_graphql.filter.short_role_name_filter import ShortRoleNameFilter from bot_graphql.filter.user_filter import UserFilter @@ -59,6 +61,7 @@ class Query(QueryABC): user_warnings: UserWarningsRepositoryABC, achievement_service: AchievementService, technician_config: TechnicianConfigRepositoryABC, + scheduled_events: ScheduledEventRepositoryABC, ): QueryABC.__init__(self, "Query") @@ -95,6 +98,11 @@ class Query(QueryABC): lambda *_: short_role_names.get_short_role_names(), ShortRoleNameFilter, ) + self.add_collection( + "scheduledEvent", + lambda server, *_: scheduled_events.get_scheduled_events_by_server_id(server.id), + ScheduledEventFilter, + ) self.add_collection( "userWarning", lambda *_: user_warnings.get_user_warnings(), diff --git a/bot/src/modules/achievements/achievements.json b/bot/src/modules/achievements/achievements.json index acea20a4..911cf740 100644 --- a/bot/src/modules/achievements/achievements.json +++ b/bot/src/modules/achievements/achievements.json @@ -16,10 +16,10 @@ "LicenseName": "MIT", "LicenseDescription": "MIT, see LICENSE for more details.", "Dependencies": [ - "cpl-core>=1.2.1" + "cpl-core>=1.2.dev410" ], "DevDependencies": [ - "cpl-cli>=1.2.1" + "cpl-cli>=1.2.dev410" ], "PythonVersion": ">=3.10.4", "PythonPath": {}, diff --git a/bot/src/modules/base/base_module.py b/bot/src/modules/base/base_module.py index fc04e55e..b0608515 100644 --- a/bot/src/modules/base/base_module.py +++ b/bot/src/modules/base/base_module.py @@ -7,7 +7,7 @@ from cpl_discord.service.discord_collection_abc import DiscordCollectionABC from bot_core.abc.module_abc import ModuleABC from bot_core.abc.task_abc import TaskABC from bot_core.configuration.feature_flags_enum import FeatureFlagsEnum -from modules.base.birthday_watcher import BirthdayWatcher +from modules.base.tasks.birthday_watcher import BirthdayWatcher from modules.base.command.afk_command import AFKCommand from modules.base.command.game_server_group import GameServerGroup from modules.base.command.help_command import HelpCommand @@ -45,6 +45,7 @@ from modules.base.events.base_on_voice_state_update_event_scheduled_event_bonus from modules.base.forms.bug_report_form import BugReportForm from modules.base.forms.complaint_form import ComplaintForm from modules.base.helper.base_reaction_handler import BaseReactionHandler +from modules.base.tasks.scheduled_events_watcher import ScheduledEventsWatcher from modules.base.service.event_service import EventService from modules.base.service.user_warnings_service import UserWarningsService @@ -61,6 +62,7 @@ class BaseModule(ModuleABC): services.add_singleton(EventService) services.add_transient(UserWarningsService) services.add_singleton(TaskABC, BirthdayWatcher) + services.add_singleton(TaskABC, ScheduledEventsWatcher) # forms services.add_transient(BugReportForm) diff --git a/bot/src/modules/base/tasks/__init__.py b/bot/src/modules/base/tasks/__init__.py new file mode 100644 index 00000000..41959bff --- /dev/null +++ b/bot/src/modules/base/tasks/__init__.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- + +""" +bot sh-edraft.de Discord bot +~~~~~~~~~~~~~~~~~~~ + +Discord bot for customers of sh-edraft.de + +:copyright: (c) 2022 - 2023 sh-edraft.de +:license: MIT, see LICENSE for more details. + +""" + +__title__ = "modules.base.tasks" +__author__ = "Sven Heidemann" +__license__ = "MIT" +__copyright__ = "Copyright (c) 2022 - 2023 sh-edraft.de" +__version__ = "1.2.2" + +from collections import namedtuple + + +# imports: + +VersionInfo = namedtuple("VersionInfo", "major minor micro") +version_info = VersionInfo(major="1", minor="2", micro="2") diff --git a/bot/src/modules/base/birthday_watcher.py b/bot/src/modules/base/tasks/birthday_watcher.py similarity index 100% rename from bot/src/modules/base/birthday_watcher.py rename to bot/src/modules/base/tasks/birthday_watcher.py diff --git a/bot/src/modules/base/tasks/scheduled_events_watcher.py b/bot/src/modules/base/tasks/scheduled_events_watcher.py new file mode 100644 index 00000000..0c6738cb --- /dev/null +++ b/bot/src/modules/base/tasks/scheduled_events_watcher.py @@ -0,0 +1,126 @@ +import calendar +from datetime import datetime, timedelta +from zoneinfo import ZoneInfo + +from cpl_core.configuration import ConfigurationABC +from cpl_core.database.context import DatabaseContextABC +from cpl_discord.service import DiscordBotServiceABC +from cpl_query.extension import List +from cpl_translation import TranslatePipe +from discord import Guild, PrivacyLevel +from discord.ext import tasks +from discord.scheduled_event import ScheduledEvent as DiscordEvent + +from bot_core.abc.task_abc import TaskABC +from bot_core.logging.task_logger import TaskLogger +from bot_core.service.message_service import MessageService +from bot_data.abc.scheduled_event_repository_abc import ScheduledEventRepositoryABC +from bot_data.abc.server_repository_abc import ServerRepositoryABC +from bot_data.model.scheduled_event import ScheduledEvent +from bot_data.model.scheduled_event_interval_enum import ScheduledEventIntervalEnum + + +class ScheduledEventsWatcher(TaskABC): + def __init__( + self, + config: ConfigurationABC, + logger: TaskLogger, + bot: DiscordBotServiceABC, + db: DatabaseContextABC, + servers: ServerRepositoryABC, + events: ScheduledEventRepositoryABC, + message_service: MessageService, + t: TranslatePipe, + ): + TaskABC.__init__(self) + + self._config = config + self._logger = logger + self._bot = bot + self._db = db + self._servers = servers + self._events = events + self._message_service = message_service + self._t = t + + if not self._is_maintenance(): + self.watch.start() + + def _append_interval(self, interval: ScheduledEventIntervalEnum, ts: datetime) -> datetime: + now = datetime.now() + if ts >= now: + return ts + + if interval == ScheduledEventIntervalEnum.daily: + ts = ts + timedelta(days=1) + + elif interval == ScheduledEventIntervalEnum.weekly: + ts = ts + timedelta(weeks=1) + + elif interval == ScheduledEventIntervalEnum.monthly: + days_in_month = calendar.monthrange(ts.year, ts.month + 1)[1] + ts = ts + timedelta(days=days_in_month) + + elif interval == ScheduledEventIntervalEnum.yearly: + ts = ts + timedelta(days=365) + + return ts + + @tasks.loop(hours=24) + async def watch(self): + self._logger.info(__name__, "Watching scheduled events") + try: + for guild in self._bot.guilds: + guild: Guild = guild + server = self._servers.get_server_by_discord_id(guild.id) + scheduled_events_from_guild = self._events.get_scheduled_events_by_server_id(server.id) + for scheduled_event in scheduled_events_from_guild: + scheduled_event: ScheduledEvent = scheduled_event + from_guild = List(DiscordEvent, guild.scheduled_events).where( + lambda x: x.name == scheduled_event.name + and x.description == scheduled_event.description + and x.entity_type == scheduled_event.entity_type + ) + if from_guild.count() != 0: + continue + + kwargs = {"name": scheduled_event.name, "description": scheduled_event.description} + + if scheduled_event.channel_id is not None: + kwargs["channel"] = guild.get_channel(scheduled_event.channel_id) + + if scheduled_event.start_time is not None: + scheduled_event.start_time = self._append_interval( + scheduled_event.interval, scheduled_event.start_time + ) + + start_time = scheduled_event.start_time.replace(tzinfo=ZoneInfo("Europe/Berlin")) + + kwargs["start_time"] = start_time + + if scheduled_event.end_time is not None: + scheduled_event.end_time = self._append_interval( + scheduled_event.interval, scheduled_event.end_time + ) + end_time = scheduled_event.end_time.replace(tzinfo=ZoneInfo("Europe/Berlin")) + kwargs["end_time"] = end_time + + kwargs["entity_type"] = scheduled_event.entity_type + if scheduled_event.location is not None: + kwargs["location"] = scheduled_event.location + + kwargs["privacy_level"] = PrivacyLevel.guild_only + + try: + self._logger.debug(__name__, f"Try to create scheduled event for guild {guild.name}") + await guild.create_scheduled_event(**kwargs) + self._events.update_scheduled_event(scheduled_event) + self._db.save_changes() + except Exception as e: + self._logger.error(__name__, f"Watching scheduled events failed", e) + except Exception as e: + self._logger.error(__name__, f"Watching scheduled events failed", e) + + @watch.before_loop + async def wait(self): + await self._wait_until_ready() diff --git a/bot/src/modules/config/config.json b/bot/src/modules/config/config.json index 301f4630..6a80a8c4 100644 --- a/bot/src/modules/config/config.json +++ b/bot/src/modules/config/config.json @@ -16,10 +16,10 @@ "LicenseName": "", "LicenseDescription": "", "Dependencies": [ - "cpl-core>=1.2.1" + "cpl-core>=1.2.dev410" ], "DevDependencies": [ - "cpl-cli>=1.2.1" + "cpl-cli>=1.2.dev410" ], "PythonVersion": ">=3.10.4", "PythonPath": { diff --git a/bot/src/modules/short_role_name/short-role-name.json b/bot/src/modules/short_role_name/short-role-name.json index 57329ee1..23b81e41 100644 --- a/bot/src/modules/short_role_name/short-role-name.json +++ b/bot/src/modules/short_role_name/short-role-name.json @@ -16,10 +16,10 @@ "LicenseName": "", "LicenseDescription": "", "Dependencies": [ - "cpl-core>=1.2.1" + "cpl-core>=1.2.dev410" ], "DevDependencies": [ - "cpl-cli>=1.2.1" + "cpl-cli>=1.2.dev410" ], "PythonVersion": ">=3.10.4", "PythonPath": { diff --git a/bot/src/modules/special_offers/special-offers.json b/bot/src/modules/special_offers/special-offers.json index 8def3776..cd6b44b1 100644 --- a/bot/src/modules/special_offers/special-offers.json +++ b/bot/src/modules/special_offers/special-offers.json @@ -16,10 +16,10 @@ "LicenseName": "", "LicenseDescription": "", "Dependencies": [ - "cpl-core>=1.2.1" + "cpl-core>=1.2.dev410" ], "DevDependencies": [ - "cpl-cli>=1.2.1" + "cpl-cli>=1.2.dev410" ], "PythonVersion": ">=3.10.4", "PythonPath": { diff --git a/bot/tools/migration_to_sql/migration-to-sql.json b/bot/tools/migration_to_sql/migration-to-sql.json index 5e4a62f8..6be85895 100644 --- a/bot/tools/migration_to_sql/migration-to-sql.json +++ b/bot/tools/migration_to_sql/migration-to-sql.json @@ -2,9 +2,9 @@ "ProjectSettings": { "Name": "migration-to-sql", "Version": { - "Major": "0", - "Minor": "0", - "Micro": "0" + "Major": "1", + "Minor": "2", + "Micro": "2" }, "Author": "", "AuthorEmail": "", @@ -16,10 +16,10 @@ "LicenseName": "", "LicenseDescription": "", "Dependencies": [ - "cpl-core>=2023.10.0" + "cpl-core>=1.2.dev410" ], "DevDependencies": [ - "cpl-cli>=2023.4.0.post3" + "cpl-cli>=1.2.dev410" ], "PythonVersion": ">=3.10.4", "PythonPath": { diff --git a/web/package.json b/web/package.json index 3255abc5..281eca54 100644 --- a/web/package.json +++ b/web/package.json @@ -1,56 +1,56 @@ { - "name": "web", - "version": "1.2.2", - "scripts": { - "ng": "ng", - "update-version": "ts-node update-version.ts", - "prestart": "npm run update-version", - "start": "ng serve", - "prebuild": "npm run update-version", - "build": "ng build", - "watch": "ng build --watch --configuration development", - "test": "ng test", - "gv": "echo $npm_package_version", - "predocker-build": "npm run update-version", - "docker-build": "export VERSION=$npm_package_version; ng build; docker build -t sh-edraft.de/sdb-web:$VERSION .", - "docker-build-dev": "export VERSION=$npm_package_version; ng build --configuration development; docker build -t sh-edraft.de/sdb-web:$VERSION .", - "docker-build-stage": "export VERSION=$npm_package_version; ng build --configuration staging; docker build -t sh-edraft.de/sdb-web:$VERSION ." - }, - "private": true, - "dependencies": { - "@angular/animations": "^15.1.4", - "@angular/common": "^15.1.4", - "@angular/compiler": "^15.1.4", - "@angular/core": "^15.1.4", - "@angular/forms": "^15.1.4", - "@angular/platform-browser": "^15.1.4", - "@angular/platform-browser-dynamic": "^15.1.4", - "@angular/router": "^15.1.4", - "@auth0/angular-jwt": "^5.1.0", - "@microsoft/signalr": "^6.0.9", - "@ngx-translate/core": "^14.0.0", - "@ngx-translate/http-loader": "^7.0.0", - "@types/socket.io-client": "^3.0.0", - "moment": "^2.29.4", - "primeicons": "^6.0.1", - "primeng": "^15.2.0", - "rxjs": "~7.5.0", - "socket.io-client": "^4.5.3", - "zone.js": "~0.11.4" - }, - "devDependencies": { - "@angular-devkit/build-angular": "^15.1.5", - "@angular/cli": "~15.1.5", - "@angular/compiler-cli": "^15.1.4", - "@types/jasmine": "~4.0.0", - "@types/node": "^18.11.9", - "jasmine-core": "~4.1.0", - "karma": "~6.3.0", - "karma-chrome-launcher": "~3.1.0", - "karma-coverage": "~2.2.0", - "karma-jasmine": "~5.0.0", - "karma-jasmine-html-reporter": "~1.7.0", - "tslib": "^2.4.1", - "typescript": "~4.9.5" - } -} + "name": "web", + "version": "1.2.dev410", + "scripts": { + "ng": "ng", + "update-version": "ts-node update-version.ts", + "prestart": "npm run update-version", + "start": "ng serve", + "prebuild": "npm run update-version", + "build": "ng build", + "watch": "ng build --watch --configuration development", + "test": "ng test", + "gv": "echo $npm_package_version", + "predocker-build": "npm run update-version", + "docker-build": "export VERSION=$npm_package_version; ng build; docker build -t sh-edraft.de/sdb-web:$VERSION .", + "docker-build-dev": "export VERSION=$npm_package_version; ng build --configuration development; docker build -t sh-edraft.de/sdb-web:$VERSION .", + "docker-build-stage": "export VERSION=$npm_package_version; ng build --configuration staging; docker build -t sh-edraft.de/sdb-web:$VERSION ." + }, + "private": true, + "dependencies": { + "@angular/animations": "^15.1.4", + "@angular/common": "^15.1.4", + "@angular/compiler": "^15.1.4", + "@angular/core": "^15.1.4", + "@angular/forms": "^15.1.4", + "@angular/platform-browser": "^15.1.4", + "@angular/platform-browser-dynamic": "^15.1.4", + "@angular/router": "^15.1.4", + "@auth0/angular-jwt": "^5.1.0", + "@microsoft/signalr": "^6.0.9", + "@ngx-translate/core": "^14.0.0", + "@ngx-translate/http-loader": "^7.0.0", + "@types/socket.io-client": "^3.0.0", + "moment": "^2.29.4", + "primeicons": "^6.0.1", + "primeng": "^15.2.0", + "rxjs": "~7.5.0", + "socket.io-client": "^4.5.3", + "zone.js": "~0.11.4" + }, + "devDependencies": { + "@angular-devkit/build-angular": "^15.1.5", + "@angular/cli": "~15.1.5", + "@angular/compiler-cli": "^15.1.4", + "@types/jasmine": "~4.0.0", + "@types/node": "^18.11.9", + "jasmine-core": "~4.1.0", + "karma": "~6.3.0", + "karma-chrome-launcher": "~3.1.0", + "karma-coverage": "~2.2.0", + "karma-jasmine": "~5.0.0", + "karma-jasmine-html-reporter": "~1.7.0", + "tslib": "^2.4.1", + "typescript": "~4.9.5" + } +} \ No newline at end of file diff --git a/web/src/app/models/data/discord.model.ts b/web/src/app/models/data/discord.model.ts index 6e640052..a77de21e 100644 --- a/web/src/app/models/data/discord.model.ts +++ b/web/src/app/models/data/discord.model.ts @@ -1,4 +1,4 @@ -export interface Discord { +export interface Discord { guilds?: Guild[]; users?: DiscordUser[]; } @@ -21,7 +21,8 @@ export interface Channel { export enum ChannelType { category = "CategoryChannel", text = "TextChannel", - voice = "VoiceChannel" + voice = "VoiceChannel", + stage = "StageChannel" } export interface Role { diff --git a/web/src/app/models/data/scheduled_events.model.ts b/web/src/app/models/data/scheduled_events.model.ts new file mode 100644 index 00000000..e94db4b5 --- /dev/null +++ b/web/src/app/models/data/scheduled_events.model.ts @@ -0,0 +1,43 @@ +import { DataWithHistory } from "./data.model"; +import { Server, ServerFilter } from "./server.model"; + +export enum EventType { + stageInstance = 1, + voice = 2, + external = 3, +} + +export interface ScheduledEvent extends DataWithHistory { + id?: number; + interval?: ScheduledEventInterval; + name?: string; + description?: string; + channelId?: string; + startTime?: Date; + endTime?: Date; + entityType?: EventType; + location?: string; + server?: Server; +} + +export interface ScheduledEventFilter { + id?: number; + interval?: string; + name?: string; + description?: string; + channelId?: string; + startTime?: string; + endTime?: string; + entityType?: number; + location?: string; + server?: ServerFilter; +} + +// export enum ScheduledEventInterval { +// daily = "daily", +// weekly = "weekly", +// monthly = "monthly", +// yearly = "yearly" +// } + +export type ScheduledEventInterval = "daily" | "weekly" | "monthly" | "month" diff --git a/web/src/app/models/graphql/mutations.model.ts b/web/src/app/models/graphql/mutations.model.ts index 4f52fa01..bdac7b0c 100644 --- a/web/src/app/models/graphql/mutations.model.ts +++ b/web/src/app/models/graphql/mutations.model.ts @@ -173,6 +173,78 @@ export class Mutations { } `; + static createScheduledEvent = ` + mutation createScheduledEvent($interval: String,$name: String,$description: String,$channelId: String,$startTime: String, $endTime: String,$entityType: Int,$location: String, $serverId: ID) { + scheduledEvent { + createScheduledEvent(input: { + interval: $interval, + name: $name, + description: $description, + channelId: $channelId, + startTime: $startTime, + endTime: $endTime, + entityType: $entityType, + location: $location, + serverId: $serverId + }) { + interval + name + description + channelId + startTime + endTime + entityType + location + server { + id + } + } + } + } + `; + + static updateScheduledEvent = ` + mutation updateScheduledEvent($id: ID, $interval: String,$name: String,$description: String,$channelId: String,$startTime: String, $endTime: String,$entityType: Int,$location: String, $serverId: ID) { + scheduledEvent { + updateScheduledEvent(input: { + id: $id, + interval: $interval, + name: $name, + description: $description, + channelId: $channelId, + startTime: $startTime, + endTime: $endTime, + entityType: $entityType, + location: $location, + serverId: $serverId} + ) { + interval + name + description + channelId + startTime + endTime + entityType + location + server { + id + } + } + } + } + `; + + static deleteScheduledEvent = ` + mutation deleteScheduledEvent($id: ID) { + scheduledEvent { + deleteScheduledEvent(id: $id) { + id + name + } + } + } + `; + static createShortRoleName = ` mutation createShortRoleName($shortName: String, $roleId: String, $position: String, $serverId: ID) { shortRoleName { @@ -333,7 +405,6 @@ export class Mutations { `; - static createUserWarning = ` mutation createUserWarning($name: String, $description: String, $attribute: String, $operator: String, $value: String, $serverId: ID) { userWarning { diff --git a/web/src/app/models/graphql/queries.model.ts b/web/src/app/models/graphql/queries.model.ts index e44e3aab..1365d76e 100644 --- a/web/src/app/models/graphql/queries.model.ts +++ b/web/src/app/models/graphql/queries.model.ts @@ -229,6 +229,58 @@ export class Queries { } `; + static scheduledEventQuery = ` + query ScheduledEventList($serverId: ID, $filter: ScheduledEventFilter, $page: Page, $sort: Sort) { + servers(filter: {id: $serverId}) { + scheduledEventCount + scheduledEvents(filter: $filter, page: $page, sort: $sort) { + id + interval + name + description + channelId + startTime + endTime + entityType + location + server { + id + name + } + createdAt + modifiedAt + } + } + } + `; + + static scheduledEventWithHistoryQuery = ` + query ScheduledEventHistory($serverId: ID, $id: ID) { + servers(filter: {id: $serverId}) { + scheduledEventCount + scheduledEvents(filter: {id: $id}) { + id + + history { + id + interval + name + description + channelId + startTime + endTime + entityType + location + server + deleted + dateFrom + dateTo + } + } + } + } + `; + static shortRoleNamePositionsQuery = ` query { diff --git a/web/src/app/models/graphql/query.model.ts b/web/src/app/models/graphql/query.model.ts index f98f9a4a..b7da6553 100644 --- a/web/src/app/models/graphql/query.model.ts +++ b/web/src/app/models/graphql/query.model.ts @@ -9,6 +9,7 @@ import { ServerConfig } from "../config/server-config.model"; import { ShortRoleName } from "../data/short_role_name.model"; import { FeatureFlag } from "../config/feature-flags.model"; import { UserWarning } from "../data/user_warning.model"; +import { ScheduledEvent } from "../data/scheduled_events.model"; export interface Query { serverCount: number; @@ -57,6 +58,11 @@ export interface AchievementListQuery { achievements: Achievement[]; } +export interface ScheduledEventListQuery { + scheduledEventCount: number; + scheduledEvents: ScheduledEvent[]; +} + export interface AutoRoleQuery { autoRoleCount: number; autoRoles: AutoRole[]; diff --git a/web/src/app/models/graphql/result.model.ts b/web/src/app/models/graphql/result.model.ts index 411d6f1d..2b9844a7 100644 --- a/web/src/app/models/graphql/result.model.ts +++ b/web/src/app/models/graphql/result.model.ts @@ -7,6 +7,7 @@ import { TechnicianConfig } from "../config/technician-config.model"; import { ServerConfig } from "../config/server-config.model"; import { ShortRoleName } from "../data/short_role_name.model"; import { UserWarning } from "../data/user_warning.model"; +import { ScheduledEvent } from "../data/scheduled_events.model"; export interface GraphQLResult { data: { @@ -71,6 +72,14 @@ export interface AchievementMutationResult { }; } +export interface ScheduledEventMutationResult { + scheduledEvent: { + createScheduledEvent?: ScheduledEvent + updateScheduledEvent?: ScheduledEvent + deleteScheduledEvent?: ScheduledEvent + }; +} + export interface ShortRoleNameMutationResult { shortRoleName: { createShortRoleName?: ShortRoleName diff --git a/web/src/app/modules/shared/shared.module.ts b/web/src/app/modules/shared/shared.module.ts index b3ca8e60..af9e8ea8 100644 --- a/web/src/app/modules/shared/shared.module.ts +++ b/web/src/app/modules/shared/shared.module.ts @@ -1,4 +1,4 @@ -import { CommonModule } from "@angular/common"; +import { CommonModule, DatePipe } from "@angular/common"; import { HttpClientModule } from "@angular/common/http"; import { NgModule } from "@angular/core"; import { FormsModule, ReactiveFormsModule } from "@angular/forms"; @@ -13,7 +13,7 @@ import { InputTextModule } from "primeng/inputtext"; import { MenuModule } from "primeng/menu"; import { PasswordModule } from "primeng/password"; import { ProgressSpinnerModule } from "primeng/progressspinner"; -import { SortableColumn, TableModule } from "primeng/table"; +import { TableModule } from "primeng/table"; import { ToastModule } from "primeng/toast"; import { AuthRolePipe } from "./pipes/auth-role.pipe"; import { IpAddressPipe } from "./pipes/ip-address.pipe"; @@ -24,18 +24,22 @@ import { InputNumberModule } from "primeng/inputnumber"; import { ImageModule } from "primeng/image"; import { SidebarModule } from "primeng/sidebar"; import { HistoryBtnComponent } from "./components/history-btn/history-btn.component"; -import { DataViewModule, DataViewLayoutOptions } from "primeng/dataview"; +import { DataViewLayoutOptions, DataViewModule } from "primeng/dataview"; import { ConfigListComponent } from "./components/config-list/config-list.component"; import { MultiSelectModule } from "primeng/multiselect"; -import { HideableColumnComponent } from './components/hideable-column/hideable-column.component'; -import { HideableHeaderComponent } from './components/hideable-header/hideable-header.component'; -import { MultiSelectColumnsComponent } from './base/multi-select-columns/multi-select-columns.component'; -import { FeatureFlagListComponent } from './components/feature-flag-list/feature-flag-list.component'; +import { HideableColumnComponent } from "./components/hideable-column/hideable-column.component"; +import { HideableHeaderComponent } from "./components/hideable-header/hideable-header.component"; +import { MultiSelectColumnsComponent } from "./base/multi-select-columns/multi-select-columns.component"; +import { FeatureFlagListComponent } from "./components/feature-flag-list/feature-flag-list.component"; import { InputSwitchModule } from "primeng/inputswitch"; import { CalendarModule } from "primeng/calendar"; -import { DataImportAndExportComponent } from './components/data-import-and-export/data-import-and-export.component'; +import { DataImportAndExportComponent } from "./components/data-import-and-export/data-import-and-export.component"; import { FileUploadModule } from "primeng/fileupload"; import { SelectButtonModule } from "primeng/selectbutton"; +import { TabViewModule } from "primeng/tabview"; +import { RadioButtonModule } from "primeng/radiobutton"; +import { InputTextareaModule } from "primeng/inputtextarea"; +import { InputMaskModule } from "primeng/inputmask"; const PrimeNGModules = [ @@ -66,7 +70,11 @@ const PrimeNGModules = [ CalendarModule, FileUploadModule, SelectButtonModule, -] + TabViewModule, + RadioButtonModule, + InputTextareaModule, + InputMaskModule +]; @NgModule({ declarations: [ @@ -79,7 +87,7 @@ const PrimeNGModules = [ HideableHeaderComponent, MultiSelectColumnsComponent, FeatureFlagListComponent, - DataImportAndExportComponent, + DataImportAndExportComponent ], imports: [ CommonModule, @@ -98,6 +106,9 @@ const PrimeNGModules = [ MultiSelectColumnsComponent, FeatureFlagListComponent, DataImportAndExportComponent + ], + providers: [ + DatePipe ] }) export class SharedModule { diff --git a/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html new file mode 100644 index 00000000..c68de0de --- /dev/null +++ b/web/src/app/modules/view/server/scheduled-events/components/edit-scheduled-event-dialog/edit-scheduled-event-dialog.component.html @@ -0,0 +1,92 @@ +