65 lines
2.4 KiB
PHP
65 lines
2.4 KiB
PHP
<?php
|
|
|
|
use GuzzleHttp\Client;
|
|
|
|
require_once 'vendor/autoload.php';
|
|
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
|
|
$dotenv->load();
|
|
$client = new Client();
|
|
function send_notifications(Client $client, string $receiver, string $title, string $body): void
|
|
{
|
|
$client->post(sprintf('%s/api/services/notify/%s', $_ENV['HOMEASSISTANT_URL'], $receiver), [
|
|
'headers' => ['Authorization' => 'Bearer ' . $_ENV['HOMEASSISTANT_TOKEN']],
|
|
'json' => ['message' => $body, 'title' => $title]
|
|
]);
|
|
}
|
|
|
|
function update_homeassistent_entity(Client $client, array $package_info): void
|
|
{
|
|
$client->post(sprintf('%s/api/states/sensor.foodsi_3kromki_large', $_ENV['HOMEASSISTANT_URL']), [
|
|
'headers' => ['Authorization' => 'Bearer ' . $_ENV['HOMEASSISTANT_TOKEN']],
|
|
'json' => ['state' => $package_info['current_quantity']]
|
|
]);
|
|
}
|
|
|
|
function get_foodsie_package_info(Client $client): array
|
|
{
|
|
$response = $client->post('https://api.foodsi.pl/api/v2/auth/sign_in', [
|
|
'json' => [
|
|
'email' => $_ENV['FOODSI_EMAIL'],
|
|
'password' => $_ENV['FOODSI_PASSWORD'],
|
|
],
|
|
]);
|
|
$response = $client->get(
|
|
'https://api.foodsi.pl/api/v3/user/offers?filter[venue_name][]=Trzy kromki chleba&filter[active]=true&filter[current_quantity][gt]=-1&filter[id]=6052730',
|
|
[
|
|
'headers' => [
|
|
'Access-Token' => $response->getHeader('Access-Token'),
|
|
'Client' => $response->getHeader('Client'),
|
|
'Uid' => $response->getHeader('Uid'),
|
|
],
|
|
],
|
|
);
|
|
$data = json_decode($response->getBody(), true);
|
|
|
|
return $data['data'][0]['attributes'];
|
|
}
|
|
|
|
$packageInfo = get_foodsie_package_info($client);
|
|
$receivers = explode(',', $_ENV['HOMEASSISTANT_NOTIFICATION_CLIENTS']);
|
|
$notificationSent = false;
|
|
foreach ($receivers as $receiver) {
|
|
if (!file_exists('last_notification_date.txt')) {
|
|
touch('last_notification_date.txt');
|
|
}
|
|
$lastNotificationDate = file_get_contents('last_notification_date.txt');
|
|
if ($packageInfo['current_quantity'] > -1 && $lastNotificationDate !== date('Y-m-d')) {
|
|
send_notifications($client, $receiver, 'Dostępna paczka w 3 kromki chleba', sprintf('W trzech kromkach dostępne są paczki. Ilość: %s', $packageInfo['current_quantity']));
|
|
$notificationSent = true;
|
|
}
|
|
}
|
|
if ($notificationSent) {
|
|
file_put_contents('last_notification_date.txt', date('Y-m-d'));
|
|
}
|
|
update_homeassistent_entity($client, $packageInfo);
|