Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions src/Controllers/TelegramController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
class TelegramController
{
use ViewResponseTrait;

private TelegramService $telegramService;
private Telegram $module;
private TelegramConfigService $telegramConfigService;
Expand Down Expand Up @@ -49,7 +49,7 @@ public function configsIndex(ServerRequestInterface $request): array
$configs = $this->telegramConfigService->getAllConfigs();
$users = $this->telegramConfigService->getAvailableUsers();
$trees = $this->telegramConfigService->getAvailableTrees();

return [
'configs' => $configs,
'users' => $users,
Expand All @@ -72,7 +72,7 @@ public function configAdd(ServerRequestInterface $request): array
$events = \Tywed\Webtrees\Module\Telegram\CustomOnThisDayModule::getAllEvents();
$defaultEvents = \Tywed\Webtrees\Module\Telegram\CustomOnThisDayModule::getDefaultEvents();
$eventLabels = \Tywed\Webtrees\Module\Telegram\CustomOnThisDayModule::getEventLabels();

return [
'config' => null,
'users' => $users,
Expand Down Expand Up @@ -101,13 +101,13 @@ public function configEdit(ServerRequestInterface $request, string $id): array
FlashMessages::addMessage(I18N::translate('Configuration not found'), 'danger');
return [];
}

$users = $this->telegramConfigService->getAvailableUsers();
$trees = $this->telegramConfigService->getAvailableTrees();
$events = \Tywed\Webtrees\Module\Telegram\CustomOnThisDayModule::getAllEvents();
$defaultEvents = \Tywed\Webtrees\Module\Telegram\CustomOnThisDayModule::getDefaultEvents();
$eventLabels = \Tywed\Webtrees\Module\Telegram\CustomOnThisDayModule::getEventLabels();

return [
'config' => $config,
'users' => $users,
Expand All @@ -131,19 +131,19 @@ public function configEdit(ServerRequestInterface $request, string $id): array
public function configStore(ServerRequestInterface $request): ResponseInterface
{
$data = Validator::parsedBody($request);

$name = $data->string('name', '');
$bot_token = $data->string('bot_token', '');
$chat_id = $data->string('chat_id', '');
$user_id = $data->string('user_id', '');
$tree_id = $data->string('tree_id', '');

// Validate required fields
if (empty($name) || empty($bot_token) || empty($chat_id) || empty($user_id) || empty($tree_id)) {
FlashMessages::addMessage(I18N::translate('Please fill in all required fields'), 'danger');
return redirect(route('module', ['module' => $this->module->name(), 'action' => 'ConfigAdd']));
}

$config = [
'id' => uniqid(),
'name' => $name,
Expand All @@ -159,10 +159,10 @@ public function configStore(ServerRequestInterface $request): ResponseInterface
'start_message' => $data->string('start_message', ''),
'end_message' => $data->string('end_message', ''),
];

$this->telegramConfigService->saveConfig($config);
FlashMessages::addMessage(I18N::translate('Configuration added successfully'), 'success');

return redirect(route('module', ['module' => $this->module->name(), 'action' => 'Admin']));
}

Expand All @@ -176,19 +176,19 @@ public function configStore(ServerRequestInterface $request): ResponseInterface
public function configUpdate(ServerRequestInterface $request, string $id): ResponseInterface
{
$data = Validator::parsedBody($request);

$name = $data->string('name', '');
$bot_token = $data->string('bot_token', '');
$chat_id = $data->string('chat_id', '');
$user_id = $data->string('user_id', '');
$tree_id = $data->string('tree_id', '');

// Validate required fields
if (empty($name) || empty($bot_token) || empty($chat_id) || empty($user_id) || empty($tree_id)) {
FlashMessages::addMessage(I18N::translate('Please fill in all required fields'), 'danger');
return redirect(route('module', ['module' => $this->module->name(), 'action' => 'ConfigEdit', 'id' => $id]));
}

$config = [
'id' => $id,
'name' => $name,
Expand All @@ -204,10 +204,10 @@ public function configUpdate(ServerRequestInterface $request, string $id): Respo
'start_message' => $data->string('start_message', ''),
'end_message' => $data->string('end_message', ''),
];

$this->telegramConfigService->saveConfig($config, $id);
FlashMessages::addMessage(I18N::translate('Configuration updated successfully'), 'success');

return redirect(route('module', ['module' => $this->module->name(), 'action' => 'Admin']));
}

Expand All @@ -222,7 +222,7 @@ public function configDelete(ServerRequestInterface $request, string $id): Respo
{
$this->telegramConfigService->deleteConfig($id);
FlashMessages::addMessage(I18N::translate('Configuration deleted successfully'), 'success');

return redirect(route('module', ['module' => $this->module->name(), 'action' => 'Admin']));
}

Expand Down
2 changes: 1 addition & 1 deletion src/CustomOnThisDayModule.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,4 @@ public static function getEventLabels(): array

return $all_events;
}
}
}
2 changes: 1 addition & 1 deletion src/Helpers/AppHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ public static function get(string $class)

throw new Exception('Can not find container resolver');
}
}
}
6 changes: 2 additions & 4 deletions src/RequestHandlers/TelegramChangesCronJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface
];
continue;
}

// Daily guard for changes
$lastChangesLaunchJd = $config['last_changes_launch_jd'] ?? null;
if ($lastChangesLaunchJd === $startJd) {
Expand All @@ -78,7 +78,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface
];
continue;
}

// Prepare context (user, language, tree) via service
$context = $this->telegramService->prepareCronContext(
$config,
Expand Down Expand Up @@ -140,5 +140,3 @@ function (string $message) use (&$results, $configId): void {
]);
}
}


