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 Illuminate\Bus\Queueable;
12 use Illuminate\Contracts\Queue\ShouldQueue;
13 use Illuminate\Foundation\Bus\Dispatchable;
14 use Illuminate\Queue\InteractsWithQueue;
15 use Illuminate\Queue\SerializesModels;
16 use Illuminate\Support\Facades\Http;
17 use Illuminate\Support\Facades\Log;
19 class DispatchWebhookJob implements ShouldQueue
22 use InteractsWithQueue;
26 protected Webhook $webhook;
27 protected User $initiator;
28 protected int $initiatedTime;
29 protected array $webhookData;
32 * Create a new job instance.
36 public function __construct(Webhook $webhook, string $event, Loggable|string $detail)
38 $this->webhook = $webhook;
39 $this->initiator = user();
40 $this->initiatedTime = time();
42 $themeResponse = Theme::dispatch(ThemeEvents::WEBHOOK_CALL_BEFORE, $event, $this->webhook, $detail, $this->initiator, $this->initiatedTime);
43 $this->webhookData = $themeResponse ?? WebhookFormatter::getDefault($event, $this->webhook, $detail, $this->initiator, $this->initiatedTime)->format();
51 public function handle()
56 $response = Http::asJson()
57 ->withOptions(['allow_redirects' => ['strict' => true]])
58 ->timeout($this->webhook->timeout)
59 ->post($this->webhook->endpoint, $this->webhookData);
60 } catch (\Exception $exception) {
61 $lastError = $exception->getMessage();
62 Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with error \"{$lastError}\"");
65 if (isset($response) && $response->failed()) {
66 $lastError = "Response status from endpoint was {$response->status()}";
67 Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with status {$response->status()}");
70 $this->webhook->last_called_at = now();
72 $this->webhook->last_errored_at = now();
73 $this->webhook->last_error = $lastError;
76 $this->webhook->save();