Добавление PWA

This commit is contained in:
Petro1990 2025-11-24 23:22:11 +03:00
parent f13f284245
commit c217b83ad8
3 changed files with 79 additions and 3 deletions

View File

@ -1,5 +1,12 @@
#!/bin/sh #!/bin/sh
# Проверка наличия openssl
if ! command -v openssl &> /dev/null; then
echo "openssl not found. Please install it first."
# opkg update && opkg install openssl-utils (example for OpenWrt)
exit 1
fi
# Определяем директорию, в которой находится скрипт # Определяем директорию, в которой находится скрипт
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
@ -70,6 +77,10 @@ wget --no-check-certificate -O "$ICONS_DIR/icon-192x192.png" "$ICON192_URL"
echo "Загрузка icon-512x512.png..." echo "Загрузка icon-512x512.png..."
wget --no-check-certificate -O "$ICONS_DIR/icon-512x512.png" "$ICON512_URL" wget --no-check-certificate -O "$ICONS_DIR/icon-512x512.png" "$ICON512_URL"
# Загружаем service-worker.js
echo "Загрузка service-worker.js..."
wget -O "$PWA_DIR/service-worker.js" "$BASE_URL/public/service-worker.js"
# Скачиваем основной скрипт # Скачиваем основной скрипт
echo "Загрузка $PY_SCRIPT..." echo "Загрузка $PY_SCRIPT..."
wget --no-check-certificate -O "$INSTALL_DIR/$PY_SCRIPT" "$BASE_URL/$PY_SCRIPT" wget --no-check-certificate -O "$INSTALL_DIR/$PY_SCRIPT" "$BASE_URL/$PY_SCRIPT"

View File

@ -12,6 +12,7 @@ import time
import shutil import shutil
import glob import glob
import json import json
import ssl
from datetime import datetime from datetime import datetime
# --- НАСТРОЙКИ --- # --- НАСТРОЙКИ ---
@ -677,6 +678,15 @@ function doRename() {
}) })
.catch(e => alert("Сетевая ошибка: " + e)); .catch(e => alert("Сетевая ошибка: " + e));
} }
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js').then(registration => {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, err => {
console.log('ServiceWorker registration failed: ', err);
});
});
}
</script></body></html>""" </script></body></html>"""
@ -779,6 +789,17 @@ class H(http.server.SimpleHTTPRequestHandler):
pass # Silent fail to avoid crashing pass # Silent fail to avoid crashing
def do_GET(s): def do_GET(s):
if s.path == '/service-worker.js':
try:
with open('public/service-worker.js', 'rb') as f:
s.send_response(200)
s.send_header('Content-type', 'application/javascript')
s.end_headers()
s.wfile.write(f.read())
except FileNotFoundError:
s.send_error(404, "File not found")
return
if s.path == '/manifest.json': if s.path == '/manifest.json':
try: try:
with open('public/manifest.json', 'rb') as f: with open('public/manifest.json', 'rb') as f:
@ -1007,7 +1028,23 @@ class H(http.server.SimpleHTTPRequestHandler):
try: try:
socketserver.TCPServer.allow_reuse_address = True; # Создаем самоподписанный сертификат "на лету"
socketserver.TCPServer(("", PORT), H).serve_forever() certfile = '/tmp/mihomo_cert.pem'
keyfile = '/tmp/mihomo_key.pem'
if not os.path.exists(certfile):
subprocess.call('openssl req -new -x509 -keyout {k} -out {c} -days 365 -nodes -subj "/C=US/ST=CA/L=./O=./CN=localhost"'.format(k=keyfile, c=certfile), shell=True, stderr=subprocess.DEVNULL)
server_address = ('', PORT)
httpd = http.server.HTTPServer(server_address, H)
httpd.socket = ssl.wrap_socket(httpd.socket,
server_side=True,
certfile=certfile,
keyfile=keyfile,
ssl_version=ssl.PROTOCOL_TLS)
print(f"Server running on https://localhost:{PORT}")
httpd.serve_forever()
except Exception as e: except Exception as e:
print(e) print(f"Failed to start HTTPS server: {e}")
print("Fallback to HTTP...")
socketserver.TCPServer.allow_reuse_address = True
socketserver.TCPServer(("", PORT), H).serve_forever()

28
public/service-worker.js Normal file
View File

@ -0,0 +1,28 @@
// Список ресурсов для кэширования
const CACHE_NAME = 'mihomo-studio-cache-v1';
const urlsToCache = [
'/',
'/manifest.json',
'/icons/icon-192x192.png',
'/icons/icon-512x512.png'
];
// Установка Service Worker и кэширование ресурсов
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
// Обработка запросов: сначала из сети, потом из кэша
self.addEventListener('fetch', event => {
event.respondWith(
fetch(event.request).catch(() => {
return caches.match(event.request);
})
);
});