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 string $event;
28 protected User $initiator;
29 protected int $initiatedTime;
32 * @var string|Loggable
37 * Create a new job instance.
41 public function __construct(Webhook $webhook, string $event, $detail)
43 $this->webhook = $webhook;
44 $this->event = $event;
45 $this->detail = $detail;
46 $this->initiator = user();
47 $this->initiatedTime = time();
55 public function handle()
57 $themeResponse = Theme::dispatch(ThemeEvents::WEBHOOK_CALL_BEFORE, $this->event, $this->webhook, $this->detail, $this->initiator, $this->initiatedTime);
58 $webhookData = $themeResponse ?? WebhookFormatter::getDefault($this->event, $this->webhook, $this->detail, $this->initiator, $this->initiatedTime)->format();
62 $response = Http::asJson()
63 ->withOptions(['allow_redirects' => ['strict' => true]])
64 ->timeout($this->webhook->timeout)
65 ->post($this->webhook->endpoint, $webhookData);
66 } catch (\Exception $exception) {
67 $lastError = $exception->getMessage();
68 Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with error \"{$lastError}\"");
71 if (isset($response) && $response->failed()) {
72 $lastError = "Response status from endpoint was {$response->status()}";
73 Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with status {$response->status()}");
76 $this->webhook->last_called_at = now();
78 $this->webhook->last_errored_at = now();
79 $this->webhook->last_error = $lastError;
82 $this->webhook->save();