asset hash 새로고침 추가

This commit is contained in:
seo
2026-07-08 03:27:26 +09:00
parent c5edb46ec7
commit f06bc3643d
6 changed files with 178 additions and 3 deletions
+4 -1
View File
@@ -38,9 +38,13 @@ Financial은 개인 금융 데이터를 서버 렌더링 PHP 화면에서 관리
- `app/lib/recurring_service.php`: 반복거래 처리 - `app/lib/recurring_service.php`: 반복거래 처리
- `app/lib/merchant_pattern_service.php`: 가맹점 규칙과 추천 - `app/lib/merchant_pattern_service.php`: 가맹점 규칙과 추천
- `public/*.php`: 사용자 화면과 form 처리 - `public/*.php`: 사용자 화면과 form 처리
- `public/asset-version.php`: 앱/PWA 파일 묶음의 현재 hash를 내려주는 JSON 엔드포인트
- `public/assets/app.css`: 화면 스타일 - `public/assets/app.css`: 화면 스타일
- `public/assets/asset-reload.js`: 열린 브라우저에서 파일 묶음 hash가 달라졌는지 확인하고 새로 여는 스크립트
- `public/assets/pwa.js`, `public/sw.js`: PWA 동작 - `public/assets/pwa.js`, `public/sw.js`: PWA 동작
`asset-version.php``app`의 PHP 파일과 `public`의 PHP/HTML/JS/CSS/manifest/icon 파일을 읽어 크기, 수정 시각, sha256 hash를 묶은 버전을 만듭니다. 공통 헤더, 로그인, 회원가입 화면에서 `asset-reload.js`를 불러오며, 파일 묶음 hash가 달라지면 Cache Storage를 비우고 현재 화면을 다시 엽니다.
## 데이터/저장소 ## 데이터/저장소
- financial DB tables: 계좌, 거래, 카테고리, 할부, 대출, 반복거래, 가맹점 규칙 - financial DB tables: 계좌, 거래, 카테고리, 할부, 대출, 반복거래, 가맹점 규칙
@@ -73,4 +77,3 @@ Financial은 개인 금융 데이터를 서버 렌더링 PHP 화면에서 관리
- 삭제된 미사용 테이블이 다시 참조되지 않는지 확인합니다. - 삭제된 미사용 테이블이 다시 참조되지 않는지 확인합니다.
- 가맹점 추천 규칙의 우선순위 충돌을 주기적으로 점검합니다. - 가맹점 추천 규칙의 우선순위 충돌을 주기적으로 점검합니다.
- DB 백업과 secret 파일 권한을 관리합니다. - DB 백업과 secret 파일 권한을 관리합니다.
+3 -2
View File
@@ -22,8 +22,8 @@
<link rel="shortcut icon" href="/favicon.png?v=2"> <link rel="shortcut icon" href="/favicon.png?v=2">
<link rel="apple-touch-icon" href="/favicon.png?v=2"> <link rel="apple-touch-icon" href="/favicon.png?v=2">
<link rel="manifest" href="/manifest.webmanifest"> <link rel="manifest" href="/manifest.webmanifest">
<meta property="og:type" content="website"> <meta property="og:type" content="website">
<meta property="og:site_name" content="Financial"> <meta property="og:site_name" content="Financial">
<meta property="og:title" content="Financial | 개인 자산관리 · 가계부 · 대출 · 할부 통합 관리"> <meta property="og:title" content="Financial | 개인 자산관리 · 가계부 · 대출 · 할부 통합 관리">
<meta property="og:description" content="계좌, 카드, 가계부, 대출, 할부를 한 곳에서 쉽고 체계적으로 관리하세요."> <meta property="og:description" content="계좌, 카드, 가계부, 대출, 할부를 한 곳에서 쉽고 체계적으로 관리하세요.">
@@ -37,6 +37,7 @@
<link href="/assets/vendor/bootstrap.min.css" rel="stylesheet"> <link href="/assets/vendor/bootstrap.min.css" rel="stylesheet">
<link href="/assets/app.css" rel="stylesheet"> <link href="/assets/app.css" rel="stylesheet">
<script src="/assets/asset-reload.js" data-service="financial" defer></script>
<script src="https://chaegeon.com/log/bancheck.min.js?_=<?php echo time(); ?>"></script> <script src="https://chaegeon.com/log/bancheck.min.js?_=<?php echo time(); ?>"></script>
<script src="/assets/vendor/chart.umd.js"></script> <script src="/assets/vendor/chart.umd.js"></script>
</head> </head>
+76
View File
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
$service = 'financial';
$root = dirname(__DIR__);
$scanRoots = [
'app' => ['php'],
'public' => ['php', 'html', 'js', 'css', 'webmanifest', '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 . DIRECTORY_SEPARATOR) !== 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);
+93
View File
@@ -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);
})();
+1
View File
@@ -78,6 +78,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
<link href="/assets/vendor/bootstrap.min.css" rel="stylesheet"> <link href="/assets/vendor/bootstrap.min.css" rel="stylesheet">
<link href="/assets/app.css" rel="stylesheet"> <link href="/assets/app.css" rel="stylesheet">
<script src="/assets/asset-reload.js" data-service="financial" defer></script>
<script src="https://chaegeon.com/log/bancheck.min.js?_=<?php echo time(); ?>"></script> <script src="https://chaegeon.com/log/bancheck.min.js?_=<?php echo time(); ?>"></script>
</head> </head>
<body> <body>
+1
View File
@@ -87,6 +87,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
<link rel="manifest" href="/manifest.webmanifest"> <link rel="manifest" href="/manifest.webmanifest">
<link href="/assets/vendor/bootstrap.min.css" rel="stylesheet"> <link href="/assets/vendor/bootstrap.min.css" rel="stylesheet">
<link href="/assets/app.css" rel="stylesheet"> <link href="/assets/app.css" rel="stylesheet">
<script src="/assets/asset-reload.js" data-service="financial" defer></script>
<script src="https://chaegeon.com/log/bancheck.min.js?_=<?php echo time(); ?>"></script> <script src="https://chaegeon.com/log/bancheck.min.js?_=<?php echo time(); ?>"></script>
</head> </head>
<body> <body>