alfred-nextcloud/bot/Request.php

65 lines
1.8 KiB
PHP
Raw Permalink Normal View History

2024-08-06 16:06:07 +02:00
<?php
namespace Shikiryu\Bot;
2024-08-07 17:46:01 +02:00
use JsonException;
2024-08-06 16:06:07 +02:00
class Request
{
2024-08-07 17:46:01 +02:00
public string $nc_signature;
public string $nc_random;
public string $nc_server;
public string $delivery;
public string $event;
public string $signature;
public string $body;
2024-08-07 17:51:07 +02:00
public array $config;
2024-08-07 17:46:01 +02:00
2024-08-07 17:51:07 +02:00
public function __construct(array $config = [])
2024-08-07 17:46:01 +02:00
{
$this->nc_signature = $_SERVER['HTTP_X_NEXTCLOUD_TALK_SIGNATURE'] ?? '';
$this->nc_random = $_SERVER['HTTP_X_NEXTCLOUD_TALK_RANDOM'] ?? '';
$this->nc_server = $_SERVER['HTTP_X_NEXTCLOUD_TALK_BACKEND'] ?? '';
$this->delivery = $_SERVER['HTTP_X_H1_DELIVERY'] ?? '';
$this->event = $_SERVER['HTTP_X_H1_EVENT'] ?? '';
$this->signature = $_SERVER['HTTP_X_H1_SIGNATURE'] ?? '';
$this->body = file_get_contents('php://input');
2024-08-07 17:51:07 +02:00
$this->config = $config;
}
public function isValid(): bool
{
return hash_equals(
hash_hmac('sha256', $this->nc_random . $this->body, $this->config['secret']),
strtolower($this->nc_signature)
);
2024-08-07 17:46:01 +02:00
}
public function getJSONBody(): array
{
try {
return json_decode($this->body, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
return [];
}
}
public function isMessage(): bool
{
$data = $this->getJSONBody();
return $data['type'] === 'Create' &&
$data['object']['name'] === 'message' &&
!empty($data['object']['content']);
}
2024-08-06 16:06:07 +02:00
2024-08-07 17:46:01 +02:00
public function getMessage(): string
{
try {
$data = $this->getJSONBody();
return json_decode($data['object']['content'], true, 512, JSON_THROW_ON_ERROR)['message'];
} catch (JsonException $e) {
return '';
}
}
2024-08-06 16:06:07 +02:00
}