ui: fix service-worker config

This commit is contained in:
undefined committed 2023-02-01 13:21:29 +08:00
1 parent 1bd551916e
commit d6cd5579b6
4 files changed
+27 -36

No files matched your search

+3 -3
View File
@@ -27,9 +27,11 @@ console.log(
`, `,
); );
window.UiContext = JSON.parse(window.UiContext);
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
window.addEventListener('load', () => { window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js').then((registration) => { const encodedConfig = encodeURIComponent(JSON.stringify(UiContext.SWConfig));
navigator.serviceWorker.register(`/service-worker.js?config=${encodedConfig}`).then((registration) => {
console.log('SW registered: ', registration); console.log('SW registered: ', registration);
}).catch((registrationError) => { }).catch((registrationError) => {
console.log('SW registration failed: ', registrationError); console.log('SW registration failed: ', registrationError);
@@ -38,8 +40,6 @@ if ('serviceWorker' in navigator) {
} }
document.addEventListener('DOMContentLoaded', async () => { document.addEventListener('DOMContentLoaded', async () => {
window.UiContext = JSON.parse(window.UiContext);
const PageLoader = '<div class="page-loader nojs--hide" style="display:none;"><div class="loader"></div></div>'; const PageLoader = '<div class="page-loader nojs--hide" style="display:none;"><div class="loader"></div></div>';
$('body').prepend(PageLoader); $('body').prepend(PageLoader);
$('.page-loader').fadeIn(500); $('.page-loader').fadeIn(500);
+12 -19
View File
@@ -78,24 +78,6 @@ class MarkdownHandler extends Handler {
} }
} }
class SWConfigHandler extends Handler {
noCheckPermView = true;
async get() {
this.response.addHeader('Cache-Control', 'public, max-age=86400');
this.response.body = {
preload: SystemModel.get('ui-default.preload'),
hosts: [
`http://${this.request.host}`,
`https://${this.request.host}`,
SystemModel.get('server.url'),
SystemModel.get('server.cdn'),
],
domains: SystemModel.get('ui-default.domains') || [],
};
}
}
class SystemConfigSchemaHandler extends Handler { class SystemConfigSchemaHandler extends Handler {
async get() { async get() {
const schema = convert(Schema.intersect(SystemSettings) as any, true); const schema = convert(Schema.intersect(SystemSettings) as any, true);
@@ -162,7 +144,6 @@ export function apply(ctx: Context) {
ctx.Route('set_legacy', '/legacy', LegacyModeHandler); ctx.Route('set_legacy', '/legacy', LegacyModeHandler);
ctx.Route('markdown', '/markdown', MarkdownHandler); ctx.Route('markdown', '/markdown', MarkdownHandler);
ctx.Route('config_schema', '/manage/config/schema.json', SystemConfigSchemaHandler, PRIV.PRIV_EDIT_SYSTEM); ctx.Route('config_schema', '/manage/config/schema.json', SystemConfigSchemaHandler, PRIV.PRIV_EDIT_SYSTEM);
ctx.Route('sw_config', '/sw-config', SWConfigHandler);
ctx.Route('media', '/media', RichMediaHandler); ctx.Route('media', '/media', RichMediaHandler);
ctx.plugin(require('./backendlib/builder')); ctx.plugin(require('./backendlib/builder'));
ctx.on('handler/after/DiscussionRaw', async (that) => { ctx.on('handler/after/DiscussionRaw', async (that) => {
@@ -171,4 +152,16 @@ export function apply(ctx: Context) {
that.response.body = await markdown.render(that.response.body); that.response.body = await markdown.render(that.response.body);
} }
}); });
ctx.on('handler/after', async (that) => {
that.UiContext.SWConfig = {
preload: SystemModel.get('ui-default.preload'),
hosts: [
`http://${that.request.host}`,
`https://${that.request.host}`,
SystemModel.get('server.url'),
SystemModel.get('server.cdn'),
],
domains: SystemModel.get('ui-default.domains') || [],
};
});
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@hydrooj/ui-default", "name": "@hydrooj/ui-default",
"version": "4.47.0", "version": "4.47.1",
"author": "undefined <i@undefined.moe>", "author": "undefined <i@undefined.moe>",
"license": "AGPL-3.0", "license": "AGPL-3.0",
"main": "index.ts", "main": "index.ts",
+11 -13
View File
@@ -49,20 +49,20 @@ interface ServiceWorkerConfig {
} }
let config: ServiceWorkerConfig = null; let config: ServiceWorkerConfig = null;
async function initConfig() { function initConfig() {
const res = await fetch('/sw-config'); config = JSON.parse(new URL(location).searchParams.get('config'));
config = await res.json();
config.hosts ||= []; config.hosts ||= [];
if (!config.domains?.length) config.domains = [location.host]; if (!config.domains?.length) config.domains = [location.host];
console.log('Config:', config);
} }
self.addEventListener('install', (event) => event.waitUntil((async () => { self.addEventListener('install', (event) => event.waitUntil((async () => {
const [cache, manifest] = await Promise.all([ initConfig();
caches.open(PRECACHE),
fetch('/manifest.json').then((res) => res.json()),
initConfig(),
]);
if (process.env.NODE_ENV === 'production' && config?.preload) { if (process.env.NODE_ENV === 'production' && config?.preload) {
const [cache, manifest] = await Promise.all([
caches.open(PRECACHE),
fetch('/manifest.json').then((res) => res.json()),
]);
const files = Object.values(manifest).filter(shouldPreCache) const files = Object.values(manifest).filter(shouldPreCache)
.map((i: string) => new URL(i, config.preload).toString()); .map((i: string) => new URL(i, config.preload).toString());
await cache.addAll(files); // NOTE: CORS header await cache.addAll(files); // NOTE: CORS header
@@ -72,12 +72,9 @@ self.addEventListener('install', (event) => event.waitUntil((async () => {
self.addEventListener('activate', (event) => { self.addEventListener('activate', (event) => {
const valid = [PRECACHE]; const valid = [PRECACHE];
initConfig();
event.waitUntil((async () => { event.waitUntil((async () => {
const [names] = await Promise.all([ const names = await caches.keys();
caches.keys(),
initConfig(),
]);
console.log('Config: ', config);
await Promise.all(names.filter((name) => !valid.includes(name)).map((p) => caches.delete(p))); await Promise.all(names.filter((name) => !valid.includes(name)).map((p) => caches.delete(p)));
self.clients.claim(); self.clients.claim();
})()); })());
@@ -94,6 +91,7 @@ async function get(request: Request) {
method: request.method, method: request.method,
credentials: isResource ? 'same-origin' : 'include', credentials: isResource ? 'same-origin' : 'include',
headers: request.headers, headers: request.headers,
body: request.body,
}); });
if (r.ok) { if (r.ok) {
console.log('Load success from ', source.toString()); console.log('Load success from ', source.toString());