3 namespace BookStack\Actions;
5 use BookStack\Auth\User;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Interfaces\Loggable;
9 use Illuminate\Bus\Queueable;
10 use Illuminate\Contracts\Queue\ShouldQueue;
11 use Illuminate\Foundation\Bus\Dispatchable;
12 use Illuminate\Queue\InteractsWithQueue;
13 use Illuminate\Queue\SerializesModels;
14 use Illuminate\Support\Carbon;
15 use Illuminate\Support\Facades\Http;
16 use Illuminate\Support\Facades\Log;
18 class DispatchWebhookJob implements ShouldQueue
21 use InteractsWithQueue;
36 * @var string|Loggable
48 protected $initiatedTime;
51 * Create a new job instance.
55 public function __construct(Webhook $webhook, string $event, $detail)
57 $this->webhook = $webhook;
58 $this->event = $event;
59 $this->detail = $detail;
60 $this->initiator = user();
61 $this->initiatedTime = time();
69 public function handle()
71 $response = Http::asJson()
72 ->withOptions(['allow_redirects' => ['strict' => true]])
74 ->post($this->webhook->endpoint, $this->buildWebhookData());
76 if ($response->failed()) {
77 Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with status {$response->status()}");
81 protected function buildWebhookData(): array
84 $this->initiator->name,
85 trans('activities.' . $this->event),
88 if ($this->detail instanceof Entity) {
89 $textParts[] = '"' . $this->detail->name . '"';
93 'event' => $this->event,
94 'text' => implode(' ', $textParts),
95 'triggered_at' => Carbon::createFromTimestampUTC($this->initiatedTime)->toISOString(),
96 'triggered_by' => $this->initiator->attributesToArray(),
97 'triggered_by_profile_url' => $this->initiator->getProfileUrl(),
98 'webhook_id' => $this->webhook->id,
99 'webhook_name' => $this->webhook->name,
102 if (method_exists($this->detail, 'getUrl')) {
103 $data['url'] = $this->detail->getUrl();
106 if ($this->detail instanceof Model) {
107 $data['related_item'] = $this->detail->attributesToArray();