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
20 use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
33 * @var string|Loggable
45 protected $initiatedTime;
48 * Create a new job instance.
52 public function __construct(Webhook $webhook, string $event, $detail)
54 $this->webhook = $webhook;
55 $this->event = $event;
56 $this->detail = $detail;
57 $this->initiator = user();
58 $this->initiatedTime = time();
66 public function handle()
68 $response = Http::asJson()
69 ->withOptions(['allow_redirects' => ['strict' => true]])
71 ->post($this->webhook->endpoint, $this->buildWebhookData());
73 if ($response->failed()) {
74 Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with status {$response->status()}");
78 protected function buildWebhookData(): array
81 $this->initiator->name,
82 trans('activities.' . $this->event),
85 if ($this->detail instanceof Entity) {
86 $textParts[] = '"' . $this->detail->name . '"';
90 'event' => $this->event,
91 'text' => implode(' ', $textParts),
92 'triggered_at' => Carbon::createFromTimestampUTC($this->initiatedTime)->toISOString(),
93 'triggered_by' => $this->initiator->attributesToArray(),
94 'triggered_by_profile_url' => $this->initiator->getProfileUrl(),
95 'webhook_id' => $this->webhook->id,
96 'webhook_name' => $this->webhook->name,
99 if (method_exists($this->detail, 'getUrl')) {
100 $data['url'] = $this->detail->getUrl();
103 if ($this->detail instanceof Model) {
104 $data['related_item'] = $this->detail->attributesToArray();