3 namespace BookStack\Activity;
5 use BookStack\Activity\Models\Loggable;
6 use BookStack\Activity\Models\Webhook;
7 use BookStack\Activity\Tools\WebhookFormatter;
8 use BookStack\Facades\Theme;
9 use BookStack\Http\HttpRequestService;
10 use BookStack\Theming\ThemeEvents;
11 use BookStack\Users\Models\User;
12 use BookStack\Util\SsrUrlValidator;
13 use Illuminate\Bus\Queueable;
14 use Illuminate\Contracts\Queue\ShouldQueue;
15 use Illuminate\Foundation\Bus\Dispatchable;
16 use Illuminate\Queue\InteractsWithQueue;
17 use Illuminate\Queue\SerializesModels;
18 use Illuminate\Support\Facades\Log;
20 class DispatchWebhookJob implements ShouldQueue
23 use InteractsWithQueue;
27 protected Webhook $webhook;
28 protected User $initiator;
29 protected int $initiatedTime;
30 protected array $webhookData;
33 * Create a new job instance.
37 public function __construct(Webhook $webhook, string $event, Loggable|string $detail)
39 $this->webhook = $webhook;
40 $this->initiator = user();
41 $this->initiatedTime = time();
43 $themeResponse = Theme::dispatch(ThemeEvents::WEBHOOK_CALL_BEFORE, $event, $this->webhook, $detail, $this->initiator, $this->initiatedTime);
44 $this->webhookData = $themeResponse ?? WebhookFormatter::getDefault($event, $this->webhook, $detail, $this->initiator, $this->initiatedTime)->format();
52 public function handle(HttpRequestService $http)
57 (new SsrUrlValidator())->ensureAllowed($this->webhook->endpoint);
59 $client = $http->buildClient($this->webhook->timeout, [
60 'connect_timeout' => 10,
61 'allow_redirects' => ['strict' => true],
64 $response = $client->sendRequest($http->jsonRequest('POST', $this->webhook->endpoint, $this->webhookData));
65 $statusCode = $response->getStatusCode();
67 if ($statusCode >= 400) {
68 $lastError = "Response status from endpoint was {$statusCode}";
69 Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with status {$statusCode}");
71 } catch (\Exception $error) {
72 $lastError = $error->getMessage();
73 Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with error \"{$lastError}\"");
76 $this->webhook->last_called_at = now();
78 $this->webhook->last_errored_at = now();
79 $this->webhook->last_error = $lastError;
82 $this->webhook->save();