From 1dbc66e517ed86f2e2e60373c36b636b72ecf3a3 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Sun, 15 Oct 2023 10:04:05 +0700 Subject: [PATCH 01/10] fix: protects the integrity of a class --- src/Constants/EventConstant.php | 2 +- src/Constants/SettingConstant.php | 2 +- src/Exceptions/CallbackException.php | 8 +++----- src/Exceptions/EntryNotFoundException.php | 10 ++++------ .../InvalidViewTemplateException.php | 3 +-- src/Exceptions/MessageIsEmptyException.php | 4 +--- src/Exceptions/SendNotificationException.php | 4 +--- .../TelegramGitNotifierException.php | 18 ++++++++++++++++++ src/Helpers/ConfigHelper.php | 2 +- 9 files changed, 31 insertions(+), 22 deletions(-) create mode 100644 src/Exceptions/TelegramGitNotifierException.php diff --git a/src/Constants/EventConstant.php b/src/Constants/EventConstant.php index 67e5ebe..94a54a2 100644 --- a/src/Constants/EventConstant.php +++ b/src/Constants/EventConstant.php @@ -2,7 +2,7 @@ namespace LbilTech\TelegramGitNotifier\Constants; -class EventConstant +final class EventConstant { public const DEFAULT_PLATFORM = 'github'; diff --git a/src/Constants/SettingConstant.php b/src/Constants/SettingConstant.php index 1346452..4b5e4a3 100644 --- a/src/Constants/SettingConstant.php +++ b/src/Constants/SettingConstant.php @@ -2,7 +2,7 @@ namespace LbilTech\TelegramGitNotifier\Constants; -class SettingConstant +final class SettingConstant { public const SETTING_PREFIX = 'stg.'; diff --git a/src/Exceptions/CallbackException.php b/src/Exceptions/CallbackException.php index 890f38d..f709bd4 100644 --- a/src/Exceptions/CallbackException.php +++ b/src/Exceptions/CallbackException.php @@ -2,17 +2,15 @@ namespace LbilTech\TelegramGitNotifier\Exceptions; -use Exception; - -class CallbackException extends Exception +final class CallbackException extends TelegramGitNotifierException { public static function isEmpty(): self { - return new static('Callback is empty'); + return new self('Callback is empty'); } public static function invalid(): self { - return new static('Callback is invalid'); + return new self('Callback is invalid'); } } diff --git a/src/Exceptions/EntryNotFoundException.php b/src/Exceptions/EntryNotFoundException.php index 919f18e..2e20763 100644 --- a/src/Exceptions/EntryNotFoundException.php +++ b/src/Exceptions/EntryNotFoundException.php @@ -2,22 +2,20 @@ namespace LbilTech\TelegramGitNotifier\Exceptions; -use Exception; - -class EntryNotFoundException extends Exception +final class EntryNotFoundException extends TelegramGitNotifierException { public static function fileNotFound(): self { - return new static('File not found'); + return new self('File not found'); } public static function configNotFound($config): self { - return new static("Config {$config} not found"); + return new self("Config {$config} not found"); } public static function viewNotFound($view): self { - return new static("View {$view} not found"); + return new self("View {$view} not found"); } } diff --git a/src/Exceptions/InvalidViewTemplateException.php b/src/Exceptions/InvalidViewTemplateException.php index af94850..0acddc2 100644 --- a/src/Exceptions/InvalidViewTemplateException.php +++ b/src/Exceptions/InvalidViewTemplateException.php @@ -2,10 +2,9 @@ namespace LbilTech\TelegramGitNotifier\Exceptions; -use Exception; use Throwable; -class InvalidViewTemplateException extends Exception +final class InvalidViewTemplateException extends TelegramGitNotifierException { public static function create( string $view, diff --git a/src/Exceptions/MessageIsEmptyException.php b/src/Exceptions/MessageIsEmptyException.php index 8fb3821..75d8cd6 100644 --- a/src/Exceptions/MessageIsEmptyException.php +++ b/src/Exceptions/MessageIsEmptyException.php @@ -2,9 +2,7 @@ namespace LbilTech\TelegramGitNotifier\Exceptions; -use Exception; - -class MessageIsEmptyException extends Exception +final class MessageIsEmptyException extends TelegramGitNotifierException { public static function create(): self { diff --git a/src/Exceptions/SendNotificationException.php b/src/Exceptions/SendNotificationException.php index 0318486..55a6b9a 100644 --- a/src/Exceptions/SendNotificationException.php +++ b/src/Exceptions/SendNotificationException.php @@ -2,9 +2,7 @@ namespace LbilTech\TelegramGitNotifier\Exceptions; -use Exception; - -class SendNotificationException extends Exception +final class SendNotificationException extends TelegramGitNotifierException { public static function create(): self { diff --git a/src/Exceptions/TelegramGitNotifierException.php b/src/Exceptions/TelegramGitNotifierException.php new file mode 100644 index 0000000..e9e0337 --- /dev/null +++ b/src/Exceptions/TelegramGitNotifierException.php @@ -0,0 +1,18 @@ + Date: Sun, 15 Oct 2023 18:00:21 +0700 Subject: [PATCH 02/10] refactor: structures --- src/{Services/TelegramService.php => Bot.php} | 35 ++++++---- src/Helpers/ConfigHelper.php | 2 +- ...TelegramInterface.php => BotInterface.php} | 2 +- src/Interfaces/EventInterface.php | 31 --------- .../{ => Structures}/AppInterface.php | 2 +- src/Interfaces/Structures/EventInterface.php | 68 +++++++++++++++++++ .../NotificationInterface.php | 5 +- .../{ => Structures}/SettingInterface.php | 19 +++++- .../{ => Structures}/WebhookInterface.php | 2 +- src/Notifier.php | 21 ++++++ src/Services/EventService.php | 55 --------------- src/Services/SettingService.php | 36 ---------- .../AppService.php => Structures/App.php} | 16 ++--- src/{Models => Structures}/Event.php | 27 +------- .../Notification.php} | 16 +---- src/{Models => Structures}/Setting.php | 15 +--- src/Trait/BotSettingTrait.php | 6 +- src/Trait/EventSettingTrait.php | 4 +- src/Trait/ValidationEventTrait.php | 35 ++++++++++ .../WebhookService.php => Webhook.php} | 6 +- 20 files changed, 190 insertions(+), 213 deletions(-) rename src/{Services/TelegramService.php => Bot.php} (52%) rename src/Interfaces/{TelegramInterface.php => BotInterface.php} (97%) delete mode 100644 src/Interfaces/EventInterface.php rename src/Interfaces/{ => Structures}/AppInterface.php (97%) create mode 100644 src/Interfaces/Structures/EventInterface.php rename src/Interfaces/{ => Structures}/NotificationInterface.php (86%) rename src/Interfaces/{ => Structures}/SettingInterface.php (89%) rename src/Interfaces/{ => Structures}/WebhookInterface.php (90%) create mode 100644 src/Notifier.php delete mode 100644 src/Services/EventService.php delete mode 100644 src/Services/SettingService.php rename src/{Services/AppService.php => Structures/App.php} (88%) rename src/{Models => Structures}/Event.php (75%) rename src/{Services/NotificationService.php => Structures/Notification.php} (86%) rename src/{Models => Structures}/Setting.php (90%) create mode 100644 src/Trait/ValidationEventTrait.php rename src/{Services/WebhookService.php => Webhook.php} (79%) diff --git a/src/Services/TelegramService.php b/src/Bot.php similarity index 52% rename from src/Services/TelegramService.php rename to src/Bot.php index 0b8d9c1..788bc56 100644 --- a/src/Services/TelegramService.php +++ b/src/Bot.php @@ -1,22 +1,33 @@ setCurrentChatId($chatId); - - $this->telegram = $telegram; + public function __construct(Telegram $telegram = null) + { + $this->telegram = $telegram ?? new Telegram(config('telegram-git-notifier.bot.token')); } public function setMyCommands( diff --git a/src/Helpers/ConfigHelper.php b/src/Helpers/ConfigHelper.php index 8fa6ce6..7626aba 100644 --- a/src/Helpers/ConfigHelper.php +++ b/src/Helpers/ConfigHelper.php @@ -6,7 +6,7 @@ use LbilTech\TelegramGitNotifier\Exceptions\InvalidViewTemplateException; use Throwable; -final class ConfigHelper +class ConfigHelper { public array $config; diff --git a/src/Interfaces/TelegramInterface.php b/src/Interfaces/BotInterface.php similarity index 97% rename from src/Interfaces/TelegramInterface.php rename to src/Interfaces/BotInterface.php index f6d95c4..8f9091d 100644 --- a/src/Interfaces/TelegramInterface.php +++ b/src/Interfaces/BotInterface.php @@ -4,7 +4,7 @@ use LbilTech\TelegramGitNotifier\Exceptions\MessageIsEmptyException; -interface TelegramInterface +interface BotInterface { /** * Set the menu button for a telegram diff --git a/src/Interfaces/EventInterface.php b/src/Interfaces/EventInterface.php deleted file mode 100644 index 82c6028..0000000 --- a/src/Interfaces/EventInterface.php +++ /dev/null @@ -1,31 +0,0 @@ -client = $client; + } +} diff --git a/src/Services/EventService.php b/src/Services/EventService.php deleted file mode 100644 index 50e5bcf..0000000 --- a/src/Services/EventService.php +++ /dev/null @@ -1,55 +0,0 @@ -setting = $setting; - $this->event = $event; - } - - public function validateAccessEvent( - string $platform, - string $event, - $payload - ): bool { - if (!$this->setting->isNotified()) { - return false; - } - - if ($this->setting->isAllEventsNotification()) { - return true; - } - - $this->event->setEventConfig($platform); - $eventConfig = $this->event->eventConfig; - - $eventConfig = $eventConfig[tgn_convert_event_name($event)] ?? false; - $action = $this->getActionOfEvent($payload); - - if (!empty($action) && isset($eventConfig[$action])) { - $eventConfig = $eventConfig[$action]; - } - - if (!$eventConfig) { - error_log('\n Event config is not found \n'); - } - - return (bool)$eventConfig; - } -} diff --git a/src/Services/SettingService.php b/src/Services/SettingService.php deleted file mode 100644 index 4a1684d..0000000 --- a/src/Services/SettingService.php +++ /dev/null @@ -1,36 +0,0 @@ -setting = $setting; - $this->event = $event; - - $this->setCurrentChatId($chatId); - } -} diff --git a/src/Services/AppService.php b/src/Structures/App.php similarity index 88% rename from src/Services/AppService.php rename to src/Structures/App.php index 6a7f4a0..46183ba 100644 --- a/src/Services/AppService.php +++ b/src/Structures/App.php @@ -1,30 +1,24 @@ telegram = $telegram ?? new Telegram(config('telegram-git-notifier.bot.token')); - } - public function setCurrentChatId(string $chatId = null): void { $this->chatId = $chatId ?? config('telegram-git-notifier.bot.chat_id'); } - private function createBaseContent(): array + private function createTelegramBaseContent(): array { return [ 'chat_id' => $this->chatId, @@ -39,7 +33,7 @@ public function sendMessage(string $message = '', array $options = []): void throw MessageIsEmptyException::create(); } - $content = $this->createBaseContent(); + $content = $this->createTelegramBaseContent(); $content['text'] = $message; if (!empty($options['reply_markup'])) { @@ -57,7 +51,7 @@ public function sendPhoto(string $photo = '', string $caption = ''): void throw EntryNotFoundException::fileNotFound(); } - $content = $this->createBaseContent(); + $content = $this->createTelegramBaseContent(); $content['photo'] = curl_file_create($photo); $content['caption'] = $caption; diff --git a/src/Models/Event.php b/src/Structures/Event.php similarity index 75% rename from src/Models/Event.php rename to src/Structures/Event.php index c223f56..8b60b60 100644 --- a/src/Models/Event.php +++ b/src/Structures/Event.php @@ -1,10 +1,10 @@ platformFile; } - /** - * @param string $platformFile - * - * @return void - */ public function setPlatformFile(string $platformFile): void { $this->platformFile = $platformFile; } - /** - * Set event config - * - * @param string $platform - * - * @return void - */ public function setEventConfig( string $platform = EventConstant::DEFAULT_PLATFORM ): void { @@ -46,14 +31,6 @@ public function setEventConfig( $this->eventConfig = json_decode($json, true); } - /** - * Update event config by event and action - * - * @param string $event - * @param string|null $action - * - * @return void - */ public function updateEvent(string $event, string|null $action): void { if (!empty($action)) { diff --git a/src/Services/NotificationService.php b/src/Structures/Notification.php similarity index 86% rename from src/Services/NotificationService.php rename to src/Structures/Notification.php index dc85ef4..a3b9b03 100644 --- a/src/Services/NotificationService.php +++ b/src/Structures/Notification.php @@ -1,19 +1,15 @@ client = $client; - } - public function accessDenied( - TelegramService $telegramService, string $chatId = null, string $viewTemplate = null, ): void { - $telegramService->telegram->sendMessage([ + $this->telegram->sendMessage([ 'chat_id' => config('telegram-git-notifier.bot.chat_id'), 'text' => view( $viewTemplate ?? config('telegram-git-notifier.view.globals.access_denied'), diff --git a/src/Models/Setting.php b/src/Structures/Setting.php similarity index 90% rename from src/Models/Setting.php rename to src/Structures/Setting.php index bce7fe8..99de902 100644 --- a/src/Models/Setting.php +++ b/src/Structures/Setting.php @@ -1,10 +1,10 @@ settings) @@ -75,14 +72,6 @@ public function isNotified(): bool return false; } - /** - * Update setting item value and save to file - * - * @param string $settingName - * @param $settingValue - * - * @return bool - */ public function updateSettingItem( string $settingName, $settingValue = null diff --git a/src/Trait/BotSettingTrait.php b/src/Trait/BotSettingTrait.php index 3d2593f..c5a34a1 100644 --- a/src/Trait/BotSettingTrait.php +++ b/src/Trait/BotSettingTrait.php @@ -19,7 +19,7 @@ public function settingMarkup(): array $markup = [ [ $this->telegram->buildInlineKeyBoardButton( - $this->setting->getSettings()[SettingConstant::T_IS_NOTIFIED] + $this->getSettings()[SettingConstant::T_IS_NOTIFIED] ? '✅ Allow notifications' : 'Allow notifications', '', @@ -28,7 +28,7 @@ public function settingMarkup(): array ], [ $this->telegram->buildInlineKeyBoardButton( - $this->setting->getSettings()[SettingConstant::T_ALL_EVENTS_NOTIFICATION] + $this->getSettings()[SettingConstant::T_ALL_EVENTS_NOTIFICATION] ? '✅ Enable All Events Notify' : 'Enable All Events Notify', '', @@ -52,7 +52,7 @@ public function settingMarkup(): array public function customEventMarkup(array $markup): array { - if (!$this->setting->getSettings()[SettingConstant::T_ALL_EVENTS_NOTIFICATION]) { + if (!$this->getSettings()[SettingConstant::T_ALL_EVENTS_NOTIFICATION]) { $markup[] = [ $this->telegram->buildInlineKeyBoardButton( '🦑 Custom github events', diff --git a/src/Trait/EventSettingTrait.php b/src/Trait/EventSettingTrait.php index 369766d..8c1ddbc 100644 --- a/src/Trait/EventSettingTrait.php +++ b/src/Trait/EventSettingTrait.php @@ -202,8 +202,8 @@ public function eventUpdateHandle(string $event, string $platform): void { [$event, $action] = explode('.', $event); - $this->event->setEventConfig($platform); - $this->event->updateEvent($event, $action); + $this->setEventConfig($platform); + $this->updateEvent($event, $action); $this->eventHandle( $action ? EventConstant::PLATFORM_EVENT_SEPARATOR[$platform] diff --git a/src/Trait/ValidationEventTrait.php b/src/Trait/ValidationEventTrait.php new file mode 100644 index 0000000..3628820 --- /dev/null +++ b/src/Trait/ValidationEventTrait.php @@ -0,0 +1,35 @@ +isNotified()) { + return false; + } + + if ($this->isAllEventsNotification()) { + return true; + } + + $this->setEventConfig($platform); + + $eventConfig = $this->eventConfig[tgn_convert_event_name($event)] ?? false; + $action = $this->getActionOfEvent($payload); + + if (!empty($action) && isset($eventConfig[$action])) { + $eventConfig = $eventConfig[$action]; + } + + if (!$eventConfig) { + error_log('\n Event config is not found \n'); + } + + return (bool)$eventConfig; + } +} diff --git a/src/Services/WebhookService.php b/src/Webhook.php similarity index 79% rename from src/Services/WebhookService.php rename to src/Webhook.php index bc7d75f..4ab0230 100644 --- a/src/Services/WebhookService.php +++ b/src/Webhook.php @@ -1,10 +1,10 @@ Date: Mon, 16 Oct 2023 23:41:42 +0700 Subject: [PATCH 03/10] refactor: structures v2 --- src/Bot.php | 3 +- src/Interfaces/Structures/AppInterface.php | 2 +- .../Structures/SettingInterface.php | 2 +- src/Notifier.php | 12 +++++--- src/Structures/App.php | 18 +++++++----- src/Structures/Notification.php | 28 ++++--------------- src/Structures/Setting.php | 2 +- src/Trait/EventSettingTrait.php | 6 ++-- 8 files changed, 32 insertions(+), 41 deletions(-) diff --git a/src/Bot.php b/src/Bot.php index 788bc56..0188f67 100644 --- a/src/Bot.php +++ b/src/Bot.php @@ -28,6 +28,7 @@ class Bot implements AppInterface, EventInterface, SettingInterface, BotInterfac public function __construct(Telegram $telegram = null) { $this->telegram = $telegram ?? new Telegram(config('telegram-git-notifier.bot.token')); + $this->setCurrentChatBotId(); } public function setMyCommands( @@ -65,7 +66,7 @@ public function isMessage(): bool public function isOwner(): bool { - if ($this->telegram->ChatID() == $this->chatId) { + if ($this->telegram->ChatID() == $this->chatBotId) { return true; } diff --git a/src/Interfaces/Structures/AppInterface.php b/src/Interfaces/Structures/AppInterface.php index 883de43..a8a70c7 100644 --- a/src/Interfaces/Structures/AppInterface.php +++ b/src/Interfaces/Structures/AppInterface.php @@ -85,7 +85,7 @@ public function setCallbackContentMessage(array $options = []): array; * * @return void */ - public function setCurrentChatId(string $chatId): void; + public function setCurrentChatBotId(string $chatId): void; /** * Get the username of the bot diff --git a/src/Interfaces/Structures/SettingInterface.php b/src/Interfaces/Structures/SettingInterface.php index 667fe11..d10f1a6 100644 --- a/src/Interfaces/Structures/SettingInterface.php +++ b/src/Interfaces/Structures/SettingInterface.php @@ -183,7 +183,7 @@ public function customEventMarkup(array $markup): array; * * @return bool */ - public function updateSettingItem(string $settingName, $settingValue = null): bool; + public function updateSetting(string $settingName, $settingValue = null): bool; /** * Condition for checking the notification status diff --git a/src/Notifier.php b/src/Notifier.php index 5692f1f..4a6f3bd 100644 --- a/src/Notifier.php +++ b/src/Notifier.php @@ -2,20 +2,24 @@ namespace LbilTech\TelegramGitNotifier; -use GuzzleHttp\Client; use LbilTech\TelegramGitNotifier\Interfaces\Structures\NotificationInterface; use LbilTech\TelegramGitNotifier\Structures\App; +use LbilTech\TelegramGitNotifier\Structures\Event; use LbilTech\TelegramGitNotifier\Structures\Notification; use LbilTech\TelegramGitNotifier\Trait\ActionEventTrait; +use Telegram; class Notifier implements NotificationInterface { use App; + use Event; use Notification; use ActionEventTrait; - public function __construct(Client $client) - { - $this->client = $client; + public function __construct( + Telegram $telegram = null + ) { + $this->telegram = $telegram ?? new Telegram(config('telegram-git-notifier.bot.token')); + $this->setCurrentChatBotId(); } } diff --git a/src/Structures/App.php b/src/Structures/App.php index 46183ba..596b059 100644 --- a/src/Structures/App.php +++ b/src/Structures/App.php @@ -11,17 +11,17 @@ trait App { public Telegram $telegram; - public string $chatId; + public string $chatBotId; - public function setCurrentChatId(string $chatId = null): void + public function setCurrentChatBotId(string $chatBotId = null): void { - $this->chatId = $chatId ?? config('telegram-git-notifier.bot.chat_id'); + $this->chatBotId = $chatBotId ?? config('telegram-git-notifier.bot.chat_id'); } private function createTelegramBaseContent(): array { return [ - 'chat_id' => $this->chatId, + 'chat_id' => $this->chatBotId, 'disable_web_page_preview' => true, 'parse_mode' => 'HTML' ]; @@ -40,8 +40,11 @@ public function sendMessage(string $message = '', array $options = []): void $content['reply_markup'] = $this->telegram->buildInlineKeyBoard( $options['reply_markup'] ); + unset($options['reply_markup']); } + $content = array_merge($content, $options); + $this->telegram->sendMessage($content); } @@ -58,18 +61,19 @@ public function sendPhoto(string $photo = '', string $caption = ''): void $this->telegram->sendPhoto($content); } - public function answerCallbackQuery(string $text = null): void + public function answerCallbackQuery(string $text = null, array $options = []): void { if (empty($text)) { throw MessageIsEmptyException::create(); } try { - $this->telegram->answerCallbackQuery([ + $options = array_merge([ 'callback_query_id' => $this->telegram->Callback_ID(), 'text' => $text, 'show_alert' => true - ]); + ], $options); + $this->telegram->answerCallbackQuery($options); } catch (Exception $e) { error_log("Error answering callback query: " . $e->getMessage()); } diff --git a/src/Structures/Notification.php b/src/Structures/Notification.php index a3b9b03..2dc6c5b 100644 --- a/src/Structures/Notification.php +++ b/src/Structures/Notification.php @@ -2,9 +2,8 @@ namespace LbilTech\TelegramGitNotifier\Structures; -use GuzzleHttp\Client; -use GuzzleHttp\Exception\GuzzleException; use LbilTech\TelegramGitNotifier\Constants\EventConstant; +use LbilTech\TelegramGitNotifier\Exceptions\MessageIsEmptyException; use LbilTech\TelegramGitNotifier\Exceptions\SendNotificationException; use Symfony\Component\HttpFoundation\Request; @@ -14,10 +13,6 @@ trait Notification public string $message = ''; - public string $platform = EventConstant::DEFAULT_PLATFORM; - - public Client $client; - public function accessDenied( string $chatId = null, string $viewTemplate = null, @@ -73,26 +68,13 @@ public function sendNotify(string $chatId, string $message = null): bool $this->message = $message; } - $queryParams = [ - 'chat_id' => $chatId, - 'disable_web_page_preview' => 1, - 'parse_mode' => 'html', - 'text' => $this->message - ]; - - $url = 'https://api.telegram.org/bot' - . config('telegram-git-notifier.bot.token') . '/sendMessage' - . '?' . http_build_query($queryParams); - try { - $response = $this->client->request('GET', $url); - - if ($response->getStatusCode() === 200) { - return true; - } + $this->sendMessage($this->message, [ + 'chat_id' => $chatId, + ]); throw SendNotificationException::create(); - } catch (GuzzleException $e) { + } catch (MessageIsEmptyException $e) { error_log($e->getMessage()); } diff --git a/src/Structures/Setting.php b/src/Structures/Setting.php index 99de902..4de4521 100644 --- a/src/Structures/Setting.php +++ b/src/Structures/Setting.php @@ -72,7 +72,7 @@ public function isNotified(): bool return false; } - public function updateSettingItem( + public function updateSetting( string $settingName, $settingValue = null ): bool { diff --git a/src/Trait/EventSettingTrait.php b/src/Trait/EventSettingTrait.php index 8c1ddbc..dfbbccb 100644 --- a/src/Trait/EventSettingTrait.php +++ b/src/Trait/EventSettingTrait.php @@ -13,9 +13,9 @@ public function eventMarkup( ): array { $replyMarkup = $replyMarkupItem = []; - $this->event->setEventConfig($platform); - $events = $parentEvent === null ? $this->event->eventConfig - : $this->event->eventConfig[$parentEvent]; + $this->setEventConfig($platform); + $events = $parentEvent === null ? $this->eventConfig + : $this->eventConfig[$parentEvent]; foreach ($events as $key => $value) { if (count($replyMarkupItem) === SettingConstant::BTN_LINE_ITEM_COUNT) { From 817116127e73372530154fab1f542495244ead01 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Tue, 17 Oct 2023 21:59:49 +0700 Subject: [PATCH 04/10] refactor: structures for notifier --- .../{github-event.json => github-events.json} | 0 .../{gitlab-event.json => gitlab-events.json} | 0 .../{tg-setting.json => tgn-settings.json} | 0 config/tg-notifier.php | 14 +++- src/Bot.php | 49 +++++++++---- src/Interfaces/EventInterface.php | 55 +++++++++++++++ src/Interfaces/Structures/EventInterface.php | 68 ------------------- .../Structures/NotificationInterface.php | 2 +- .../Structures/SettingInterface.php | 17 ----- .../{Structures => }/WebhookInterface.php | 2 +- src/{Structures => Models}/Event.php | 27 +++++++- src/{Structures => Models}/Setting.php | 19 +++++- src/Notifier.php | 32 +++++++-- src/Objects/Validator.php | 50 ++++++++++++++ src/Structures/App.php | 2 +- src/Structures/Notification.php | 31 ++++++--- src/Trait/BotSettingTrait.php | 6 +- src/Trait/EventSettingTrait.php | 10 +-- src/Trait/EventTrait.php | 36 ++++++++++ src/Trait/ValidationEventTrait.php | 35 ---------- src/Webhook.php | 2 +- 21 files changed, 290 insertions(+), 167 deletions(-) rename config/jsons/{github-event.json => github-events.json} (100%) rename config/jsons/{gitlab-event.json => gitlab-events.json} (100%) rename config/jsons/{tg-setting.json => tgn-settings.json} (100%) create mode 100644 src/Interfaces/EventInterface.php delete mode 100644 src/Interfaces/Structures/EventInterface.php rename src/Interfaces/{Structures => }/WebhookInterface.php (90%) rename src/{Structures => Models}/Event.php (75%) rename src/{Structures => Models}/Setting.php (87%) create mode 100644 src/Objects/Validator.php create mode 100644 src/Trait/EventTrait.php delete mode 100644 src/Trait/ValidationEventTrait.php diff --git a/config/jsons/github-event.json b/config/jsons/github-events.json similarity index 100% rename from config/jsons/github-event.json rename to config/jsons/github-events.json diff --git a/config/jsons/gitlab-event.json b/config/jsons/gitlab-events.json similarity index 100% rename from config/jsons/gitlab-event.json rename to config/jsons/gitlab-events.json diff --git a/config/jsons/tg-setting.json b/config/jsons/tgn-settings.json similarity index 100% rename from config/jsons/tg-setting.json rename to config/jsons/tgn-settings.json diff --git a/config/tg-notifier.php b/config/tg-notifier.php index 1021753..abf5021 100644 --- a/config/tg-notifier.php +++ b/config/tg-notifier.php @@ -18,12 +18,24 @@ ], 'author' => [ - 'discussion' => $_ENV['TGN_AUTHOR_DISCUSSION'] ?? + 'discussion' => $_ENV['TGN_AUTHOR_DISCUSSION'] ?? 'https://github.com/lbiltech/telegram-git-notifier/discussions', 'source_code' => $_ENV['TGN_AUTHOR_SOURCE_CODE'] ?? 'https://github.com/lbiltech/telegram-git-notifier', ], + 'data_file' => [ + 'setting' => $_ENV['TGN_PATH_SETTING'] ?? + 'storage/json/tgn/tgn-settings.json', + + 'platform' => [ + 'gitlab' => $_ENV['TGN_PATH_PLATFORM_GITLAB'] ?? + 'storage/json/tgn/gitlab-events.json', + 'github' => $_ENV['TGN_PATH_PLATFORM_GITHUB'] ?? + 'storage/json/tgn/github-events.json', + ], + ], + 'view' => [ 'path' => $_ENV['TGN_VIEW_PATH'] ?? 'resources/views', diff --git a/src/Bot.php b/src/Bot.php index 0188f67..dfe9a5b 100644 --- a/src/Bot.php +++ b/src/Bot.php @@ -2,33 +2,56 @@ namespace LbilTech\TelegramGitNotifier; +use LbilTech\TelegramGitNotifier\Constants\EventConstant; use LbilTech\TelegramGitNotifier\Interfaces\BotInterface; use LbilTech\TelegramGitNotifier\Interfaces\Structures\AppInterface; -use LbilTech\TelegramGitNotifier\Interfaces\Structures\EventInterface; +use LbilTech\TelegramGitNotifier\Interfaces\EventInterface; use LbilTech\TelegramGitNotifier\Interfaces\Structures\SettingInterface; +use LbilTech\TelegramGitNotifier\Models\Event; +use LbilTech\TelegramGitNotifier\Models\Setting; use LbilTech\TelegramGitNotifier\Structures\App; -use LbilTech\TelegramGitNotifier\Structures\Event; -use LbilTech\TelegramGitNotifier\Structures\Setting; use LbilTech\TelegramGitNotifier\Trait\BotSettingTrait; use LbilTech\TelegramGitNotifier\Trait\EventSettingTrait; -use LbilTech\TelegramGitNotifier\Trait\ValidationEventTrait; -use LbilTech\TelegramGitNotifier\Trait\ActionEventTrait; +use LbilTech\TelegramGitNotifier\Trait\EventTrait; use Telegram; -class Bot implements AppInterface, EventInterface, SettingInterface, BotInterface +class Bot implements AppInterface, BotInterface, EventInterface { use App; - use Event; - use Setting; - use ValidationEventTrait; - use ActionEventTrait; + use EventTrait; use BotSettingTrait; use EventSettingTrait; - public function __construct(Telegram $telegram = null) - { + public Event $event; + + public Setting $setting; + + public function __construct( + Telegram $telegram = null, + ?string $chatBotId = null, + Setting $setting = null, + Event $event = null, + ?string $settingFile = null, + ?string $platform = EventConstant::DEFAULT_PLATFORM, + ?string $platformFile = null, + ) { $this->telegram = $telegram ?? new Telegram(config('telegram-git-notifier.bot.token')); - $this->setCurrentChatBotId(); + $this->setCurrentChatBotId($chatBotId); + $this->event = $event ?? new Event(); + $this->setPlatFormForEvent($platform, $platformFile); + + $this->setting = $setting ?? new Setting(); + $this->updateSetting($settingFile); + } + + public function updateSetting(?string $settingFile = null): void + { + if ($this->setting->getSettingFile()) { + return; + } + $settingFile = $settingFile ?? config('telegram-git-notifier.data_file.setting'); + $this->setting->setSettingFile($settingFile); + $this->setting->setSettingConfig(); } public function setMyCommands( diff --git a/src/Interfaces/EventInterface.php b/src/Interfaces/EventInterface.php new file mode 100644 index 0000000..571365c --- /dev/null +++ b/src/Interfaces/EventInterface.php @@ -0,0 +1,55 @@ +platformFile; } + /** + * @param string $platformFile + * + * @return void + */ public function setPlatformFile(string $platformFile): void { $this->platformFile = $platformFile; } + /** + * Set event config + * + * @param string $platform + * + * @return void + */ public function setEventConfig( string $platform = EventConstant::DEFAULT_PLATFORM ): void { @@ -31,6 +46,14 @@ public function setEventConfig( $this->eventConfig = json_decode($json, true); } + /** + * Update event config by event and action + * + * @param string $event + * @param string|null $action + * + * @return void + */ public function updateEvent(string $event, string|null $action): void { if (!empty($action)) { diff --git a/src/Structures/Setting.php b/src/Models/Setting.php similarity index 87% rename from src/Structures/Setting.php rename to src/Models/Setting.php index 4de4521..11bc475 100644 --- a/src/Structures/Setting.php +++ b/src/Models/Setting.php @@ -1,12 +1,12 @@ settings) @@ -72,6 +77,14 @@ public function isNotified(): bool return false; } + /** + * Update setting item value and save to file + * + * @param string $settingName + * @param $settingValue + * + * @return bool + */ public function updateSetting( string $settingName, $settingValue = null diff --git a/src/Notifier.php b/src/Notifier.php index 4a6f3bd..37844c0 100644 --- a/src/Notifier.php +++ b/src/Notifier.php @@ -2,24 +2,42 @@ namespace LbilTech\TelegramGitNotifier; +use GuzzleHttp\Client; +use LbilTech\TelegramGitNotifier\Constants\EventConstant; +use LbilTech\TelegramGitNotifier\Interfaces\Structures\AppInterface; +use LbilTech\TelegramGitNotifier\Interfaces\EventInterface; use LbilTech\TelegramGitNotifier\Interfaces\Structures\NotificationInterface; +use LbilTech\TelegramGitNotifier\Models\Event; use LbilTech\TelegramGitNotifier\Structures\App; -use LbilTech\TelegramGitNotifier\Structures\Event; use LbilTech\TelegramGitNotifier\Structures\Notification; -use LbilTech\TelegramGitNotifier\Trait\ActionEventTrait; +use LbilTech\TelegramGitNotifier\Trait\EventTrait; use Telegram; -class Notifier implements NotificationInterface +class Notifier implements AppInterface, NotificationInterface, EventInterface { use App; - use Event; use Notification; - use ActionEventTrait; + + use EventTrait; + + public Event $event; + + public Client $client; public function __construct( - Telegram $telegram = null + Telegram $telegram = null, + ?string $chatBotId = null, + Event $event = null, + ?string $platform = EventConstant::DEFAULT_PLATFORM, + ?string $platformFile = null, + Client $client = null, ) { $this->telegram = $telegram ?? new Telegram(config('telegram-git-notifier.bot.token')); - $this->setCurrentChatBotId(); + $this->setCurrentChatBotId($chatBotId); + + $this->event = $event ?? new Event(); + $this->setPlatFormForEvent($platform, $platformFile); + + $this->client = $client ?? new Client(); } } diff --git a/src/Objects/Validator.php b/src/Objects/Validator.php new file mode 100644 index 0000000..77969ce --- /dev/null +++ b/src/Objects/Validator.php @@ -0,0 +1,50 @@ +setting = $setting; + $this->event = $event; + } + + public function accessEvent( + string $platform, + string $event, + $payload + ): bool { + if (!$this->setting->isNotified()) { + return false; + } + + if ($this->setting->isAllEventsNotification()) { + return true; + } + $this->event->setEventConfig($platform); + + $eventConfig = $this->event->eventConfig[tgn_convert_event_name($event)] ?? false; + $action = $this->getActionOfEvent($payload); + + if (!empty($action) && isset($eventConfig[$action])) { + $eventConfig = $eventConfig[$action]; + } + + if (!$eventConfig) { + error_log('\n Event config is not found \n'); + } + + return (bool)$eventConfig; + } +} diff --git a/src/Structures/App.php b/src/Structures/App.php index 596b059..f3bf8c1 100644 --- a/src/Structures/App.php +++ b/src/Structures/App.php @@ -43,7 +43,7 @@ public function sendMessage(string $message = '', array $options = []): void unset($options['reply_markup']); } - $content = array_merge($content, $options); + $content = $content + $options; $this->telegram->sendMessage($content); } diff --git a/src/Structures/Notification.php b/src/Structures/Notification.php index 2dc6c5b..b9e2508 100644 --- a/src/Structures/Notification.php +++ b/src/Structures/Notification.php @@ -2,8 +2,8 @@ namespace LbilTech\TelegramGitNotifier\Structures; +use GuzzleHttp\Exception\GuzzleException; use LbilTech\TelegramGitNotifier\Constants\EventConstant; -use LbilTech\TelegramGitNotifier\Exceptions\MessageIsEmptyException; use LbilTech\TelegramGitNotifier\Exceptions\SendNotificationException; use Symfony\Component\HttpFoundation\Request; @@ -30,9 +30,9 @@ public function accessDenied( public function setPayload(Request $request, string $event) { - if ($this->platform === 'gitlab') { + if ($this->event->platform === 'gitlab') { $this->payload = json_decode($request->getContent()); - } elseif ($this->platform === EventConstant::DEFAULT_PLATFORM) { + } elseif ($this->event->platform === EventConstant::DEFAULT_PLATFORM) { $this->payload = json_decode($request->request->get('payload')); } $this->setMessage($event); @@ -53,8 +53,8 @@ private function setMessage(string $typeEvent): void $action = $this->getActionOfEvent($this->payload); $viewTemplate = empty($action) - ? "events.{$this->platform}.{$event}.default" - : "events.{$this->platform}.{$event}.{$action}"; + ? "events.{$this->event->platform}.{$event}.default" + : "events.{$this->event->platform}.{$event}.{$action}"; $this->message = view($viewTemplate, [ 'payload' => $this->payload, @@ -68,13 +68,26 @@ public function sendNotify(string $chatId, string $message = null): bool $this->message = $message; } + $queryParams = [ + 'chat_id' => $chatId, + 'disable_web_page_preview' => 1, + 'parse_mode' => 'html', + 'text' => $this->message + ]; + + $url = 'https://api.telegram.org/bot' + . config('telegram-git-notifier.bot.token') . '/sendMessage' + . '?' . http_build_query($queryParams); + try { - $this->sendMessage($this->message, [ - 'chat_id' => $chatId, - ]); + $response = $this->client->request('GET', $url); + + if ($response->getStatusCode() === 200) { + return true; + } throw SendNotificationException::create(); - } catch (MessageIsEmptyException $e) { + } catch (GuzzleException $e) { error_log($e->getMessage()); } diff --git a/src/Trait/BotSettingTrait.php b/src/Trait/BotSettingTrait.php index c5a34a1..3d2593f 100644 --- a/src/Trait/BotSettingTrait.php +++ b/src/Trait/BotSettingTrait.php @@ -19,7 +19,7 @@ public function settingMarkup(): array $markup = [ [ $this->telegram->buildInlineKeyBoardButton( - $this->getSettings()[SettingConstant::T_IS_NOTIFIED] + $this->setting->getSettings()[SettingConstant::T_IS_NOTIFIED] ? '✅ Allow notifications' : 'Allow notifications', '', @@ -28,7 +28,7 @@ public function settingMarkup(): array ], [ $this->telegram->buildInlineKeyBoardButton( - $this->getSettings()[SettingConstant::T_ALL_EVENTS_NOTIFICATION] + $this->setting->getSettings()[SettingConstant::T_ALL_EVENTS_NOTIFICATION] ? '✅ Enable All Events Notify' : 'Enable All Events Notify', '', @@ -52,7 +52,7 @@ public function settingMarkup(): array public function customEventMarkup(array $markup): array { - if (!$this->getSettings()[SettingConstant::T_ALL_EVENTS_NOTIFICATION]) { + if (!$this->setting->getSettings()[SettingConstant::T_ALL_EVENTS_NOTIFICATION]) { $markup[] = [ $this->telegram->buildInlineKeyBoardButton( '🦑 Custom github events', diff --git a/src/Trait/EventSettingTrait.php b/src/Trait/EventSettingTrait.php index dfbbccb..369766d 100644 --- a/src/Trait/EventSettingTrait.php +++ b/src/Trait/EventSettingTrait.php @@ -13,9 +13,9 @@ public function eventMarkup( ): array { $replyMarkup = $replyMarkupItem = []; - $this->setEventConfig($platform); - $events = $parentEvent === null ? $this->eventConfig - : $this->eventConfig[$parentEvent]; + $this->event->setEventConfig($platform); + $events = $parentEvent === null ? $this->event->eventConfig + : $this->event->eventConfig[$parentEvent]; foreach ($events as $key => $value) { if (count($replyMarkupItem) === SettingConstant::BTN_LINE_ITEM_COUNT) { @@ -202,8 +202,8 @@ public function eventUpdateHandle(string $event, string $platform): void { [$event, $action] = explode('.', $event); - $this->setEventConfig($platform); - $this->updateEvent($event, $action); + $this->event->setEventConfig($platform); + $this->event->updateEvent($event, $action); $this->eventHandle( $action ? EventConstant::PLATFORM_EVENT_SEPARATOR[$platform] diff --git a/src/Trait/EventTrait.php b/src/Trait/EventTrait.php new file mode 100644 index 0000000..b29c157 --- /dev/null +++ b/src/Trait/EventTrait.php @@ -0,0 +1,36 @@ +event->getPlatformFile()) { + /** @var array $platformFileDefaults */ + $platformFileDefaults = config('telegram-git-notifier.data_file.platform'); + $this->event->setPlatformFile($platformFile ?? $platformFileDefaults[$platform]); + } + $this->event->setEventConfig($platform); + } + + public function handleEventFromRequest(Request $request): ?string + { + foreach (EventConstant::WEBHOOK_EVENT_HEADER as $platform => $header) { + $event = $request->server->get($header); + if (!is_null($event)) { + $this->event->platform = $platform; + $this->setPlatFormForEvent($platform); + + return $event; + } + } + + return null; + } +} diff --git a/src/Trait/ValidationEventTrait.php b/src/Trait/ValidationEventTrait.php deleted file mode 100644 index 3628820..0000000 --- a/src/Trait/ValidationEventTrait.php +++ /dev/null @@ -1,35 +0,0 @@ -isNotified()) { - return false; - } - - if ($this->isAllEventsNotification()) { - return true; - } - - $this->setEventConfig($platform); - - $eventConfig = $this->eventConfig[tgn_convert_event_name($event)] ?? false; - $action = $this->getActionOfEvent($payload); - - if (!empty($action) && isset($eventConfig[$action])) { - $eventConfig = $eventConfig[$action]; - } - - if (!$eventConfig) { - error_log('\n Event config is not found \n'); - } - - return (bool)$eventConfig; - } -} diff --git a/src/Webhook.php b/src/Webhook.php index 4ab0230..1782adc 100644 --- a/src/Webhook.php +++ b/src/Webhook.php @@ -2,7 +2,7 @@ namespace LbilTech\TelegramGitNotifier; -use LbilTech\TelegramGitNotifier\Interfaces\Structures\WebhookInterface; +use LbilTech\TelegramGitNotifier\Interfaces\WebhookInterface; class Webhook implements WebhookInterface { From 2c10816a5a7e40b08ec3b3fb2ae215e8c61709c7 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Tue, 17 Oct 2023 22:28:56 +0700 Subject: [PATCH 05/10] update some methods in object and models --- src/Interfaces/EventInterface.php | 16 ---------------- src/Models/Event.php | 10 +++++++++- src/Models/Setting.php | 2 +- src/Objects/Validator.php | 13 +++++++++++-- 4 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/Interfaces/EventInterface.php b/src/Interfaces/EventInterface.php index 571365c..fdbb2b4 100644 --- a/src/Interfaces/EventInterface.php +++ b/src/Interfaces/EventInterface.php @@ -2,26 +2,10 @@ namespace LbilTech\TelegramGitNotifier\Interfaces; -use LbilTech\TelegramGitNotifier\Constants\EventConstant; use Symfony\Component\HttpFoundation\Request; interface EventInterface { -// /** -// * Validate access event before send notify -// * -// * @param string $platform Source code platform (GitHub, GitLab) -// * @param string $event Event name (push, pull_request) -// * @param $payload -// * -// * @return bool -// */ -// public function validateAccessEvent( -// string $platform, -// string $event, -// $payload -// ): bool; - /** * Get action name of event from payload data * diff --git a/src/Models/Event.php b/src/Models/Event.php index c223f56..a6a8287 100644 --- a/src/Models/Event.php +++ b/src/Models/Event.php @@ -6,7 +6,7 @@ class Event { - public array $eventConfig = []; + private array $eventConfig = []; public string $platform = EventConstant::DEFAULT_PLATFORM; @@ -30,6 +30,14 @@ public function setPlatformFile(string $platformFile): void $this->platformFile = $platformFile; } + /** + * @return array + */ + public function getEventConfig(): array + { + return $this->eventConfig; + } + /** * Set event config * diff --git a/src/Models/Setting.php b/src/Models/Setting.php index 11bc475..6c07913 100644 --- a/src/Models/Setting.php +++ b/src/Models/Setting.php @@ -6,7 +6,7 @@ class Setting { - public array $settings = []; + private array $settings = []; private string $settingFile = ''; diff --git a/src/Objects/Validator.php b/src/Objects/Validator.php index 77969ce..944529d 100644 --- a/src/Objects/Validator.php +++ b/src/Objects/Validator.php @@ -20,7 +20,16 @@ public function __construct(Setting $setting, Event $event) $this->event = $event; } - public function accessEvent( + /** + * Validate is access event before send notify + * + * @param string $platform Source code platform (GitHub, GitLab) + * @param string $event Event name (push, pull_request) + * @param $payload + * + * @return bool + */ + public function isAccessEvent( string $platform, string $event, $payload @@ -34,7 +43,7 @@ public function accessEvent( } $this->event->setEventConfig($platform); - $eventConfig = $this->event->eventConfig[tgn_convert_event_name($event)] ?? false; + $eventConfig = $this->event->getEventConfig()[tgn_convert_event_name($event)] ?? false; $action = $this->getActionOfEvent($payload); if (!empty($action) && isset($eventConfig[$action])) { From 970fd0e9b2d7331b2907981aff9312e138cfa9ca Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Tue, 17 Oct 2023 22:51:03 +0700 Subject: [PATCH 06/10] fix: update phpdoc interfaces and change the request type for send notification method --- src/Interfaces/EventInterface.php | 3 ++- src/Interfaces/Structures/AppInterface.php | 10 +++++++++ .../Structures/NotificationInterface.php | 7 +++++-- src/Structures/Notification.php | 21 +++++++------------ src/Trait/EventSettingTrait.php | 4 ++-- 5 files changed, 26 insertions(+), 19 deletions(-) diff --git a/src/Interfaces/EventInterface.php b/src/Interfaces/EventInterface.php index fdbb2b4..846a260 100644 --- a/src/Interfaces/EventInterface.php +++ b/src/Interfaces/EventInterface.php @@ -2,6 +2,7 @@ namespace LbilTech\TelegramGitNotifier\Interfaces; +use LbilTech\TelegramGitNotifier\Trait\ActionEventTrait; use Symfony\Component\HttpFoundation\Request; interface EventInterface @@ -12,7 +13,7 @@ interface EventInterface * @param $payload * * @return string - * @see EventTrait::getActionOfEvent() + * @see ActionEventTrait::getActionOfEvent() */ public function getActionOfEvent($payload): string; diff --git a/src/Interfaces/Structures/AppInterface.php b/src/Interfaces/Structures/AppInterface.php index a8a70c7..13f0786 100644 --- a/src/Interfaces/Structures/AppInterface.php +++ b/src/Interfaces/Structures/AppInterface.php @@ -15,6 +15,7 @@ interface AppInterface * * @return void * @throws MessageIsEmptyException + * @see App::sendMessage() */ public function sendMessage( string $message = '', @@ -29,6 +30,7 @@ public function sendMessage( * * @return void * @throws EntryNotFoundException + * @see App::sendPhoto() */ public function sendPhoto(string $photo = '', string $caption = ''): void; @@ -39,6 +41,7 @@ public function sendPhoto(string $photo = '', string $caption = ''): void; * * @return void * @throws MessageIsEmptyException + * @see App::answerCallbackQuery() */ public function answerCallbackQuery(string $text = null): void; @@ -49,6 +52,7 @@ public function answerCallbackQuery(string $text = null): void; * @param array $options * * @return void + * @see App::editMessageText() */ public function editMessageText( ?string $text = null, @@ -61,6 +65,7 @@ public function editMessageText( * @param array $options * * @return void + * @see App::editMessageReplyMarkup() */ public function editMessageReplyMarkup(array $options = []): void; @@ -68,6 +73,7 @@ public function editMessageReplyMarkup(array $options = []): void; * Get the text from callback message * * @return string + * @see App::getCallbackTextMessage() */ public function getCallbackTextMessage(): string; @@ -77,6 +83,7 @@ public function getCallbackTextMessage(): string; * @param array $options * * @return array + * @see App::setCallbackContentMessage() */ public function setCallbackContentMessage(array $options = []): array; @@ -84,6 +91,7 @@ public function setCallbackContentMessage(array $options = []): array; * @param string $chatId * * @return void + * @see App::setCurrentChatBotId() */ public function setCurrentChatBotId(string $chatId): void; @@ -91,6 +99,7 @@ public function setCurrentChatBotId(string $chatId): void; * Get the username of the bot * * @return string|null + * @see App::getBotName() */ public function getBotName(): ?string; @@ -98,6 +107,7 @@ public function getBotName(): ?string; * Get the command message from a telegram * * @return string + * @see App::getCommandMessage() */ public function getCommandMessage(): string; } diff --git a/src/Interfaces/Structures/NotificationInterface.php b/src/Interfaces/Structures/NotificationInterface.php index f34919d..418d1ca 100644 --- a/src/Interfaces/Structures/NotificationInterface.php +++ b/src/Interfaces/Structures/NotificationInterface.php @@ -16,6 +16,7 @@ interface NotificationInterface * * @return void * @throws InvalidViewTemplateException + * @see Notification::accessDenied() */ public function accessDenied( string $chatId = null, @@ -30,19 +31,21 @@ public function accessDenied( * * @return mixed|void * @throws InvalidViewTemplateException + * @see Notification::setPayload() */ public function setPayload(Request $request, string $event); /** * Send notification to telegram * - * @param string $chatId * @param string|null $message + * @param array $options * * @return bool * @throws SendNotificationException + * @see Notification::sendNotify() */ - public function sendNotify(string $chatId, string $message = null): bool; + public function sendNotify(string $message = null, array $options = []): bool; /** * Get action name of event from payload data diff --git a/src/Structures/Notification.php b/src/Structures/Notification.php index b9e2508..25661e5 100644 --- a/src/Structures/Notification.php +++ b/src/Structures/Notification.php @@ -62,25 +62,18 @@ private function setMessage(string $typeEvent): void ]); } - public function sendNotify(string $chatId, string $message = null): bool + public function sendNotify(string $message = null, array $options = []): bool { - if (!is_null($message)) { - $this->message = $message; - } + $this->message = $message ?? $this->message; - $queryParams = [ - 'chat_id' => $chatId, - 'disable_web_page_preview' => 1, - 'parse_mode' => 'html', - 'text' => $this->message - ]; + $queryParams = array_merge($this->createTelegramBaseContent(), ['text' => $this->message], $options); - $url = 'https://api.telegram.org/bot' - . config('telegram-git-notifier.bot.token') . '/sendMessage' - . '?' . http_build_query($queryParams); + $url = 'https://api.telegram.org/bot' . config('telegram-git-notifier.bot.token') . '/sendMessage'; try { - $response = $this->client->request('GET', $url); + $response = $this->client->request('POST', $url, [ + 'form_params' => $queryParams + ]); if ($response->getStatusCode() === 200) { return true; diff --git a/src/Trait/EventSettingTrait.php b/src/Trait/EventSettingTrait.php index 369766d..7e4f7fa 100644 --- a/src/Trait/EventSettingTrait.php +++ b/src/Trait/EventSettingTrait.php @@ -14,8 +14,8 @@ public function eventMarkup( $replyMarkup = $replyMarkupItem = []; $this->event->setEventConfig($platform); - $events = $parentEvent === null ? $this->event->eventConfig - : $this->event->eventConfig[$parentEvent]; + $events = $parentEvent === null ? $this->event->getEventConfig() + : $this->event->getEventConfig()[$parentEvent]; foreach ($events as $key => $value) { if (count($replyMarkupItem) === SettingConstant::BTN_LINE_ITEM_COUNT) { From 7415e7514e70e860bbd3a36fed4f1d3192b0c299 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Tue, 17 Oct 2023 23:58:21 +0700 Subject: [PATCH 07/10] fix: some traits and add docs to configs --- config/tg-notifier.php | 14 +++++-- src/Bot.php | 66 ++------------------------------- src/Structures/Notification.php | 4 +- src/Structures/TelegramBot.php | 33 +++++++++++++++++ src/Trait/BotSettingTrait.php | 25 +++++++++++++ 5 files changed, 73 insertions(+), 69 deletions(-) create mode 100644 src/Structures/TelegramBot.php diff --git a/config/tg-notifier.php b/config/tg-notifier.php index abf5021..6b78f2a 100644 --- a/config/tg-notifier.php +++ b/config/tg-notifier.php @@ -11,10 +11,14 @@ 'bot' => [ 'token' => $_ENV['TELEGRAM_BOT_TOKEN'] ?? '', 'chat_id' => $_ENV['TELEGRAM_BOT_CHAT_ID'] ?? '', - 'notify_chat_ids' => explode( - ',', - $_ENV['TELEGRAM_NOTIFY_CHAT_IDS'] ?? '' - ), + + /** + * Set the chat ids that will receive notifications + * You can add the owner bot id, group id, ... ( And please use semicolon ";" to separate chat ids ) + * The environment variable is expected to be in the format: + * "chat_id1;chat_id2,thread_id2;chat_id3,thread_id3;..." + */ + 'notify_chat_ids' => $_ENV['TELEGRAM_NOTIFY_CHAT_IDS'] ?? '', ], 'author' => [ @@ -24,6 +28,7 @@ 'https://github.com/lbiltech/telegram-git-notifier', ], + /** Set the path to the data file */ 'data_file' => [ 'setting' => $_ENV['TGN_PATH_SETTING'] ?? 'storage/json/tgn/tgn-settings.json', @@ -36,6 +41,7 @@ ], ], + /** Set the path to the view file */ 'view' => [ 'path' => $_ENV['TGN_VIEW_PATH'] ?? 'resources/views', diff --git a/src/Bot.php b/src/Bot.php index dfe9a5b..445c98a 100644 --- a/src/Bot.php +++ b/src/Bot.php @@ -6,10 +6,10 @@ use LbilTech\TelegramGitNotifier\Interfaces\BotInterface; use LbilTech\TelegramGitNotifier\Interfaces\Structures\AppInterface; use LbilTech\TelegramGitNotifier\Interfaces\EventInterface; -use LbilTech\TelegramGitNotifier\Interfaces\Structures\SettingInterface; use LbilTech\TelegramGitNotifier\Models\Event; use LbilTech\TelegramGitNotifier\Models\Setting; use LbilTech\TelegramGitNotifier\Structures\App; +use LbilTech\TelegramGitNotifier\Structures\TelegramBot; use LbilTech\TelegramGitNotifier\Trait\BotSettingTrait; use LbilTech\TelegramGitNotifier\Trait\EventSettingTrait; use LbilTech\TelegramGitNotifier\Trait\EventTrait; @@ -18,6 +18,8 @@ class Bot implements AppInterface, BotInterface, EventInterface { use App; + use TelegramBot; + use EventTrait; use BotSettingTrait; use EventSettingTrait; @@ -43,66 +45,4 @@ public function __construct( $this->setting = $setting ?? new Setting(); $this->updateSetting($settingFile); } - - public function updateSetting(?string $settingFile = null): void - { - if ($this->setting->getSettingFile()) { - return; - } - $settingFile = $settingFile ?? config('telegram-git-notifier.data_file.setting'); - $this->setting->setSettingFile($settingFile); - $this->setting->setSettingConfig(); - } - - public function setMyCommands( - array $menuCommand, - ?string $view = null - ): void { - $this->telegram->setMyCommands([ - 'commands' => json_encode($menuCommand) - ]); - $this->sendMessage( - view( - $view ?? - config('telegram-git-notifier.view.tools.set_menu_cmd') - ) - ); - } - - public function isCallback(): bool - { - if ($this->telegram->getUpdateType() === Telegram::CALLBACK_QUERY) { - return true; - } - - return false; - } - - public function isMessage(): bool - { - if ($this->telegram->getUpdateType() === Telegram::MESSAGE) { - return true; - } - - return false; - } - - public function isOwner(): bool - { - if ($this->telegram->ChatID() == $this->chatBotId) { - return true; - } - - return false; - } - - public function isNotifyChat(): bool - { - $chatIds = config('telegram-git-notifier.bot.notify_chat_ids'); - if (in_array($this->telegram->ChatID(), $chatIds)) { - return true; - } - - return false; - } } diff --git a/src/Structures/Notification.php b/src/Structures/Notification.php index 25661e5..cfdbef3 100644 --- a/src/Structures/Notification.php +++ b/src/Structures/Notification.php @@ -18,7 +18,7 @@ public function accessDenied( string $viewTemplate = null, ): void { $this->telegram->sendMessage([ - 'chat_id' => config('telegram-git-notifier.bot.chat_id'), + 'chat_id' => $this->chatBotId, 'text' => view( $viewTemplate ?? config('telegram-git-notifier.view.globals.access_denied'), ['chatId' => $chatId] @@ -64,7 +64,7 @@ private function setMessage(string $typeEvent): void public function sendNotify(string $message = null, array $options = []): bool { - $this->message = $message ?? $this->message; + $this->message = !empty($message) ? $message : $this->message; $queryParams = array_merge($this->createTelegramBaseContent(), ['text' => $this->message], $options); diff --git a/src/Structures/TelegramBot.php b/src/Structures/TelegramBot.php new file mode 100644 index 0000000..af865dd --- /dev/null +++ b/src/Structures/TelegramBot.php @@ -0,0 +1,33 @@ +telegram->getUpdateType() === Telegram::CALLBACK_QUERY; + } + + public function isMessage(): bool + { + return $this->telegram->getUpdateType() === Telegram::MESSAGE; + } + + public function isOwner(): bool + { + return $this->telegram->ChatID() == $this->chatBotId; + } + + public function isNotifyChat(): bool + { + $chatIds = config('telegram-git-notifier.bot.notify_chat_ids'); + if (in_array($this->telegram->ChatID(), $chatIds)) { + return true; + } + + return false; + } +} diff --git a/src/Trait/BotSettingTrait.php b/src/Trait/BotSettingTrait.php index 3d2593f..ef0ad2d 100644 --- a/src/Trait/BotSettingTrait.php +++ b/src/Trait/BotSettingTrait.php @@ -6,6 +6,31 @@ trait BotSettingTrait { + public function updateSetting(?string $settingFile = null): void + { + if ($this->setting->getSettingFile()) { + return; + } + $settingFile = $settingFile ?? config('telegram-git-notifier.data_file.setting'); + $this->setting->setSettingFile($settingFile); + $this->setting->setSettingConfig(); + } + + public function setMyCommands( + array $menuCommand, + ?string $view = null + ): void { + $this->telegram->setMyCommands([ + 'commands' => json_encode($menuCommand) + ]); + $this->sendMessage( + view( + $view ?? + config('telegram-git-notifier.view.tools.set_menu_cmd') + ) + ); + } + public function settingHandle(?string $view = null): void { $this->sendMessage( From 3dbc9d66b497fb274ca4493383173cc9f258616a Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Wed, 18 Oct 2023 18:03:11 +0700 Subject: [PATCH 08/10] feat: add some methods to send notification for topic in super chat group --- config/tg-notifier.php | 7 +++++-- src/Constants/NotificationConstant.php | 15 +++++++++++++++ .../Structures/NotificationInterface.php | 7 +++++++ src/Interfaces/WebhookInterface.php | 14 ++++++++++++++ src/Notifier.php | 18 ++++++++++++++++++ src/Webhook.php | 14 ++++++++++++++ 6 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 src/Constants/NotificationConstant.php diff --git a/config/tg-notifier.php b/config/tg-notifier.php index 6b78f2a..f265ba7 100644 --- a/config/tg-notifier.php +++ b/config/tg-notifier.php @@ -14,9 +14,12 @@ /** * Set the chat ids that will receive notifications - * You can add the owner bot id, group id, ... ( And please use semicolon ";" to separate chat ids ) + * You can add the owner bot id, group id, ... + * ( Please use semicolon ";" to separate chat ids ) + * ( And use colon ":" to separate chat id and thread id ) + * ( And use comma "," if you want to add multiple thread ids ) * The environment variable is expected to be in the format: - * "chat_id1;chat_id2,thread_id2;chat_id3,thread_id3;..." + * "chat_id1;chat_id2:thread_id2;chat_id3:thread_id3_1,thread_id3_2;..." */ 'notify_chat_ids' => $_ENV['TELEGRAM_NOTIFY_CHAT_IDS'] ?? '', ], diff --git a/src/Constants/NotificationConstant.php b/src/Constants/NotificationConstant.php new file mode 100644 index 0000000..27d6df5 --- /dev/null +++ b/src/Constants/NotificationConstant.php @@ -0,0 +1,15 @@ +client = $client ?? new Client(); } + + function parseNotifyChatIds(): array + { + $chatData = explode( + NotificationConstant::CHAT_ID_PAIRS_SEPARATOR, + config('telegram-git-notifier.bot.notify_chat_ids') + ); + $chatThreadMapping = []; + + foreach ($chatData as $data) { + [$chatId, $threadIds] = explode(NotificationConstant::CHAT_THREAD_ID_SEPARATOR, $data) + [null, null]; + $chatThreadMapping[$chatId] = $threadIds + ? explode(NotificationConstant::THREAD_ID_SEPARATOR, $threadIds) + : []; + } + return $chatThreadMapping; + } } diff --git a/src/Webhook.php b/src/Webhook.php index 1782adc..1fa81a1 100644 --- a/src/Webhook.php +++ b/src/Webhook.php @@ -33,4 +33,18 @@ public function deleteWebHook(): false|string return file_get_contents($url); } + + public function getWebHookInfo(): false|string + { + $url = "https://api.telegram.org/bot{$this->token}/getWebhookInfo"; + + return file_get_contents($url); + } + + public function getUpdates(): false|string + { + $url = "https://api.telegram.org/bot{$this->token}/getUpdates"; + + return file_get_contents($url); + } } From 7645d1fa9c488c355fb3eaaad91510d40d7bd632 Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Wed, 18 Oct 2023 22:03:04 +0700 Subject: [PATCH 09/10] fix: update php doc and style code --- config/tg-notifier.php | 9 ++++++--- src/Notifier.php | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/config/tg-notifier.php b/config/tg-notifier.php index f265ba7..6e4e5cb 100644 --- a/config/tg-notifier.php +++ b/config/tg-notifier.php @@ -15,9 +15,12 @@ /** * Set the chat ids that will receive notifications * You can add the owner bot id, group id, ... - * ( Please use semicolon ";" to separate chat ids ) - * ( And use colon ":" to separate chat id and thread id ) - * ( And use comma "," if you want to add multiple thread ids ) + * ------------------------------------------------------- + * Note: + * Please use semicolon ";" to separate chat ids + * And use colon ":" to separate chat id and thread id + * And use comma "," if you want to add multiple thread ids + * ------------------------------------------------------- * The environment variable is expected to be in the format: * "chat_id1;chat_id2:thread_id2;chat_id3:thread_id3_1,thread_id3_2;..." */ diff --git a/src/Notifier.php b/src/Notifier.php index 39dd322..33d9a0c 100644 --- a/src/Notifier.php +++ b/src/Notifier.php @@ -42,7 +42,7 @@ public function __construct( $this->client = $client ?? new Client(); } - function parseNotifyChatIds(): array + public function parseNotifyChatIds(): array { $chatData = explode( NotificationConstant::CHAT_ID_PAIRS_SEPARATOR, From 5a4c9d239b7f05f4ac6c8c5963147f23271b912b Mon Sep 17 00:00:00 2001 From: Tan Nguyen Date: Thu, 19 Oct 2023 09:48:32 +0700 Subject: [PATCH 10/10] add comment for config --- config/tg-notifier.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/config/tg-notifier.php b/config/tg-notifier.php index 6e4e5cb..9127043 100644 --- a/config/tg-notifier.php +++ b/config/tg-notifier.php @@ -4,7 +4,10 @@ 'telegram-git-notifier' => [ 'app' => [ 'name' => $_ENV['TGN_APP_NAME'] ?? 'Telegram Git Notifier', + + // Required for the bot to work properly 'url' => $_ENV['TGN_APP_URL'] ?? 'http://localhost:3000', + 'timezone' => $_ENV['TIMEZONE'] ?? 'Asia/Ho_Chi_Minh', ],