3 namespace BookStack\Actions;
5 use BookStack\Auth\User;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Facades\Theme;
8 use BookStack\Interfaces\Loggable;
10 use BookStack\Theming\ThemeEvents;
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\Carbon;
17 use Illuminate\Support\Facades\Http;
18 use Illuminate\Support\Facades\Log;
20 class DispatchWebhookJob implements ShouldQueue
23 use InteractsWithQueue;
38 * @var string|Loggable
50 protected $initiatedTime;
53 * Create a new job instance.
57 public function __construct(Webhook $webhook, string $event, $detail)
59 $this->webhook = $webhook;
60 $this->event = $event;
61 $this->detail = $detail;
62 $this->initiator = user();
63 $this->initiatedTime = time();
71 public function handle()
73 $themeResponse = Theme::dispatch(ThemeEvents::WEBHOOK_CALL_BEFORE, $this->event, $this->webhook, $this->detail);
74 $webhookData = $themeResponse ?? $this->buildWebhookData();
76 $response = Http::asJson()
77 ->withOptions(['allow_redirects' => ['strict' => true]])
79 ->post($this->webhook->endpoint, $webhookData);
81 if ($response->failed()) {
82 Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with status {$response->status()}");
86 protected function buildWebhookData(): array
89 $this->initiator->name,
90 trans('activities.' . $this->event),
93 if ($this->detail instanceof Entity) {
94 $textParts[] = '"' . $this->detail->name . '"';
98 'event' => $this->event,
99 'text' => implode(' ', $textParts),
100 'triggered_at' => Carbon::createFromTimestampUTC($this->initiatedTime)->toISOString(),
101 'triggered_by' => $this->initiator->attributesToArray(),
102 'triggered_by_profile_url' => $this->initiator->getProfileUrl(),
103 'webhook_id' => $this->webhook->id,
104 'webhook_name' => $this->webhook->name,
107 if (method_exists($this->detail, 'getUrl')) {
108 $data['url'] = $this->detail->getUrl();
111 if ($this->detail instanceof Model) {
112 $data['related_item'] = $this->detail->attributesToArray();