diff --git a/README.md b/README.md index a78604f..40c1112 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ Car는 차량 모뎀/게이트웨이에서 받은 상태를 수집해 DB에 저 ## 구성 - `api.php`: 차량 상태/제어 API +- `asset-version.php`: 차량 모니터 파일 묶음의 현재 hash를 내려주는 JSON 엔드포인트 - `monitor.php`: 모니터링 화면과 AJAX 응답 - `common.php`: 외부 secret 로드와 공통 DB/API 함수 - `collector_se.php`: 상태 수집 CLI/cron @@ -63,6 +64,8 @@ Car는 차량 모뎀/게이트웨이에서 받은 상태를 수집해 DB에 저 - `sw.js`: service worker - `assets/`: 아이콘과 정적 자산 +`asset-version.php`는 차량 모니터의 PHP/JS/CSS/manifest/icon 파일을 읽어 크기, 수정 시각, sha256 hash를 묶은 버전을 만듭니다. `assets/asset-reload.js`는 열린 모니터 화면에서 이 값을 확인하고, 달라지면 Cache Storage를 비운 뒤 현재 화면을 다시 엽니다. + ## 데이터/저장소 - Car DB tables: 차량 상태, 로그, 차트용 기록, TCP 요청 큐 diff --git a/asset-version.php b/asset-version.php new file mode 100644 index 0000000..39bfb70 --- /dev/null +++ b/asset-version.php @@ -0,0 +1,75 @@ + ['php', 'js', 'css', 'webmanifest', 'svg', 'png', 'ico'], +]; + +function collect_asset_files(string $root, array $scanRoots): array +{ + $files = []; + $rootPath = realpath($root); + if (!$rootPath) { + return $files; + } + + foreach ($scanRoots as $relativeRoot => $extensions) { + $base = realpath($rootPath . DIRECTORY_SEPARATOR . $relativeRoot); + if (!$base || strpos($base, $rootPath) !== 0) { + continue; + } + + $allowed = array_fill_keys(array_map('strtolower', $extensions), true); + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS) + ); + + foreach ($iterator as $file) { + if (!$file instanceof SplFileInfo || !$file->isFile()) { + continue; + } + + $extension = strtolower($file->getExtension()); + if (!isset($allowed[$extension])) { + continue; + } + + $path = $file->getRealPath(); + if ($path && strpos($path, $rootPath . DIRECTORY_SEPARATOR) === 0) { + $files[] = $path; + } + } + } + + sort($files, SORT_STRING); + return array_values(array_unique($files)); +} + +clearstatcache(); +$rootPath = realpath($root); +$fingerprints = []; + +foreach (collect_asset_files($root, $scanRoots) as $fullPath) { + $relativePath = ltrim(str_replace($rootPath ?: $root, '', $fullPath), DIRECTORY_SEPARATOR); + $fileHash = is_readable($fullPath) ? (hash_file('sha256', $fullPath) ?: 'hash-failed') : 'unreadable'; + $fingerprints[] = implode('|', [ + str_replace(DIRECTORY_SEPARATOR, '/', $relativePath), + (string)filesize($fullPath), + (string)filemtime($fullPath), + $fileHash, + ]); +} + +echo json_encode([ + 'result' => 'ok', + 'service' => $service, + 'version' => hash('sha256', implode("\n", $fingerprints)), + 'count' => count($fingerprints), + 'generatedAt' => time(), +], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); diff --git a/assets/asset-reload.js b/assets/asset-reload.js new file mode 100644 index 0000000..1b291bb --- /dev/null +++ b/assets/asset-reload.js @@ -0,0 +1,93 @@ +(function () { + 'use strict'; + + var script = document.currentScript || (function () { + var scripts = document.getElementsByTagName('script'); + return scripts[scripts.length - 1] || null; + })(); + var service = script && script.dataset ? script.dataset.service : ''; + var endpoint = script && script.dataset && script.dataset.endpoint + ? script.dataset.endpoint + : new URL('../asset-version.php', script ? script.src : window.location.href).toString(); + var interval = script && script.dataset && script.dataset.interval ? Number(script.dataset.interval) : 30000; + + if (!service || window.__assetReloadStarted) return; + + window.__assetReloadStarted = true; + interval = Math.max(15000, Number.isFinite(interval) ? interval : 30000); + + var storageKey = 'assetVersion:' + service; + var reloadKey = 'assetReload:' + service; + var running = false; + + function addQuery(url, key, value) { + var parsed = new URL(url, window.location.href); + parsed.searchParams.set(key, value); + return parsed.toString(); + } + + function deleteCaches() { + if (!window.caches || !window.caches.keys) return Promise.resolve(); + + return window.caches.keys().then(function (keys) { + return Promise.all(keys.map(function (key) { + return window.caches.delete(key); + })); + }).catch(function () {}); + } + + function reloadWith(version) { + var token = version.slice(0, 12); + var marker = token + ':' + Math.floor(Date.now() / 10000); + + if (sessionStorage.getItem(reloadKey) === marker) return; + + sessionStorage.setItem(reloadKey, marker); + deleteCaches().then(function () { + window.location.replace(addQuery(window.location.href, 'assetReload', token)); + }); + } + + function check(force) { + if (running || (!force && document.hidden)) return; + + running = true; + fetch(addQuery(endpoint, '_', String(Date.now())), { + cache: 'no-store', + credentials: 'same-origin', + headers: { + 'Cache-Control': 'no-cache', + 'Pragma': 'no-cache' + } + }).then(function (response) { + if (!response.ok) throw new Error('asset version request failed'); + return response.json(); + }).then(function (data) { + if (!data || data.result !== 'ok' || !data.version) return; + + var previous = localStorage.getItem(storageKey); + localStorage.setItem(storageKey, data.version); + + if (previous && previous !== data.version) { + reloadWith(data.version); + } + }).catch(function () {}).finally(function () { + running = false; + }); + } + + window.addEventListener('pageshow', function () { + check(true); + }); + window.addEventListener('focus', function () { + check(true); + }); + document.addEventListener('visibilitychange', function () { + if (!document.hidden) check(true); + }); + + setInterval(function () { + check(false); + }, interval); + check(true); +})(); diff --git a/monitor.php b/monitor.php index 7c72ddd..0764f9e 100644 --- a/monitor.php +++ b/monitor.php @@ -1197,6 +1197,7 @@ $carMonitorSession = car_monitor_launcher_session(); +