TelegramChannelMessageService.php 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. <?php
  2. namespace App\Services;
  3. use Carbon\CarbonImmutable;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Validator;
  6. use Illuminate\Validation\ValidationException;
  7. class TelegramChannelMessageService
  8. {
  9. private const TABLE = 'telegram_channel_messages';
  10. public function __construct(private TelegramChannelService $channels) {}
  11. public function list(int $page): array
  12. {
  13. $items = DB::table(self::TABLE)->orderByDesc('id')->paginate(20, ['*'], 'page', $page);
  14. return ['list' => array_map($this->present(...), $items->items()), 'total' => $items->total()];
  15. }
  16. public function create(array $input): array
  17. {
  18. $fields = Validator::make($input, [
  19. 'channel_id' => 'required|integer|min:1',
  20. 'scheduled_at' => 'nullable|date_format:Y-m-d\TH:i:sP',
  21. 'is_top' => 'sometimes|boolean',
  22. ])->validate();
  23. $message = TelegramChannelService::message($input);
  24. $channel = $this->channels->detail((int) $fields['channel_id']);
  25. if (!$channel['enabled']) {
  26. throw ValidationException::withMessages(['channel_id' => '请先启用频道']);
  27. }
  28. if ($channel['bot_id'] === null) {
  29. throw ValidationException::withMessages(['channel_id' => '请先为频道绑定机器人']);
  30. }
  31. $scheduled = isset($fields['scheduled_at']) ? CarbonImmutable::parse($fields['scheduled_at'])->utc() : null;
  32. if ($scheduled !== null && $scheduled->lessThanOrEqualTo(now('UTC'))) {
  33. throw ValidationException::withMessages(['scheduled_at' => '定时发送时间必须晚于当前时间']);
  34. }
  35. $id = (int) DB::table(self::TABLE)->insertGetId([
  36. 'channel_id' => $channel['id'],
  37. 'channel_name' => $channel['name'],
  38. 'target' => $channel['telegram_chat_id'] ?? $channel['chatId'],
  39. 'message' => json_encode($message, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
  40. 'is_top' => $fields['is_top'] ?? false,
  41. 'status' => 'scheduled',
  42. 'scheduled_at' => $scheduled ?? now('UTC'),
  43. 'created_at' => now('UTC'),
  44. 'updated_at' => now('UTC'),
  45. ]);
  46. if ($scheduled === null) {
  47. $this->dispatch($id);
  48. }
  49. return $this->present(DB::table(self::TABLE)->find($id));
  50. }
  51. public function cancel(int $id): void
  52. {
  53. if (!DB::table(self::TABLE)->where('id', $id)->where('status', 'scheduled')->update([
  54. 'status' => 'cancelled',
  55. 'updated_at' => now('UTC'),
  56. ])) {
  57. throw ValidationException::withMessages(['id' => '只有待发送消息可以取消']);
  58. }
  59. }
  60. public function dispatchDue(): void
  61. {
  62. DB::table(self::TABLE)->where('status', 'sending')
  63. ->where('attempted_at', '<=', now('UTC')->subMinutes(10))->update([
  64. 'status' => 'unknown', 'error' => '发送中断,结果未知,请到频道核对', 'updated_at' => now('UTC'),
  65. ]);
  66. $ids = DB::table(self::TABLE)->where('status', 'scheduled')
  67. ->where('scheduled_at', '<=', now('UTC'))->orderBy('scheduled_at')->orderBy('id')->limit(20)->pluck('id');
  68. foreach ($ids as $id) {
  69. $this->dispatch((int) $id);
  70. }
  71. }
  72. private function dispatch(int $id): void
  73. {
  74. $claimed = DB::table(self::TABLE)->where('id', $id)->where('status', 'scheduled')
  75. ->where('scheduled_at', '<=', now('UTC'))->update([
  76. 'status' => 'sending', 'attempted_at' => now('UTC'), 'updated_at' => now('UTC'),
  77. ]);
  78. if (!$claimed) {
  79. return;
  80. }
  81. $row = DB::table(self::TABLE)->find($id);
  82. try {
  83. $result = $this->channels->publishMessage(
  84. (int) $row->channel_id,
  85. json_decode($row->message, true, 512, JSON_THROW_ON_ERROR),
  86. (bool) $row->is_top,
  87. $row->target,
  88. );
  89. } catch (ValidationException $e) {
  90. $result = ['sent' => false, 'pinned' => null, 'message_id' => null, 'error' => $e->validator->errors()->first()];
  91. }
  92. DB::table(self::TABLE)->where('id', $id)->where('status', 'sending')->update([
  93. 'status' => match ($result['sent']) { true => 'sent', false => 'failed', null => 'unknown' },
  94. 'telegram_message_id' => $result['message_id'],
  95. 'pinned' => $result['pinned'],
  96. 'error' => $result['error'],
  97. 'updated_at' => now('UTC'),
  98. ]);
  99. }
  100. private function present(object $row): array
  101. {
  102. $data = (array) $row;
  103. $data['message'] = json_decode($row->message, true);
  104. $data['is_top'] = (bool) $row->is_top;
  105. $data['pinned'] = $row->pinned === null ? null : (bool) $row->pinned;
  106. foreach (['scheduled_at', 'attempted_at', 'created_at', 'updated_at'] as $key) {
  107. $data[$key] = $row->$key === null ? null : CarbonImmutable::parse($row->$key, 'UTC')->toIso8601String();
  108. }
  109. return $data;
  110. }
  111. }