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\Theming\ThemeEvents;
10 use BookStack\Users\Models\User;
11 use BookStack\Util\SsrUrlValidator;
12 use Illuminate\Bus\Queueable;
13 use Illuminate\Contracts\Queue\ShouldQueue;
14 use Illuminate\Foundation\Bus\Dispatchable;
15 use Illuminate\Queue\InteractsWithQueue;
16 use Illuminate\Queue\SerializesModels;
17 use Illuminate\Support\Facades\Http;
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()
57 (new SsrUrlValidator())->ensureAllowed($this->webhook->endpoint);
59 $response = Http::asJson()
60 ->withOptions(['allow_redirects' => ['strict' => true]])
61 ->timeout($this->webhook->timeout)
62 ->post($this->webhook->endpoint, $this->webhookData);
63 } catch (\Exception $exception) {
64 $lastError = $exception->getMessage();
65 Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with error \"{$lastError}\"");
68 if (isset($response) && $response->failed()) {
69 $lastError = "Response status from endpoint was {$response->status()}";
70 Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with status {$response->status()}");
73 $this->webhook->last_called_at = now();
75 $this->webhook->last_errored_at = now();
76 $this->webhook->last_error = $lastError;
79 $this->webhook->save();