]> BookStack Code Mirror - bookstack/blob - app/Actions/DispatchWebhookJob.php
Added more complexity in an attempt to make ldap host failover fit
[bookstack] / app / Actions / DispatchWebhookJob.php
1 <?php
2
3 namespace BookStack\Actions;
4
5 use BookStack\Auth\User;
6 use BookStack\Facades\Theme;
7 use BookStack\Interfaces\Loggable;
8 use BookStack\Theming\ThemeEvents;
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\Facades\Http;
15 use Illuminate\Support\Facades\Log;
16
17 class DispatchWebhookJob implements ShouldQueue
18 {
19     use Dispatchable;
20     use InteractsWithQueue;
21     use Queueable;
22     use SerializesModels;
23
24     protected Webhook $webhook;
25     protected string $event;
26     protected User $initiator;
27     protected int $initiatedTime;
28
29     /**
30      * @var string|Loggable
31      */
32     protected $detail;
33
34     /**
35      * Create a new job instance.
36      *
37      * @return void
38      */
39     public function __construct(Webhook $webhook, string $event, $detail)
40     {
41         $this->webhook = $webhook;
42         $this->event = $event;
43         $this->detail = $detail;
44         $this->initiator = user();
45         $this->initiatedTime = time();
46     }
47
48     /**
49      * Execute the job.
50      *
51      * @return void
52      */
53     public function handle()
54     {
55         $themeResponse = Theme::dispatch(ThemeEvents::WEBHOOK_CALL_BEFORE, $this->event, $this->webhook, $this->detail, $this->initiator, $this->initiatedTime);
56         $webhookData = $themeResponse ?? WebhookFormatter::getDefault($this->event, $this->webhook, $this->detail, $this->initiator, $this->initiatedTime)->format();
57         $lastError = null;
58
59         try {
60             $response = Http::asJson()
61                 ->withOptions(['allow_redirects' => ['strict' => true]])
62                 ->timeout($this->webhook->timeout)
63                 ->post($this->webhook->endpoint, $webhookData);
64         } catch (\Exception $exception) {
65             $lastError = $exception->getMessage();
66             Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with error \"{$lastError}\"");
67         }
68
69         if (isset($response) && $response->failed()) {
70             $lastError = "Response status from endpoint was {$response->status()}";
71             Log::error("Webhook call to endpoint {$this->webhook->endpoint} failed with status {$response->status()}");
72         }
73
74         $this->webhook->last_called_at = now();
75         if ($lastError) {
76             $this->webhook->last_errored_at = now();
77             $this->webhook->last_error = $lastError;
78         }
79
80         $this->webhook->save();
81     }
82 }