16 changes: 8 additions & 8 deletions src/RequestHandlers/TelegramCronJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,10 @@ function (string $message) use (&$results, $configId): void {

$events = $config['events'] ?? CustomOnThisDayModule::getDefaultEvents();
$event_array = is_array($events) ? $events : (is_string($events) ? explode(',', $events) : []);

// Normalize event types: trim whitespace and filter empty values
$event_array = array_filter(array_map('trim', $event_array), fn($e) => $e !== '');

$filter = $config['filter'] ?? true;

$factList = $this->telegramService->getTodayFacts($event_array, $startJd, $startJd, $tree, $filter);
Expand All @@ -140,7 +140,7 @@ function (string $message) use (&$results, $configId): void {
}

Auth::logout();

// Update last launch markers for this configuration (successful run)
$config['last_launch'] = $currentTimestamp; // keep timestamp for UI display
$config['last_launch_jd'] = $startJd; // use JD for daily guard
Expand All @@ -149,20 +149,20 @@ function (string $message) use (&$results, $configId): void {

} catch (\Exception $e) {
Auth::logout(); // Ensure logout even on error

// Check if this is a Telegram API error (not a general error)
$isTelegramError = strpos($e->getMessage(), 'Telegram') !== false ||
$isTelegramError = strpos($e->getMessage(), 'Telegram') !== false ||
strpos($e->getMessage(), 'bot') !== false ||
strpos($e->getMessage(), 'chat') !== false ||
strpos($e->getMessage(), 'token') !== false;

if ($isTelegramError) {
// Update last_error for Telegram-related errors
$config['last_error'] = $e->getMessage();
$config['last_error_date'] = $currentTimestamp;
$this->telegramConfigService->saveConfig($config, $configId);
}

$results[$configId] = [
'success' => false,
'message' => "Configuration \"{$configName}\": Error - " . $e->getMessage(),
Expand All @@ -175,4 +175,4 @@ function (string $message) use (&$results, $configId): void {
'results' => $results,
]);
}
}
}
24 changes: 12 additions & 12 deletions src/Services/TelegramConfigService.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,19 @@ public function __construct(Telegram $module, UserService $userService, TreeServ
public function getAllConfigs(): array
{
$configs = json_decode($this->module->getPreference(Telegram::CUSTOM_MODULE_CONFIGS, '[]'), true);

// Ensure configs is always an array
if (!is_array($configs)) {
$configs = [];
}

// Check if migration has already been done
$migrationDone = $this->module->getPreference('telegram_migration_done', '0') === '1';

if (!$migrationDone) {
// Migrate existing configs to new structure if needed
$configs = $this->migrateConfigs($configs);

// Mark migration as done
$this->module->setPreference('telegram_migration_done', '1');
}
Expand Down Expand Up @@ -112,12 +112,12 @@ public function getAllConfigs(): array
private function migrateConfigs(array $configs): array
{
$migrated = false;

foreach ($configs as $key => $config) {
// Check if config needs migration (has old field names)
if (isset($config['telegram_token']) || isset($config['telegram_id']) || isset($config['user']) || isset($config['tree'])) {
$newConfig = $config;

// Migrate field names
if (isset($config['telegram_token'])) {
$newConfig['bot_token'] = $config['telegram_token'];
Expand All @@ -135,7 +135,7 @@ private function migrateConfigs(array $configs): array
$newConfig['tree_id'] = $config['tree'];
unset($newConfig['tree']);
}

// Add missing fields
if (!isset($newConfig['enabled'])) {
$newConfig['enabled'] = true;
Expand Down Expand Up @@ -167,17 +167,17 @@ private function migrateConfigs(array $configs): array
if (!isset($newConfig['last_error_date'])) {
$newConfig['last_error_date'] = null;
}

$configs[$key] = $newConfig;
$migrated = true;
}
}

// Save migrated configs if any changes were made
if ($migrated) {
$this->saveAllConfigs($configs);
}

return $configs;
}

Expand All @@ -200,7 +200,7 @@ private function saveAllConfigs(array $configs): void
public function getConfigById(string $id): ?array
{
$configs = $this->getAllConfigs();

foreach ($configs as $config) {
if ($config['id'] === $id) {
return $config;
Expand Down Expand Up @@ -236,7 +236,7 @@ public function saveConfig(array $configData, ?string $id = null): array
if (!isset($configData['id'])) {
$configData['id'] = uniqid();
}

// Check if ID already exists
foreach ($configs as $config) {
if ($config['id'] === $configData['id']) {
Expand All @@ -245,7 +245,7 @@ public function saveConfig(array $configData, ?string $id = null): array
break;
}
}

$configs[] = $configData;
$this->saveAllConfigs($configs);
return $configData;
Expand Down
6 changes: 3 additions & 3 deletions src/Services/TelegramService.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public function generateTelegramMessage(Collection $factList, array $config = nu
if ($factType === '' || !isset($types[$factType])) {
continue;
}

if (!isset($messages[$factType])) {
$messages[$factType] = "🔸 <b>{$types[$factType]}</b>:\n";
}
Expand Down Expand Up @@ -220,7 +220,7 @@ public function generateTelegramMessage(Collection $factList, array $config = nu
$eventOrder = is_array($events)
? $events
: (is_string($events) ? explode(',', $events) : []);

// Normalize event types: trim whitespace and filter empty values
$eventOrder = array_filter(array_map('trim', $eventOrder), fn($e) => $e !== '');

Expand Down Expand Up @@ -399,4 +399,4 @@ public function sendTelegramMessage(string $telegramToken, string $telegramId, s
throw $e;
}
}
}
}
Loading