Repository navigation
Expand file tree
/
Copy pathget_printer_data.php
More file actions
66 lines (54 loc) · 1.73 KB
/
Copy pathget_printer_data.php
File metadata and controls
66 lines (54 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
declare(strict_types=1);
require_once __DIR__ . '/lib/printer_providers.php';
require_once __DIR__ . '/lib/job_history.php';
require_once __DIR__ . '/lib/app_config.php';
$applicationConfig = applicationConfig();
$printersFile = $applicationConfig['printers_file'];
$cacheFile = $applicationConfig['cache_file'];
$jobHistoryFile = printerJobHistoryPath($cacheFile);
function loadPrinters(string $path): array
{
if (!is_file($path)) {
return [];
}
$decoded = json_decode((string)file_get_contents($path), true);
return is_array($decoded) ? $decoded : [];
}
function fetchPrinterData(array $printers, array $homeAssistantConfig): array
{
$printerData = [];
foreach ($printers as $printer) {
if (!printerIsActive($printer)) {
continue;
}
$printerData[] = fetchPrinter($printer, $homeAssistantConfig);
}
return $printerData;
}
function getCachedData(string $cacheFile, int $maxAge = 60): string|false
{
if (!is_file($cacheFile)) {
return false;
}
return time() - filemtime($cacheFile) < $maxAge
? file_get_contents($cacheFile)
: false;
}
$cachedData = getCachedData($cacheFile);
if ($cachedData === false) {
$printers = loadPrinters($printersFile);
$homeAssistantConfig = $applicationConfig['home_assistant'];
$printerData = fetchPrinterData($printers, $homeAssistantConfig);
$printerData = applyPrinterJobHistory($jobHistoryFile, $printers, $printerData);
$cachedData = json_encode(
$printerData,
JSON_UNESCAPED_SLASHES
);
if ($cachedData === false) {
$cachedData = '[]';
}
file_put_contents($cacheFile, $cachedData, LOCK_EX);
}
header('Content-Type: application/json');
echo $cachedData;