Files
nodehub/ops/AdminNotice.php

67 lines
3.1 KiB
PHP

<?php
declare(strict_types=1);
namespace LegacyOperations;
final class AdminNotice
{
public static function bot(string $code): string
{
return match ($code) {
'log' => 'log',
'warn', 'warning' => 'warning',
'fail', 'error' => 'error',
'notify', 'notification' => 'notification',
'base', 'admin', '' => 'base',
default => throw new \DomainException('Unregistered operations notification category'),
};
}
public static function submit(string $projectRoot, array $data, string $eventKey): array
{
$target = (string) ($data['sChatCode'] ?? '');
if (!in_array($target, ['', 'base', 'admin'], true) || !empty($data['iChatId']) || !empty($data['sBotToken'])) {
throw new \DomainException('Explicit Telegram recipients require their own publisher');
}
if (!empty($data['sPhotoUrl']) || !empty($data['sFileUrl'])) {
throw new \DomainException('Attachments require their original publisher');
}
$configPath = '/etc/telehub-operations/' . hash('sha256', $projectRoot) . '.json';
$config = json_decode((string) @file_get_contents($configPath), true, 16, JSON_THROW_ON_ERROR);
$bot = self::bot($data['sBotCode'] ?? '');
$text = (string) ($data['sMsg'] ?? '');
if (trim($text) === '') {
throw new \DomainException('Empty operations notification');
}
$title = '【' . $config['project'] . '/生产 - 运行通知】' . "\n";
$room = 4096 - mb_strlen($title, 'UTF-8');
$receipts = [];
foreach (mb_str_split($text, $room, 'UTF-8') as $part => $body) {
$payload = json_encode(['bot' => $bot, 'target' => 'base', 'text' => $title . $body], JSON_THROW_ON_ERROR);
$http = curl_init('https://telehub.gemcook.net/api/v1/messages');
curl_setopt_array($http, [
CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 4, CURLOPT_TIMEOUT => 15, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json', 'Accept: application/json',
'Authorization: Bearer ' . $config['key'],
'Idempotency-Key: ' . $eventKey . '.' . $part,
],
]);
$response = curl_exec($http);
$status = curl_getinfo($http, CURLINFO_RESPONSE_CODE);
curl_close($http);
$receipt = is_string($response) ? (json_decode($response, true)['data'] ?? []) : [];
if (!in_array($status, [200, 202], true) || empty($receipt['id'])) {
throw new \RuntimeException('TeleHub submission unconfirmed (HTTP ' . $status . ')');
}
if (in_array($receipt['status'] ?? '', ['failed', 'uncertain', 'cancelled'], true)) {
throw new \RuntimeException('TeleHub delivery requires review: ' . $receipt['id']);
}
$receipts[] = $receipt['id'];
}
return $receipts;
}
}