]> BookStack Code Mirror - bookstack/blob - app/Activity/DispatchWebhookJob.php
Webhooks: Fixed failing delete-based events
[bookstack] / app / Activity / DispatchWebhookJob.php
1 <?php
2
3 namespace BookStack\Activity;
4
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;
18
19 class DispatchWebhookJob implements ShouldQueue
20 {
21     use Dispatchable;
22     use InteractsWithQueue;
23     use Queueable;
24     use SerializesModels;
25
26     protected Webhook $webhook;
27     protected User $initiator;
28     protected int $initiatedTime;
29     protected array $webhookData;
30
31     /**
32      * Create a new job instance.
33      *
34      * @return void
35      */
36     public function __construct(Webhook $webhook, string $event, Loggable|string $detail)
37     {
38         $this->webhook = $webhook;
39         $this->initiator = user();
40         $this->initiatedTime = time();
41
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();
44     }
45
46     /**
47      * Execute the job.
48      *
49      * @return void
50      */
51     public function handle()
52     {
53         $lastError = null;
54
55         try {
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}\"");
63         }
64
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()}");
68         }
69
70         $this->webhook->last_called_at = now();
71         if ($lastError) {
72             $this->webhook->last_errored_at = now();
73             $this->webhook->last_error = $lastError;
74         }
75
76         $this->webhook->save();
77     }
78 }