14303 lines
780 KiB
HTML
14303 lines
780 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="fr" data-theme="dark">
|
||
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
|
||
<meta http-equiv="Pragma" content="no-cache">
|
||
<meta http-equiv="Expires" content="0">
|
||
<title class="app-short-title">AP Manageur</title>
|
||
<link rel="icon" type="image/png" href="/images/favicon.png">
|
||
<!-- Dictionnaires i18n modulaires -->
|
||
<script src="/lang/fr.js"></script>
|
||
<script src="/lang/en-us.js"></script>
|
||
<script src="/lang/en-gb.js"></script>
|
||
<script>
|
||
(function () {
|
||
// Masquer le nom de fichier dans la barre d'adresse
|
||
try {
|
||
if (/\/(index\.html)$/i.test(window.location.pathname)) {
|
||
var cleanUrl = (window.location.pathname.replace(/\/(index\.html)$/i, '') || '/') + window.location.search + window.location.hash;
|
||
window.history.replaceState(null, '', cleanUrl);
|
||
}
|
||
} catch (_) {}
|
||
|
||
function setT(t) {
|
||
if (!t) return;
|
||
var m = window.matchMedia('(prefers-color-scheme: light)');
|
||
var resolved = t === 'auto' ? (m.matches ? 'light' : 'dark') : t;
|
||
document.documentElement.dataset.theme = resolved;
|
||
if (t === 'macos') {
|
||
document.documentElement.dataset.macosMode = m.matches ? 'light' : 'dark';
|
||
} else {
|
||
delete document.documentElement.dataset.macosMode;
|
||
}
|
||
}
|
||
try {
|
||
var t = localStorage.getItem('apTheme') || 'dark';
|
||
setT(t);
|
||
} catch (_) {}
|
||
try {
|
||
fetch('/api/preferences', { cache: 'no-store' })
|
||
.then(function (r) { return r.json(); })
|
||
.then(function (d) {
|
||
if (d && d.theme) {
|
||
try { localStorage.setItem('apTheme', d.theme); } catch (_) {}
|
||
setT(d.theme);
|
||
}
|
||
})
|
||
.catch(function () {});
|
||
} catch (_) {}
|
||
|
||
try {
|
||
fetch('/api/auth/status', { cache: 'no-store' })
|
||
.then(function (r) { return r.json(); })
|
||
.then(function (d) {
|
||
if (d && !d.configured) {
|
||
window.location.replace('/setup');
|
||
}
|
||
})
|
||
.catch(function () {});
|
||
} catch (_) {}
|
||
})();
|
||
</script>
|
||
<style>
|
||
|
||
* {
|
||
box-sizing: border-box
|
||
}
|
||
|
||
html,
|
||
body {
|
||
overflow-x: hidden;
|
||
max-width: 100%
|
||
}
|
||
|
||
body {
|
||
margin: 0;
|
||
font-family: system-ui, -apple-system, sans-serif;
|
||
background: var(--bg);
|
||
color: var(--text);
|
||
transition: background .2s, color .2s
|
||
}
|
||
|
||
.wrap {
|
||
max-width: 1100px;
|
||
margin: 0 auto;
|
||
padding: 24px;
|
||
width: 100%
|
||
}
|
||
|
||
header {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
margin-bottom: 20px;
|
||
gap: 12px;
|
||
flex-wrap: wrap
|
||
}
|
||
|
||
h1 {
|
||
margin: 0;
|
||
font-size: 26px
|
||
}
|
||
|
||
.sub {
|
||
color: var(--muted);
|
||
font-size: 14px;
|
||
margin-top: 4px
|
||
}
|
||
|
||
.header-actions {
|
||
display: flex;
|
||
gap: 8px;
|
||
flex-wrap: wrap;
|
||
align-items: center
|
||
}
|
||
|
||
.header-actions button {
|
||
display: inline-flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
gap: 8px;
|
||
height: 38px;
|
||
padding: 9px 16px;
|
||
font-size: 14px;
|
||
font-weight: 600;
|
||
border-radius: 8px;
|
||
box-sizing: border-box;
|
||
line-height: 1;
|
||
}
|
||
|
||
nav {
|
||
display: flex;
|
||
gap: 8px;
|
||
margin-bottom: 20px;
|
||
border-bottom: 1px solid var(--line);
|
||
padding-bottom: 12px;
|
||
overflow-x: auto;
|
||
-webkit-overflow-scrolling: touch
|
||
}
|
||
|
||
nav button,
|
||
nav button.secondary {
|
||
background: var(--panel2) !important;
|
||
border: 1px solid var(--line) !important;
|
||
color: var(--muted) !important;
|
||
font-size: 15px;
|
||
font-weight: 600;
|
||
padding: 8px 16px;
|
||
border-radius: 8px;
|
||
cursor: pointer;
|
||
white-space: nowrap;
|
||
flex-shrink: 0;
|
||
transition: all .18s ease;
|
||
user-select: none
|
||
}
|
||
|
||
nav button:hover:not(.active) {
|
||
background: var(--panel) !important;
|
||
color: var(--text) !important;
|
||
border-color: var(--blue) !important
|
||
}
|
||
|
||
nav button.active {
|
||
background: var(--green) !important;
|
||
color: #061a12 !important;
|
||
border-color: var(--green) !important;
|
||
font-weight: 700 !important;
|
||
box-shadow: 0 2px 10px rgba(50, 213, 131, .35)
|
||
}
|
||
|
||
.grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||
gap: 16px;
|
||
margin-bottom: 20px
|
||
}
|
||
|
||
.grid>.card {
|
||
min-width: 0;
|
||
overflow: hidden
|
||
}
|
||
|
||
.card {
|
||
background: var(--panel);
|
||
border: 1px solid var(--line);
|
||
border-radius: 14px;
|
||
padding: 20px
|
||
}
|
||
|
||
.metric {
|
||
font-size: 28px;
|
||
font-weight: 700;
|
||
margin-top: 6px;
|
||
overflow-wrap: anywhere;
|
||
word-break: break-word
|
||
}
|
||
|
||
.status {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
flex-wrap: wrap
|
||
}
|
||
|
||
.dot {
|
||
width: 12px;
|
||
height: 12px;
|
||
border-radius: 50%;
|
||
background: var(--green);
|
||
box-shadow: 0 0 10px rgba(50, 213, 131, .5);
|
||
flex-shrink: 0
|
||
}
|
||
|
||
.layout {
|
||
display: grid;
|
||
grid-template-columns: minmax(0, 1fr) 340px;
|
||
gap: 20px;
|
||
align-items: start
|
||
}
|
||
|
||
.layout>section,
|
||
.layout>aside {
|
||
min-width: 0;
|
||
max-width: 100%
|
||
}
|
||
|
||
.layout>aside {
|
||
position: sticky;
|
||
top: 18px;
|
||
align-self: start
|
||
}
|
||
|
||
.qr-card-content {
|
||
width: 100%;
|
||
max-width: 320px;
|
||
margin: 0 auto;
|
||
text-align: center
|
||
}
|
||
|
||
.qr-card-content h2 {
|
||
margin: 0 0 14px
|
||
}
|
||
|
||
.qr-card-content .label {
|
||
text-align: left
|
||
}
|
||
|
||
#qrcode,
|
||
#twoFaQr {
|
||
background: #ffffff !important;
|
||
padding: 16px !important;
|
||
border-radius: 12px;
|
||
margin: 0 auto 16px;
|
||
box-sizing: border-box;
|
||
box-shadow: 0 4px 18px rgba(0, 0, 0, .28);
|
||
width: 222px;
|
||
height: 222px;
|
||
max-width: 100%;
|
||
display: flex;
|
||
justify-content: center;
|
||
align-items: center;
|
||
overflow: hidden
|
||
}
|
||
|
||
#qrcode canvas,
|
||
#qrcode img,
|
||
#twoFaQr canvas,
|
||
#twoFaQr img {
|
||
max-width: 100% !important;
|
||
max-height: 100% !important;
|
||
image-rendering: pixelated;
|
||
image-rendering: -webkit-optimize-contrast;
|
||
margin: 0 auto
|
||
}
|
||
|
||
.settings-nav {
|
||
display: flex;
|
||
flex-wrap: wrap;
|
||
gap: 6px;
|
||
margin-bottom: 20px;
|
||
align-items: center
|
||
}
|
||
|
||
.settings-nav::-webkit-scrollbar {
|
||
display: none
|
||
}
|
||
|
||
.settings-nav-btn {
|
||
background: var(--panel2) !important;
|
||
border: 1px solid var(--line) !important;
|
||
color: var(--muted) !important;
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
padding: 7px 11px;
|
||
border-radius: 8px;
|
||
cursor: pointer;
|
||
white-space: nowrap;
|
||
flex-shrink: 0;
|
||
transition: all .18s ease;
|
||
user-select: none;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 6px
|
||
}
|
||
|
||
.settings-nav-btn:hover:not(.active) {
|
||
background: var(--panel) !important;
|
||
color: var(--text) !important;
|
||
border-color: var(--blue) !important
|
||
}
|
||
|
||
.settings-nav-btn.active {
|
||
background: var(--blue) !important;
|
||
color: var(--blue-text, #071326) !important;
|
||
border-color: var(--blue) !important;
|
||
font-weight: 700 !important;
|
||
box-shadow: 0 2px 8px rgba(92, 167, 255, .3)
|
||
}
|
||
|
||
.settings-panel {
|
||
max-width: 760px;
|
||
margin: 0 auto
|
||
}
|
||
|
||
.topline {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
margin-bottom: 14px
|
||
}
|
||
|
||
.table-wrap {
|
||
overflow-x: auto;
|
||
-webkit-overflow-scrolling: touch;
|
||
width: 100%;
|
||
max-width: 100%;
|
||
border-radius: 8px
|
||
}
|
||
|
||
table {
|
||
width: 100%;
|
||
border-collapse: collapse
|
||
}
|
||
|
||
th,
|
||
td {
|
||
padding: 12px;
|
||
text-align: left;
|
||
border-bottom: 1px solid var(--line);
|
||
font-size: 14px
|
||
}
|
||
|
||
th {
|
||
color: var(--muted);
|
||
font-size: 12px;
|
||
text-transform: uppercase;
|
||
letter-spacing: .5px
|
||
}
|
||
|
||
.client {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
min-width: 0
|
||
}
|
||
|
||
.client strong {
|
||
max-width: 180px;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
white-space: nowrap;
|
||
display: inline-block;
|
||
vertical-align: middle
|
||
}
|
||
|
||
.avatar {
|
||
width: 34px;
|
||
height: 34px;
|
||
border-radius: 50%;
|
||
background: var(--panel2);
|
||
display: grid;
|
||
place-items: center;
|
||
font-weight: 700;
|
||
color: var(--blue);
|
||
font-size: 13px;
|
||
flex-shrink: 0
|
||
}
|
||
|
||
.signal {
|
||
font-weight: 600;
|
||
font-size: 13px
|
||
}
|
||
|
||
.signal-excellent {
|
||
color: var(--green)
|
||
}
|
||
|
||
.signal-bon {
|
||
color: #68d391
|
||
}
|
||
|
||
.signal-moyen {
|
||
color: #f6ad55
|
||
}
|
||
|
||
.signal-faible {
|
||
color: var(--red)
|
||
}
|
||
|
||
button {
|
||
background: var(--blue);
|
||
color: var(--blue-text, #071326);
|
||
border: 0;
|
||
padding: 9px 16px;
|
||
border-radius: 8px;
|
||
font-weight: 600;
|
||
cursor: pointer;
|
||
font-size: 14px;
|
||
transition: opacity .15s
|
||
}
|
||
|
||
button:hover {
|
||
opacity: .9
|
||
}
|
||
|
||
button.secondary {
|
||
background: var(--panel2);
|
||
color: var(--text);
|
||
border: 1px solid var(--line)
|
||
}
|
||
|
||
button[style*="background: var(--blue)"],
|
||
button[style*="background:var(--blue)"] {
|
||
color: var(--blue-text, #071326);
|
||
}
|
||
button.secondary[style*="color:var(--blue)"],
|
||
button.secondary[style*="color: var(--blue)"],
|
||
button.secondary[style*="border-color:var(--blue)"],
|
||
button.secondary[style*="border-color: var(--blue)"] {
|
||
color: var(--blue) !important;
|
||
}
|
||
|
||
/* Boutons de sélection du fournisseur de stockage distant */
|
||
.backup-prov-btn {
|
||
background: var(--panel2) !important;
|
||
border: 1px solid var(--line) !important;
|
||
color: var(--text) !important;
|
||
transition: all .15s ease;
|
||
user-select: none;
|
||
}
|
||
.backup-prov-btn span {
|
||
color: inherit !important;
|
||
}
|
||
.backup-prov-btn:hover:not(.active) {
|
||
background: var(--panel) !important;
|
||
border-color: var(--blue) !important;
|
||
color: var(--text) !important;
|
||
}
|
||
.backup-prov-btn.active {
|
||
border: 2px solid var(--blue) !important;
|
||
box-shadow: 0 0 0 1px var(--blue) !important;
|
||
font-weight: 700 !important;
|
||
background: rgba(92, 167, 255, 0.22) !important;
|
||
color: #ffffff !important;
|
||
}
|
||
.backup-prov-btn.active span {
|
||
color: inherit !important;
|
||
}
|
||
|
||
/* Adaptation pour les thèmes clairs (Light, Windows XP, macOS Clair) */
|
||
html[data-theme="light"] .backup-prov-btn,
|
||
html[data-theme="winxp"] .backup-prov-btn,
|
||
html[data-theme="macos"][data-macos-mode="light"] .backup-prov-btn,
|
||
html[data-theme="macos"]:not([data-macos-mode="dark"]) .backup-prov-btn {
|
||
background: var(--panel2) !important;
|
||
border-color: var(--line) !important;
|
||
color: var(--text) !important;
|
||
}
|
||
html[data-theme="light"] .backup-prov-btn span,
|
||
html[data-theme="winxp"] .backup-prov-btn span,
|
||
html[data-theme="macos"][data-macos-mode="light"] .backup-prov-btn span,
|
||
html[data-theme="macos"]:not([data-macos-mode="dark"]) .backup-prov-btn span {
|
||
color: var(--text) !important;
|
||
}
|
||
html[data-theme="light"] .backup-prov-btn.active,
|
||
html[data-theme="winxp"] .backup-prov-btn.active,
|
||
html[data-theme="macos"][data-macos-mode="light"] .backup-prov-btn.active,
|
||
html[data-theme="macos"]:not([data-macos-mode="dark"]) .backup-prov-btn.active {
|
||
background: rgba(30, 110, 240, 0.12) !important;
|
||
border-color: var(--blue) !important;
|
||
color: var(--blue) !important;
|
||
}
|
||
html[data-theme="light"] .backup-prov-btn.active span,
|
||
html[data-theme="winxp"] .backup-prov-btn.active span,
|
||
html[data-theme="macos"][data-macos-mode="light"] .backup-prov-btn.active span,
|
||
html[data-theme="macos"]:not([data-macos-mode="dark"]) .backup-prov-btn.active span {
|
||
color: var(--blue) !important;
|
||
}
|
||
|
||
/* Thème Hacker */
|
||
html[data-theme="hacker"] .backup-prov-btn.active {
|
||
background: rgba(0, 255, 65, 0.25) !important;
|
||
border-color: #00ff41 !important;
|
||
color: #00ff41 !important;
|
||
}
|
||
/* Thème Futuriste */
|
||
html[data-theme="futuristic"] .backup-prov-btn.active {
|
||
background: rgba(0, 240, 255, 0.22) !important;
|
||
border-color: #00f0ff !important;
|
||
color: #e6f6ff !important;
|
||
}
|
||
|
||
#btnAuthPasskey {
|
||
border: 1px solid rgba(56, 189, 248, 0.4);
|
||
background: rgba(56, 189, 248, 0.08);
|
||
color: var(--blue);
|
||
cursor: pointer;
|
||
transition: all .2s ease;
|
||
}
|
||
|
||
#btnAuthPasskey:hover {
|
||
background: rgba(56, 189, 248, 0.18);
|
||
border-color: rgba(56, 189, 248, 0.7);
|
||
}
|
||
|
||
.pill {
|
||
background: var(--panel2);
|
||
color: var(--text);
|
||
padding: 4px 10px;
|
||
border-radius: 999px;
|
||
font-size: 12px;
|
||
font-weight: 600
|
||
}
|
||
|
||
.badge {
|
||
background: rgba(50, 213, 131, .16);
|
||
color: var(--green);
|
||
border: 1px solid rgba(50, 213, 131, .38);
|
||
padding: 4px 10px;
|
||
border-radius: 999px;
|
||
font-size: 12px;
|
||
font-weight: 600
|
||
}
|
||
|
||
.pill-blue {
|
||
background: rgba(92, 167, 255, .16) !important;
|
||
color: var(--blue) !important;
|
||
border: 1px solid rgba(92, 167, 255, .38) !important;
|
||
font-weight: 600;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 6px
|
||
}
|
||
|
||
#networkModeBadge.pill-blue {
|
||
background: rgba(92, 167, 255, .16) !important;
|
||
color: var(--blue) !important;
|
||
border: 1px solid rgba(92, 167, 255, .38) !important;
|
||
}
|
||
|
||
#networkModeBadge.pill-green {
|
||
background: rgba(50, 213, 131, .16) !important;
|
||
color: var(--green) !important;
|
||
border: 1px solid rgba(50, 213, 131, .38) !important;
|
||
}
|
||
|
||
#updated,
|
||
#topoUpdated,
|
||
#statsChartUpdated,
|
||
#statsTrafficUpdated,
|
||
#statsHistoryUpdated,
|
||
#captureUpdated,
|
||
#logsUpdated,
|
||
#blockedUpdated,
|
||
.pill-updated,
|
||
.pill-green {
|
||
background: rgba(50, 213, 131, .16) !important;
|
||
color: var(--green) !important;
|
||
border: 1px solid rgba(50, 213, 131, .38) !important;
|
||
font-weight: 600;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 6px
|
||
}
|
||
|
||
#updated::before,
|
||
#topoUpdated::before,
|
||
#statsChartUpdated::before,
|
||
#statsTrafficUpdated::before,
|
||
#statsHistoryUpdated::before,
|
||
#captureUpdated::before,
|
||
#logsUpdated::before,
|
||
#blockedUpdated::before,
|
||
.pill-updated::before,
|
||
.pill-green:not(.pill-no-dot)::before {
|
||
content: "";
|
||
display: inline-block;
|
||
width: 7px;
|
||
height: 7px;
|
||
border-radius: 50%;
|
||
background: currentColor;
|
||
box-shadow: 0 0 6px currentColor;
|
||
flex-shrink: 0
|
||
}
|
||
|
||
.pill-no-dot::before {
|
||
display: none !important
|
||
}
|
||
|
||
.view {
|
||
display: none
|
||
}
|
||
|
||
.view.active {
|
||
display: block
|
||
}
|
||
|
||
.label {
|
||
font-size: 13px;
|
||
color: var(--muted);
|
||
font-weight: 600;
|
||
display: block;
|
||
margin-top: 14px
|
||
}
|
||
|
||
input[type="text"],
|
||
input[type="password"],
|
||
input[type="number"],
|
||
input[type="url"],
|
||
select,
|
||
textarea {
|
||
width: 100%;
|
||
padding: 10px 12px;
|
||
background: var(--panel2);
|
||
border: 1px solid var(--line);
|
||
border-radius: 8px;
|
||
color: var(--text);
|
||
margin-top: 6px;
|
||
font-size: 14px;
|
||
box-sizing: border-box;
|
||
}
|
||
|
||
input[type="text"]:focus,
|
||
input[type="password"]:focus,
|
||
input[type="number"]:focus,
|
||
input[type="url"]:focus,
|
||
select:focus,
|
||
textarea:focus {
|
||
outline: none;
|
||
border-color: var(--blue);
|
||
}
|
||
|
||
/* Windows 11 Fluent Design Toggle Switch pour les checkboxes */
|
||
input[type="checkbox"] {
|
||
appearance: none !important;
|
||
-webkit-appearance: none !important;
|
||
position: relative !important;
|
||
display: inline-block !important;
|
||
width: 40px !important;
|
||
height: 20px !important;
|
||
min-width: 40px !important;
|
||
max-width: 40px !important;
|
||
border-radius: 9999px !important;
|
||
background-color: rgba(255, 255, 255, 0.08) !important;
|
||
border: 1px solid var(--line, rgba(255, 255, 255, 0.35)) !important;
|
||
cursor: pointer !important;
|
||
outline: none !important;
|
||
vertical-align: middle !important;
|
||
margin: 0 !important;
|
||
flex-shrink: 0 !important;
|
||
box-sizing: border-box !important;
|
||
transition: background-color 0.2s cubic-bezier(0.4, 0, 0.2, 1),
|
||
border-color 0.2s cubic-bezier(0.4, 0, 0.2, 1),
|
||
box-shadow 0.2s cubic-bezier(0.4, 0, 0.2, 1) !important;
|
||
}
|
||
|
||
input[type="checkbox"]::before {
|
||
content: "" !important;
|
||
position: absolute !important;
|
||
top: 3px !important;
|
||
left: 3px !important;
|
||
width: 12px !important;
|
||
height: 12px !important;
|
||
border-radius: 50% !important;
|
||
background-color: var(--muted, #9aa8c5) !important;
|
||
transition: transform 0.2s cubic-bezier(0.2, 0.8, 0.4, 1),
|
||
width 0.15s ease,
|
||
background-color 0.2s ease !important;
|
||
}
|
||
|
||
/* Hover état désactivé */
|
||
input[type="checkbox"]:hover {
|
||
background-color: rgba(255, 255, 255, 0.14) !important;
|
||
border-color: rgba(255, 255, 255, 0.55) !important;
|
||
}
|
||
|
||
input[type="checkbox"]:hover::before {
|
||
background-color: var(--text, #ffffff) !important;
|
||
}
|
||
|
||
/* Clic maintenu (effet d'étirement Fluent Win11) */
|
||
input[type="checkbox"]:active::before {
|
||
width: 15px !important;
|
||
}
|
||
|
||
/* État Activé (Checked) */
|
||
input[type="checkbox"]:checked {
|
||
background-color: var(--blue, #38bdf8) !important;
|
||
border-color: var(--blue, #38bdf8) !important;
|
||
}
|
||
|
||
input[type="checkbox"]:checked::before {
|
||
transform: translateX(20px) !important;
|
||
background-color: #000000 !important;
|
||
}
|
||
|
||
input[type="checkbox"]:checked:hover {
|
||
filter: brightness(1.08) !important;
|
||
}
|
||
|
||
input[type="checkbox"]:checked:active::before {
|
||
transform: translateX(17px) !important;
|
||
width: 15px !important;
|
||
}
|
||
|
||
/* Focus navigation clavier */
|
||
input[type="checkbox"]:focus-visible {
|
||
box-shadow: 0 0 0 2px var(--bg, #071326), 0 0 0 4px var(--blue, #38bdf8) !important;
|
||
}
|
||
|
||
/* Disabled */
|
||
input[type="checkbox"]:disabled {
|
||
opacity: 0.4 !important;
|
||
cursor: not-allowed !important;
|
||
}
|
||
|
||
/* Adaptation thème clair */
|
||
html[data-theme="light"] input[type="checkbox"] {
|
||
background-color: rgba(0, 0, 0, 0.06) !important;
|
||
border-color: rgba(0, 0, 0, 0.28) !important;
|
||
}
|
||
|
||
html[data-theme="light"] input[type="checkbox"]::before {
|
||
background-color: #5c5c5c !important;
|
||
}
|
||
|
||
html[data-theme="light"] input[type="checkbox"]:hover {
|
||
background-color: rgba(0, 0, 0, 0.1) !important;
|
||
border-color: rgba(0, 0, 0, 0.45) !important;
|
||
}
|
||
|
||
html[data-theme="light"] input[type="checkbox"]:checked {
|
||
background-color: var(--blue, #0066da) !important;
|
||
border-color: var(--blue, #0066da) !important;
|
||
}
|
||
|
||
html[data-theme="light"] input[type="checkbox"]:checked::before {
|
||
background-color: #ffffff !important;
|
||
}
|
||
|
||
.check {
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
margin-top: 14px;
|
||
cursor: pointer;
|
||
font-size: 14px;
|
||
user-select: none;
|
||
}
|
||
|
||
.notice {
|
||
background: rgba(92, 167, 255, .08);
|
||
border: 1px solid var(--line);
|
||
border-radius: 10px;
|
||
padding: 12px;
|
||
font-size: 13px;
|
||
margin: 16px 0;
|
||
line-height: 1.5
|
||
}
|
||
|
||
.empty {
|
||
color: var(--muted);
|
||
text-align: center;
|
||
padding: 24px
|
||
}
|
||
|
||
#loader {
|
||
position: fixed;
|
||
inset: 0;
|
||
background: var(--bg);
|
||
display: flex;
|
||
flex-direction: column;
|
||
align-items: center;
|
||
justify-content: center;
|
||
z-index: 9999;
|
||
transition: opacity .35s ease, visibility .35s ease;
|
||
padding: 20px
|
||
}
|
||
|
||
#loader.hide {
|
||
opacity: 0 !important;
|
||
pointer-events: none !important
|
||
}
|
||
|
||
#loader.hidden {
|
||
display: none !important;
|
||
visibility: hidden !important;
|
||
opacity: 0 !important;
|
||
pointer-events: none !important
|
||
}
|
||
|
||
.loader-card {
|
||
background: var(--panel);
|
||
border: 1px solid var(--line);
|
||
border-radius: 18px;
|
||
padding: 32px 28px;
|
||
max-width: 440px;
|
||
width: 100%;
|
||
box-shadow: 0 12px 36px rgba(0, 0, 0, .35);
|
||
display: flex;
|
||
flex-direction: column;
|
||
align-items: center;
|
||
gap: 18px
|
||
}
|
||
|
||
.loader-logo-wrap {
|
||
position: relative;
|
||
width: 64px;
|
||
height: 64px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center
|
||
}
|
||
|
||
.loader-radar {
|
||
position: absolute;
|
||
inset: 0;
|
||
border-radius: 50%;
|
||
border: 2px solid rgba(56, 189, 248, .35);
|
||
animation: radarPulse 2s ease-out infinite
|
||
}
|
||
|
||
@keyframes radarPulse {
|
||
0% {
|
||
transform: scale(0.7);
|
||
opacity: 1
|
||
}
|
||
|
||
100% {
|
||
transform: scale(1.5);
|
||
opacity: 0
|
||
}
|
||
}
|
||
|
||
.loader-icon {
|
||
font-size: 32px;
|
||
z-index: 1;
|
||
animation: iconFloat 2s ease-in-out infinite
|
||
}
|
||
|
||
@keyframes iconFloat {
|
||
|
||
0%,
|
||
100% {
|
||
transform: translateY(0)
|
||
}
|
||
|
||
50% {
|
||
transform: translateY(-3px)
|
||
}
|
||
}
|
||
|
||
.loader-progress-box {
|
||
width: 100%;
|
||
margin-top: 4px
|
||
}
|
||
|
||
.loader-bar-bg {
|
||
background: var(--panel2);
|
||
height: 10px;
|
||
border-radius: 8px;
|
||
overflow: hidden;
|
||
border: 1px solid var(--line);
|
||
position: relative
|
||
}
|
||
|
||
.loader-bar-fill {
|
||
width: 0%;
|
||
height: 100%;
|
||
background: linear-gradient(90deg, var(--blue), #38bdf8);
|
||
border-radius: 8px;
|
||
transition: width .35s ease;
|
||
box-shadow: 0 0 10px rgba(56, 189, 248, .4)
|
||
}
|
||
|
||
.loader-checklist {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 8px;
|
||
width: 100%;
|
||
margin-top: 6px;
|
||
border-top: 1px solid var(--line);
|
||
padding-top: 14px
|
||
}
|
||
|
||
.loader-step {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 7px;
|
||
padding: 6px 10px;
|
||
background: var(--panel2);
|
||
border-radius: 8px;
|
||
border: 1px solid transparent;
|
||
font-size: 11px;
|
||
color: var(--muted);
|
||
transition: all .2s ease
|
||
}
|
||
|
||
.loader-step.active {
|
||
border-color: rgba(56, 189, 248, .4);
|
||
background: rgba(56, 189, 248, .08);
|
||
color: var(--text);
|
||
font-weight: 600
|
||
}
|
||
|
||
.loader-step.done {
|
||
border-color: rgba(50, 213, 131, .3);
|
||
background: rgba(50, 213, 131, .08);
|
||
color: var(--green)
|
||
}
|
||
|
||
.loader-step .step-state {
|
||
margin-left: auto;
|
||
font-size: 12px
|
||
}
|
||
|
||
.spinner {
|
||
width: 36px;
|
||
height: 36px;
|
||
border: 3px solid var(--line);
|
||
border-top-color: var(--blue);
|
||
border-radius: 50%;
|
||
animation: spin 1s linear infinite
|
||
}
|
||
|
||
@keyframes spin {
|
||
to {
|
||
transform: rotate(360deg)
|
||
}
|
||
}
|
||
|
||
.recovery-card {
|
||
background: rgba(92, 167, 255, .06);
|
||
border: 1px solid var(--blue);
|
||
border-radius: 12px;
|
||
padding: 16px;
|
||
margin: 16px 0
|
||
}
|
||
|
||
.recovery-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(2, 1fr);
|
||
gap: 10px;
|
||
margin: 12px 0
|
||
}
|
||
|
||
.code-chip {
|
||
background: var(--bg);
|
||
border: 1px solid var(--line);
|
||
padding: 8px 10px;
|
||
border-radius: 8px;
|
||
font-family: monospace;
|
||
font-size: 15px;
|
||
font-weight: 700;
|
||
letter-spacing: 1px;
|
||
text-align: center;
|
||
color: var(--blue);
|
||
user-select: all
|
||
}
|
||
|
||
.recovery-actions {
|
||
display: flex;
|
||
gap: 10px;
|
||
margin-top: 10px;
|
||
flex-wrap: wrap
|
||
}
|
||
|
||
.stats-range-container {
|
||
display: inline-flex;
|
||
background: var(--panel2);
|
||
border-radius: 10px;
|
||
padding: 3px;
|
||
gap: 2px;
|
||
border: 1px solid var(--line)
|
||
}
|
||
|
||
.stats-range-btn {
|
||
border: 0;
|
||
cursor: pointer;
|
||
background: transparent;
|
||
color: var(--muted);
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
padding: 7px 14px;
|
||
border-radius: 8px;
|
||
transition: all .2s ease
|
||
}
|
||
|
||
.stats-range-btn:hover {
|
||
color: var(--text)
|
||
}
|
||
|
||
.stats-range-btn.active {
|
||
background: var(--blue) !important;
|
||
color: var(--blue-text, #071326) !important;
|
||
font-weight: 700;
|
||
box-shadow: 0 2px 8px rgba(92, 167, 255, .35)
|
||
}
|
||
|
||
.chart-box {
|
||
position: relative;
|
||
width: 100%;
|
||
min-height: 300px;
|
||
height: 340px;
|
||
margin-top: 10px
|
||
}
|
||
|
||
.device-pill {
|
||
display: inline-block;
|
||
padding: 3px 8px;
|
||
border-radius: 6px;
|
||
background: var(--panel2);
|
||
border: 1px solid var(--line);
|
||
color: var(--text);
|
||
font-size: 11px;
|
||
margin: 2px 4px 2px 0
|
||
}
|
||
|
||
.svg-bar {
|
||
transition: opacity .2s;
|
||
cursor: pointer
|
||
}
|
||
|
||
.svg-bar:hover {
|
||
opacity: .8
|
||
}
|
||
|
||
.pagination {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
margin-top: 14px;
|
||
padding-top: 12px;
|
||
border-top: 1px solid var(--line);
|
||
font-size: 13px;
|
||
color: var(--muted);
|
||
gap: 10px;
|
||
flex-wrap: wrap
|
||
}
|
||
|
||
.pagination-info {
|
||
font-size: 13px;
|
||
color: var(--muted)
|
||
}
|
||
|
||
.pagination-info strong {
|
||
color: var(--text)
|
||
}
|
||
|
||
.pagination-btns {
|
||
display: flex;
|
||
gap: 6px;
|
||
align-items: center;
|
||
flex-wrap: wrap
|
||
}
|
||
|
||
.pagination button {
|
||
padding: 6px 12px;
|
||
font-size: 12px;
|
||
border-radius: 8px;
|
||
min-width: 32px;
|
||
text-align: center
|
||
}
|
||
|
||
.pagination button:disabled {
|
||
opacity: .35;
|
||
cursor: not-allowed;
|
||
pointer-events: none
|
||
}
|
||
|
||
.proto-badge {
|
||
display: inline-block;
|
||
padding: 2px 8px;
|
||
border-radius: 5px;
|
||
font-size: 11px;
|
||
font-weight: 700;
|
||
letter-spacing: 0.5px;
|
||
font-family: monospace;
|
||
text-transform: uppercase
|
||
}
|
||
|
||
.proto-dns {
|
||
background: rgba(30, 144, 255, .2);
|
||
color: #38bdf8;
|
||
border: 1px solid rgba(56, 189, 248, .35)
|
||
}
|
||
|
||
.proto-icmp {
|
||
background: rgba(236, 72, 153, .2);
|
||
color: #f472b6;
|
||
border: 1px solid rgba(244, 114, 182, .35)
|
||
}
|
||
|
||
.proto-tcp {
|
||
background: rgba(148, 163, 184, .2);
|
||
color: #cbd5e1;
|
||
border: 1px solid rgba(203, 213, 225, .35)
|
||
}
|
||
|
||
.proto-udp {
|
||
background: rgba(168, 85, 247, .2);
|
||
color: #c084fc;
|
||
border: 1px solid rgba(192, 132, 252, .35)
|
||
}
|
||
|
||
.proto-arp {
|
||
background: rgba(234, 179, 8, .2);
|
||
color: #facc15;
|
||
border: 1px solid rgba(250, 204, 21, .35)
|
||
}
|
||
|
||
.proto-dhcp {
|
||
background: rgba(249, 115, 22, .2);
|
||
color: #fb923c;
|
||
border: 1px solid rgba(251, 146, 60, .35)
|
||
}
|
||
|
||
.proto-tls {
|
||
background: rgba(34, 197, 94, .2);
|
||
color: #4ade80;
|
||
border: 1px solid rgba(74, 222, 128, .35)
|
||
}
|
||
|
||
.proto-http {
|
||
background: rgba(16, 185, 129, .2);
|
||
color: #34d399;
|
||
border: 1px solid rgba(52, 211, 153, .35)
|
||
}
|
||
|
||
.proto-mdns {
|
||
background: rgba(99, 102, 241, .2);
|
||
color: #818cf8;
|
||
border: 1px solid rgba(129, 140, 248, .35)
|
||
}
|
||
|
||
.proto-other {
|
||
background: rgba(100, 116, 139, .2);
|
||
color: #94a3b8;
|
||
border: 1px solid rgba(148, 163, 184, .35)
|
||
}
|
||
|
||
.capture-actions {
|
||
display: flex;
|
||
gap: 8px;
|
||
flex-wrap: wrap;
|
||
align-items: center
|
||
}
|
||
|
||
.filter-chips {
|
||
display: flex;
|
||
gap: 6px;
|
||
flex-wrap: wrap;
|
||
align-items: center;
|
||
margin: 10px 0 6px
|
||
}
|
||
|
||
.filter-chip {
|
||
background: var(--panel2);
|
||
border: 1px solid var(--line);
|
||
color: var(--muted);
|
||
padding: 5px 12px;
|
||
border-radius: 7px;
|
||
font-size: 12px;
|
||
cursor: pointer;
|
||
font-family: monospace;
|
||
font-weight: 600;
|
||
transition: all .15s ease
|
||
}
|
||
|
||
.filter-chip:hover {
|
||
color: var(--text);
|
||
border-color: var(--blue)
|
||
}
|
||
|
||
.filter-chip.active {
|
||
background: var(--blue) !important;
|
||
color: var(--blue-text, #071326) !important;
|
||
border-color: var(--blue) !important;
|
||
font-weight: 700
|
||
}
|
||
|
||
.wireshark-filter-bar {
|
||
display: flex;
|
||
gap: 12px;
|
||
align-items: center;
|
||
margin: 10px 0 14px;
|
||
flex-wrap: wrap
|
||
}
|
||
|
||
.filter-input-wrap {
|
||
position: relative;
|
||
flex: 1;
|
||
min-width: 240px
|
||
}
|
||
|
||
.filter-input-wrap input {
|
||
width: 100%;
|
||
padding: 10px 38px 10px 36px;
|
||
border-radius: 8px;
|
||
border: 1px solid var(--line);
|
||
background: var(--panel2);
|
||
color: var(--text);
|
||
font-family: monospace;
|
||
font-size: 13px;
|
||
box-sizing: border-box
|
||
}
|
||
|
||
.filter-input-wrap .filter-icon {
|
||
position: absolute;
|
||
left: 12px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
color: var(--muted);
|
||
pointer-events: none
|
||
}
|
||
|
||
.filter-input-wrap .clear-filter-btn {
|
||
position: absolute;
|
||
right: 8px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
background: transparent;
|
||
border: none;
|
||
color: var(--muted);
|
||
cursor: pointer;
|
||
padding: 4px 8px;
|
||
font-size: 14px
|
||
}
|
||
|
||
.filter-side-controls {
|
||
display: flex;
|
||
gap: 12px;
|
||
align-items: center;
|
||
flex-shrink: 0
|
||
}
|
||
|
||
.packet-row {
|
||
cursor: pointer;
|
||
transition: background .15s
|
||
}
|
||
|
||
.packet-row:hover {
|
||
background: rgba(92, 167, 255, .08) !important
|
||
}
|
||
|
||
.ip-country-badge {
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 4px;
|
||
padding: 2px 6px;
|
||
border-radius: 4px;
|
||
font-size: 11px;
|
||
font-weight: 700;
|
||
line-height: 1.2;
|
||
white-space: nowrap;
|
||
background: rgba(255, 255, 255, 0.06);
|
||
border: 1px solid var(--line);
|
||
cursor: default;
|
||
vertical-align: middle
|
||
}
|
||
|
||
.ip-country-badge.badge-lan {
|
||
background: rgba(92, 167, 255, .14);
|
||
border-color: rgba(92, 167, 255, .35);
|
||
color: var(--blue)
|
||
}
|
||
|
||
.ip-country-badge.badge-country {
|
||
background: rgba(34, 197, 94, .14);
|
||
border-color: rgba(34, 197, 94, .35);
|
||
color: var(--green)
|
||
}
|
||
|
||
.ip-country-badge.badge-ext {
|
||
background: rgba(234, 179, 8, .14);
|
||
border-color: rgba(234, 179, 8, .35);
|
||
color: #facc15
|
||
}
|
||
|
||
.ip-country-badge .country-code {
|
||
font-family: monospace;
|
||
font-size: 10px;
|
||
opacity: .95;
|
||
letter-spacing: 0.5px
|
||
}
|
||
|
||
.ip-country-badge .flag-icon-wrap {
|
||
display: inline-flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
line-height: 1;
|
||
flex-shrink: 0
|
||
}
|
||
|
||
.ip-country-badge .flag-icon {
|
||
display: inline-block;
|
||
vertical-align: middle;
|
||
border-radius: 2px;
|
||
box-shadow: 0 0 1px rgba(0, 0, 0, 0.5);
|
||
flex-shrink: 0
|
||
}
|
||
|
||
.ip-country-badge.country-filter-tag {
|
||
cursor: pointer;
|
||
transition: transform .12s, filter .12s
|
||
}
|
||
|
||
.ip-country-badge.country-filter-tag:hover {
|
||
filter: brightness(1.2);
|
||
border-color: var(--blue);
|
||
transform: translateY(-1px)
|
||
}
|
||
|
||
.badge-vpn-wg {
|
||
background: rgba(184, 27, 27, .18);
|
||
border: 1px solid rgba(220, 38, 38, .4);
|
||
color: #fca5a5
|
||
}
|
||
|
||
.badge-vpn-ovpn {
|
||
background: rgba(234, 88, 12, .18);
|
||
border: 1px solid rgba(234, 88, 12, .4);
|
||
color: #fdba74
|
||
}
|
||
|
||
.vpn-badge-mini {
|
||
display: inline-flex;
|
||
align-items: center;
|
||
padding: 2px 4px;
|
||
border-radius: 4px;
|
||
vertical-align: middle
|
||
}
|
||
|
||
.vpn-type-logo {
|
||
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.35));
|
||
flex-shrink: 0
|
||
}
|
||
|
||
.icon-result-card {
|
||
background: var(--panel2);
|
||
border: 1px solid var(--line);
|
||
border-radius: 8px;
|
||
display: flex;
|
||
flex-direction: column;
|
||
align-items: center;
|
||
justify-content: center;
|
||
cursor: pointer;
|
||
padding: 4px 2px;
|
||
height: 44px;
|
||
transition: all .15s ease;
|
||
user-select: none;
|
||
box-sizing: border-box
|
||
}
|
||
|
||
.icon-result-card:hover {
|
||
border-color: var(--blue);
|
||
background: rgba(56, 189, 248, .12);
|
||
transform: translateY(-1px)
|
||
}
|
||
|
||
.icon-result-card.active {
|
||
border-color: var(--blue);
|
||
background: rgba(56, 189, 248, .2);
|
||
box-shadow: 0 0 0 1.5px var(--blue)
|
||
}
|
||
|
||
.icon-result-tag {
|
||
font-size: 9px;
|
||
color: var(--muted);
|
||
max-width: 100%;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
white-space: nowrap;
|
||
margin-top: 2px;
|
||
line-height: 1;
|
||
padding: 0 2px
|
||
}
|
||
|
||
.settings-grid {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 18px;
|
||
margin-top: 18px;
|
||
align-items: start
|
||
}
|
||
|
||
.mode-selector-grid {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 12px;
|
||
margin: 7px 0 16px
|
||
}
|
||
|
||
.modal-overlay {
|
||
display: none;
|
||
position: fixed;
|
||
inset: 0;
|
||
background: rgba(0, 0, 0, 0.72);
|
||
z-index: 999;
|
||
align-items: center;
|
||
justify-content: center;
|
||
padding: 16px;
|
||
backdrop-filter: blur(3px)
|
||
}
|
||
|
||
.modal-overlay.active {
|
||
display: flex
|
||
}
|
||
|
||
.modal-card {
|
||
background: var(--panel);
|
||
border: 1px solid var(--line);
|
||
border-radius: 14px;
|
||
max-width: 760px;
|
||
width: 100%;
|
||
max-height: 90vh;
|
||
display: flex;
|
||
flex-direction: column;
|
||
box-shadow: 0 12px 40px rgba(0, 0, 0, .5);
|
||
overflow: hidden
|
||
}
|
||
|
||
.modal-header {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
padding: 16px 20px;
|
||
border-bottom: 1px solid var(--line)
|
||
}
|
||
|
||
.modal-body {
|
||
padding: 16px 20px;
|
||
overflow-y: auto;
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 14px
|
||
}
|
||
|
||
.modal-footer {
|
||
padding: 12px 20px;
|
||
border-top: 1px solid var(--line);
|
||
display: flex;
|
||
justify-content: flex-end
|
||
}
|
||
|
||
/* Topologie Réseau */
|
||
.topo-map-card {
|
||
background: linear-gradient(180deg, rgba(13, 29, 54, .96), rgba(7, 19, 38, .98));
|
||
border: 1px solid var(--line);
|
||
border-radius: 14px;
|
||
box-shadow: inset 0 0 60px rgba(0, 0, 0, .3);
|
||
position: relative;
|
||
overflow: hidden;
|
||
min-height: 520px;
|
||
padding: 28px 16px
|
||
}
|
||
|
||
.topo-node {
|
||
background: var(--panel2);
|
||
border: 1px solid var(--line);
|
||
border-radius: 14px;
|
||
padding: 12px 18px;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 14px;
|
||
cursor: pointer;
|
||
transition: all .2s ease;
|
||
box-shadow: 0 4px 16px rgba(0, 0, 0, .25);
|
||
position: relative;
|
||
user-select: none;
|
||
max-width: 420px;
|
||
width: 100%
|
||
}
|
||
|
||
.topo-node:hover {
|
||
transform: translateY(-3px);
|
||
border-color: var(--blue);
|
||
box-shadow: 0 8px 24px rgba(92, 167, 255, .22)
|
||
}
|
||
|
||
.topo-node-icon {
|
||
width: 44px;
|
||
height: 44px;
|
||
border-radius: 12px;
|
||
background: var(--panel);
|
||
border: 1px solid var(--line);
|
||
display: grid;
|
||
place-items: center;
|
||
font-size: 22px;
|
||
flex-shrink: 0
|
||
}
|
||
|
||
.topo-node-title {
|
||
font-weight: 700;
|
||
font-size: 15px;
|
||
color: var(--text)
|
||
}
|
||
|
||
.topo-node-sub {
|
||
font-size: 13px;
|
||
color: var(--muted);
|
||
font-family: ui-monospace, monospace
|
||
}
|
||
|
||
.topo-node-ap {
|
||
border-color: var(--line);
|
||
background: var(--panel2);
|
||
}
|
||
|
||
.topo-node-ap:hover {
|
||
border-color: var(--blue);
|
||
}
|
||
|
||
.topo-level1-single {
|
||
display: flex;
|
||
justify-content: center;
|
||
align-items: center;
|
||
width: 100%;
|
||
max-width: 920px
|
||
}
|
||
|
||
.topo-level1-grid {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 20px;
|
||
width: 100%;
|
||
max-width: 920px;
|
||
align-items: start
|
||
}
|
||
|
||
@media (max-width:680px) {
|
||
.topo-level1-grid {
|
||
display: grid !important;
|
||
grid-template-columns: 1fr 1fr !important;
|
||
gap: 10px !important;
|
||
align-items: start !important
|
||
}
|
||
|
||
.topo-level1-grid .topo-node {
|
||
padding: 10px 10px !important;
|
||
gap: 8px !important
|
||
}
|
||
|
||
.topo-level1-grid .topo-node-icon {
|
||
width: 36px !important;
|
||
height: 36px !important;
|
||
font-size: 18px !important;
|
||
border-radius: 10px !important
|
||
}
|
||
|
||
.topo-level1-grid .topo-node-title {
|
||
font-size: 12px !important;
|
||
line-height: 1.2 !important
|
||
}
|
||
|
||
.topo-level1-grid .topo-node-sub {
|
||
font-size: 11px !important
|
||
}
|
||
|
||
.topo-level1-grid .muted {
|
||
font-size: 10px !important
|
||
}
|
||
}
|
||
|
||
@media (max-width:480px) {
|
||
.topo-level1-grid {
|
||
gap: 8px !important
|
||
}
|
||
|
||
.topo-level1-grid .topo-node {
|
||
padding: 8px 8px !important;
|
||
gap: 6px !important;
|
||
border-radius: 10px !important
|
||
}
|
||
|
||
.topo-level1-grid .topo-node-icon {
|
||
width: 30px !important;
|
||
height: 30px !important;
|
||
font-size: 15px !important;
|
||
border-radius: 8px !important
|
||
}
|
||
|
||
.topo-level1-grid .topo-node-title {
|
||
font-size: 11px !important
|
||
}
|
||
|
||
.topo-level1-grid .topo-node-sub {
|
||
font-size: 9.5px !important
|
||
}
|
||
|
||
.topo-level1-grid .dot {
|
||
width: 8px !important;
|
||
height: 8px !important
|
||
}
|
||
}
|
||
|
||
.topo-vertical-link {
|
||
display: flex;
|
||
flex-direction: column;
|
||
align-items: center;
|
||
gap: 6px
|
||
}
|
||
|
||
@keyframes topoDashFlow {
|
||
to {
|
||
stroke-dashoffset: -24
|
||
}
|
||
}
|
||
|
||
@keyframes topoPulseGlow {
|
||
|
||
0%,
|
||
100% {
|
||
opacity: 0.2;
|
||
stroke-width: 2.5px
|
||
}
|
||
|
||
50% {
|
||
opacity: 0.55;
|
||
stroke-width: 4px
|
||
}
|
||
}
|
||
|
||
@keyframes topoPulseDot {
|
||
|
||
0%,
|
||
100% {
|
||
transform: scale(1);
|
||
opacity: 0.8
|
||
}
|
||
|
||
50% {
|
||
transform: scale(1.35);
|
||
opacity: 1
|
||
}
|
||
}
|
||
|
||
@keyframes topoWanFlow {
|
||
0% {
|
||
background-position: 0 0
|
||
}
|
||
|
||
100% {
|
||
background-position: 0 24px
|
||
}
|
||
}
|
||
|
||
.topo-link-line {
|
||
width: 4px;
|
||
height: 28px;
|
||
background-color: #5ca7ff;
|
||
background-color: var(--blue);
|
||
border-left: 2px solid var(--blue);
|
||
border-right: 2px solid var(--blue);
|
||
background-image: repeating-linear-gradient(to bottom, var(--blue) 0px, var(--blue) 6px, rgba(92, 167, 255, 0.25) 6px, rgba(92, 167, 255, 0.25) 12px);
|
||
background-size: 100% 24px;
|
||
animation: topoWanFlow 0.85s linear infinite;
|
||
box-shadow: 0 0 12px rgba(92, 167, 255, .7);
|
||
border-radius: 2px
|
||
}
|
||
|
||
.topo-line-glow {
|
||
animation: topoPulseGlow 3s ease-in-out infinite
|
||
}
|
||
|
||
.topo-line-flow {
|
||
stroke-dasharray: 6 6;
|
||
animation: topoDashFlow 1.1s linear infinite
|
||
}
|
||
|
||
.topo-end-dot {
|
||
transform-origin: center;
|
||
animation: topoPulseDot 2s ease-in-out infinite
|
||
}
|
||
|
||
.topo-link-badge {
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
color: var(--muted);
|
||
background: var(--panel);
|
||
padding: 2px 10px;
|
||
border-radius: 10px;
|
||
border: 1px solid var(--line)
|
||
}
|
||
|
||
.topo-clients-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fit, minmax(270px, 1fr));
|
||
gap: 16px;
|
||
width: 100%;
|
||
margin-top: 8px
|
||
}
|
||
|
||
.topo-client-card {
|
||
background: var(--panel2);
|
||
border: 1px solid var(--line);
|
||
border-radius: 12px;
|
||
padding: 14px;
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 10px;
|
||
cursor: pointer;
|
||
transition: all .2s ease;
|
||
box-shadow: 0 3px 12px rgba(0, 0, 0, .2);
|
||
position: relative
|
||
}
|
||
|
||
.topo-client-card:hover {
|
||
transform: translateY(-3px);
|
||
border-color: var(--blue);
|
||
box-shadow: 0 6px 20px rgba(92, 167, 255, .2)
|
||
}
|
||
|
||
.topo-client-header {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
gap: 8px
|
||
}
|
||
|
||
.topo-client-type {
|
||
width: 34px;
|
||
height: 34px;
|
||
border-radius: 8px;
|
||
background: var(--panel);
|
||
display: grid;
|
||
place-items: center;
|
||
font-size: 18px;
|
||
flex-shrink: 0
|
||
}
|
||
|
||
.topo-client-name {
|
||
font-weight: 700;
|
||
font-size: 14px;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
white-space: nowrap;
|
||
max-width: 140px
|
||
}
|
||
|
||
.topo-client-body {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 6px;
|
||
font-size: 12px;
|
||
background: var(--panel);
|
||
padding: 8px 10px;
|
||
border-radius: 8px;
|
||
border: 1px solid rgba(255, 255, 255, .04)
|
||
}
|
||
|
||
.topo-client-speeds {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
font-size: 12px;
|
||
font-weight: 600;
|
||
padding: 2px 4px
|
||
}
|
||
|
||
.topo-signal-bars {
|
||
display: inline-flex;
|
||
gap: 2px;
|
||
align-items: flex-end;
|
||
height: 12px
|
||
}
|
||
|
||
.topo-signal-bar {
|
||
width: 3px;
|
||
background: rgba(255, 255, 255, .2);
|
||
border-radius: 1px
|
||
}
|
||
|
||
.topo-signal-bar.active-green {
|
||
background: var(--green)
|
||
}
|
||
|
||
.topo-signal-bar.active-yellow {
|
||
background: #f6ad55
|
||
}
|
||
|
||
.topo-signal-bar.active-red {
|
||
background: var(--red)
|
||
}
|
||
|
||
.topo-actions {
|
||
display: flex;
|
||
gap: 6px;
|
||
margin-top: 2px
|
||
}
|
||
|
||
.topo-actions button {
|
||
flex: 1;
|
||
padding: 5px 8px;
|
||
font-size: 12px
|
||
}
|
||
|
||
.topo-progress-track {
|
||
height: 6px;
|
||
background: var(--panel);
|
||
border-radius: 3px;
|
||
overflow: hidden;
|
||
position: relative
|
||
}
|
||
|
||
.topo-progress-fill {
|
||
height: 100%;
|
||
border-radius: 3px;
|
||
transition: width .3s ease
|
||
}
|
||
|
||
|
||
/* Tablette et écrans intermédiaires (<= 1100px) */
|
||
@media (max-width:1100px) {
|
||
.wrap {
|
||
padding: 18px 16px 36px;
|
||
max-width: 100%
|
||
}
|
||
|
||
.layout {
|
||
grid-template-columns: 1fr;
|
||
gap: 18px
|
||
}
|
||
|
||
.layout>aside {
|
||
position: static;
|
||
width: 100%
|
||
}
|
||
|
||
.settings-grid {
|
||
grid-template-columns: 1fr;
|
||
gap: 16px
|
||
}
|
||
|
||
.grid {
|
||
grid-template-columns: repeat(2, 1fr);
|
||
gap: 14px
|
||
}
|
||
|
||
.chart-box {
|
||
height: 280px;
|
||
min-height: 260px
|
||
}
|
||
}
|
||
|
||
/* Téléphone et écrans compacts (<= 600px) */
|
||
@media (max-width:600px) {
|
||
.wrap {
|
||
padding: 12px 10px 32px
|
||
}
|
||
|
||
header {
|
||
flex-direction: column;
|
||
align-items: stretch;
|
||
gap: 12px;
|
||
margin-bottom: 14px
|
||
}
|
||
|
||
h1 {
|
||
font-size: 20px;
|
||
line-height: 1.25
|
||
}
|
||
|
||
h2 {
|
||
font-size: 16px
|
||
}
|
||
|
||
.sub {
|
||
font-size: 13px
|
||
}
|
||
|
||
.header-actions {
|
||
display: grid !important;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 8px;
|
||
width: 100%
|
||
}
|
||
|
||
.topo-clients-grid {
|
||
grid-template-columns: 1fr !important
|
||
}
|
||
|
||
.topo-node {
|
||
max-width: 100% !important
|
||
}
|
||
|
||
.header-actions button {
|
||
width: 100%;
|
||
padding: 10px 6px;
|
||
font-size: 13px;
|
||
min-height: 42px;
|
||
height: auto;
|
||
text-align: center
|
||
}
|
||
|
||
nav {
|
||
gap: 6px;
|
||
padding-bottom: 8px;
|
||
margin-bottom: 14px;
|
||
-webkit-overflow-scrolling: touch;
|
||
scrollbar-width: none
|
||
}
|
||
|
||
nav::-webkit-scrollbar {
|
||
display: none
|
||
}
|
||
|
||
nav button,
|
||
nav button.secondary {
|
||
padding: 7px 12px;
|
||
font-size: 13px;
|
||
min-height: 38px
|
||
}
|
||
|
||
.card {
|
||
padding: 14px 12px;
|
||
border-radius: 12px;
|
||
margin-bottom: 14px
|
||
}
|
||
|
||
.grid {
|
||
grid-template-columns: repeat(2, 1fr);
|
||
gap: 10px;
|
||
margin-bottom: 14px
|
||
}
|
||
|
||
.metric {
|
||
font-size: 20px;
|
||
margin-top: 4px
|
||
}
|
||
|
||
.card .label {
|
||
font-size: 11px;
|
||
margin-top: 2px
|
||
}
|
||
|
||
.layout {
|
||
grid-template-columns: 1fr;
|
||
gap: 14px
|
||
}
|
||
|
||
.layout>aside {
|
||
position: static;
|
||
width: 100%
|
||
}
|
||
|
||
.qr-card-content {
|
||
max-width: 100%
|
||
}
|
||
|
||
.client strong {
|
||
max-width: 120px
|
||
}
|
||
|
||
#qrcode,
|
||
#twoFaQr {
|
||
width: 202px;
|
||
height: 202px;
|
||
padding: 12px !important;
|
||
margin-bottom: 12px
|
||
}
|
||
|
||
.settings-nav {
|
||
gap: 6px;
|
||
margin-bottom: 14px
|
||
}
|
||
|
||
.settings-nav-btn {
|
||
padding: 6px 9px;
|
||
font-size: 12px;
|
||
min-height: 36px
|
||
}
|
||
|
||
.settings-panel {
|
||
max-width: 100%
|
||
}
|
||
|
||
.topline {
|
||
flex-direction: column;
|
||
align-items: flex-start;
|
||
gap: 8px
|
||
}
|
||
|
||
.table-wrap {
|
||
width: 100%;
|
||
overflow-x: auto;
|
||
-webkit-overflow-scrolling: touch;
|
||
border-radius: 8px
|
||
}
|
||
|
||
th,
|
||
td {
|
||
padding: 8px 6px;
|
||
font-size: 13px
|
||
}
|
||
|
||
th {
|
||
font-size: 11px
|
||
}
|
||
|
||
.stats-range-container {
|
||
display: grid !important;
|
||
grid-template-columns: repeat(2, 1fr) !important;
|
||
gap: 4px !important;
|
||
width: 100%
|
||
}
|
||
|
||
.stats-range-btn {
|
||
padding: 8px 6px;
|
||
font-size: 12px;
|
||
text-align: center;
|
||
width: 100%
|
||
}
|
||
|
||
.chart-box {
|
||
height: 240px;
|
||
min-height: 220px
|
||
}
|
||
|
||
.capture-actions {
|
||
display: grid !important;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 8px;
|
||
width: 100%
|
||
}
|
||
|
||
.capture-actions button {
|
||
width: 100%;
|
||
padding: 9px 6px;
|
||
font-size: 12px;
|
||
min-height: 40px;
|
||
text-align: center
|
||
}
|
||
|
||
.filter-chips {
|
||
gap: 4px;
|
||
overflow-x: auto;
|
||
-webkit-overflow-scrolling: touch
|
||
}
|
||
|
||
.filter-chip {
|
||
padding: 4px 8px;
|
||
font-size: 11px
|
||
}
|
||
|
||
.wireshark-filter-bar {
|
||
flex-direction: column;
|
||
align-items: stretch;
|
||
gap: 8px
|
||
}
|
||
|
||
.filter-input-wrap {
|
||
width: 100%;
|
||
min-width: unset
|
||
}
|
||
|
||
.filter-side-controls {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
width: 100%
|
||
}
|
||
|
||
.settings-grid {
|
||
grid-template-columns: 1fr;
|
||
gap: 14px
|
||
}
|
||
|
||
.mode-selector-grid {
|
||
grid-template-columns: 1fr !important;
|
||
gap: 8px !important
|
||
}
|
||
|
||
.pagination {
|
||
flex-direction: column;
|
||
align-items: center;
|
||
gap: 10px;
|
||
text-align: center
|
||
}
|
||
|
||
.pagination-btns {
|
||
justify-content: center;
|
||
width: 100%
|
||
}
|
||
|
||
#authView .card,
|
||
#setupView .card {
|
||
margin: 16px auto !important;
|
||
padding: 16px 14px !important;
|
||
max-width: 100% !important
|
||
}
|
||
|
||
.modal-overlay {
|
||
padding: 8px
|
||
}
|
||
|
||
.modal-card {
|
||
max-height: 94vh;
|
||
width: 100%;
|
||
border-radius: 10px
|
||
}
|
||
|
||
.modal-header {
|
||
padding: 12px 14px
|
||
}
|
||
|
||
.modal-body {
|
||
padding: 12px 14px;
|
||
gap: 10px
|
||
}
|
||
|
||
.modal-footer {
|
||
padding: 10px 14px
|
||
}
|
||
}
|
||
|
||
/* Écrans très étroits (<= 380px) */
|
||
@media (max-width:380px) {
|
||
.grid {
|
||
grid-template-columns: 1fr
|
||
}
|
||
|
||
.header-actions {
|
||
grid-template-columns: 1fr
|
||
}
|
||
|
||
.capture-actions {
|
||
grid-template-columns: 1fr
|
||
}
|
||
}
|
||
|
||
</style>
|
||
<link rel="stylesheet" href="/themes/dark.css">
|
||
<link rel="stylesheet" href="/themes/light.css">
|
||
<link rel="stylesheet" href="/themes/winxp.css">
|
||
<link rel="stylesheet" href="/themes/futuristic.css">
|
||
<link rel="stylesheet" href="/themes/macos.css">
|
||
<link rel="stylesheet" href="/themes/hacker.css">
|
||
</head>
|
||
|
||
<body>
|
||
<div id="loader">
|
||
|
||
|
||
<div class="loader-card">
|
||
<div class="loader-logo-wrap">
|
||
<div class="loader-radar"></div>
|
||
<div id="loaderTopIcon" class="loader-icon">📶</div>
|
||
</div>
|
||
<div style="text-align:center">
|
||
<h2 class="app-title" style="margin:0;font-size:20px;letter-spacing:-0.3px" data-i18n="loader_title">
|
||
Administration de l’AP Wi‑Fi</h2>
|
||
<div class="sub" style="margin-top:4px"><span class="app-short-title">AP Manageur</span> <span
|
||
class="app-version"
|
||
style="font-weight:700;background:var(--panel2);padding:2px 8px;border-radius:6px;border:1px solid var(--line);color:var(--blue);font-size:11px;margin-left:4px">V5.5</span>
|
||
</div>
|
||
<div id="loaderBadge"
|
||
style="display:inline-flex;align-items:center;gap:6px;background:rgba(56,189,248,0.12);border:1px solid rgba(56,189,248,0.3);color:var(--blue);padding:3px 12px;border-radius:20px;font-size:12px;font-weight:600;margin-top:8px">
|
||
<span id="loaderBadgeIcon"
|
||
style="display:inline-flex;align-items:center;justify-content:center;animation:spin 1.5s linear infinite">⚙️</span>
|
||
<span id="loaderBadgeText" data-i18n="loader_starting_badge">Démarrage en cours</span>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Barre de progression -->
|
||
<div class="loader-progress-box">
|
||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;font-size:12px">
|
||
<span id="loaderStepLabel" style="font-weight:600;color:var(--text)" data-i18n="loader_step1_label">Étape 1 /
|
||
4</span>
|
||
<span id="loaderPercent" style="font-weight:700;color:var(--blue);font-family:monospace">0%</span>
|
||
</div>
|
||
<div class="loader-bar-bg">
|
||
<div id="loaderProgressBar" class="loader-bar-fill"></div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Libellés d'état dynamique -->
|
||
<div style="text-align:center;min-height:44px">
|
||
<div id="loaderStatusText" style="font-weight:700;font-size:15px;color:var(--text)" data-i18n="loader_starting">
|
||
Démarrage en cours…</div>
|
||
<div id="loaderStepDetails" class="muted" style="font-size:12px;margin-top:3px" data-i18n="loader_step1_sub">
|
||
Connexion au serveur et vérification de la session…</div>
|
||
</div>
|
||
|
||
<!-- Checklist visuelle des étapes -->
|
||
<div class="loader-checklist">
|
||
<div id="stepCheckApi" class="loader-step active">
|
||
<span class="step-icon">🌐</span>
|
||
<span class="step-name" data-i18n="loader_step1">API & Session</span>
|
||
<span class="step-state" style="font-weight:700">↻</span>
|
||
</div>
|
||
<div id="stepCheckWifi" class="loader-step">
|
||
<span class="step-icon">📶</span>
|
||
<span class="step-name" data-i18n="loader_step2">Réseau Wi-Fi</span>
|
||
<span class="step-state">⏳</span>
|
||
</div>
|
||
<div id="stepCheckVpn" class="loader-step">
|
||
<span class="step-icon">🛡️</span>
|
||
<span class="step-name" data-i18n="loader_step3">Tests & VPN</span>
|
||
<span class="step-state">⏳</span>
|
||
</div>
|
||
<div id="stepCheckDashboard" class="loader-step">
|
||
<span class="step-icon">📊</span>
|
||
<span class="step-name" data-i18n="loader_step4">Tableau de bord</span>
|
||
<span class="step-state">⏳</span>
|
||
</div>
|
||
</div>
|
||
<div style="text-align:center;margin-top:14px">
|
||
<button id="btnSkipLoader" type="button" class="secondary"
|
||
style="display:inline-block;padding:8px 18px;font-size:13px;font-weight:600;border-radius:20px;border:1px solid var(--line);color:var(--text);background:var(--panel2);cursor:pointer;transition:all .2s ease"
|
||
onclick="skipLoaderToDashboard()" data-i18n="loader_skip">Passer au tableau de bord →</button>
|
||
</div>
|
||
</div>
|
||
<script>
|
||
(function () {
|
||
try {
|
||
var l = localStorage.getItem('apLanguage') || 'fr';
|
||
if (l && l.startsWith('en')) {
|
||
var b = document.getElementById('loaderBadgeText');
|
||
var s = document.getElementById('loaderStatusText');
|
||
var d = document.getElementById('loaderStepDetails');
|
||
var step = document.getElementById('loaderStepLabel');
|
||
var skip = document.getElementById('btnSkipLoader');
|
||
var title = document.querySelector('[data-i18n="loader_title"]');
|
||
var t1 = document.querySelector('#stepCheckApi .step-name');
|
||
var t2 = document.querySelector('#stepCheckWifi .step-name');
|
||
var t3 = document.querySelector('#stepCheckVpn .step-name');
|
||
var t4 = document.querySelector('#stepCheckDashboard .step-name');
|
||
var isRefresh = (sessionStorage.getItem('apAppStarted') || localStorage.getItem('apAppStarted')) === '1';
|
||
if (title) title.textContent = "Wi-Fi AP Administration";
|
||
if (b) b.textContent = isRefresh ? "Refreshing" : "Starting up";
|
||
if (s) s.textContent = isRefresh ? "Refreshing…" : "Starting up…";
|
||
if (d) d.textContent = "Connecting to server and verifying session…";
|
||
if (step) step.textContent = "Step 1 of 4";
|
||
if (skip) skip.textContent = "Skip to dashboard →";
|
||
if (t1) t1.textContent = "API & Session";
|
||
if (t2) t2.textContent = "Wi-Fi Network";
|
||
if (t3) t3.textContent = "Tests & VPN";
|
||
if (t4) t4.textContent = "Dashboard";
|
||
}
|
||
} catch (_) { }
|
||
})();
|
||
|
||
// Définition autonome immédiate de skipLoaderToDashboard
|
||
window.skipLoaderToDashboard = function () {
|
||
try {
|
||
window.loaderSkipped = true;
|
||
var l = document.getElementById('loader');
|
||
if (l) {
|
||
l.style.opacity = '0';
|
||
l.style.pointerEvents = 'none';
|
||
l.classList.add('hide');
|
||
setTimeout(function () {
|
||
l.style.display = 'none';
|
||
l.classList.add('hidden');
|
||
}, 260);
|
||
}
|
||
var tok = localStorage.getItem('apAuthToken') || sessionStorage.getItem('apAuthToken') || (document.cookie.match(/apAuthToken=([^;]+)/) || [])[1];
|
||
var authV = document.getElementById('authView');
|
||
var appEl = document.getElementById('app');
|
||
if (tok) {
|
||
if (authV) { authV.classList.remove('active'); authV.style.display = 'none'; }
|
||
if (appEl) { appEl.style.display = 'block'; }
|
||
var dashV = document.getElementById('dashboardView');
|
||
if (dashV && !document.querySelector('.view.active')) dashV.classList.add('active');
|
||
if (typeof showApp === 'function') {
|
||
try { showApp(); } catch (_) { }
|
||
}
|
||
if (typeof load === 'function') {
|
||
try { load(); } catch (_) { }
|
||
}
|
||
if (typeof loadVpnProfiles === 'function') {
|
||
try { loadVpnProfiles(); } catch (_) { }
|
||
}
|
||
} else {
|
||
if (appEl) { appEl.style.display = 'none'; }
|
||
if (authV) { authV.classList.add('active'); authV.style.display = 'block'; }
|
||
if (typeof showAuth === 'function') {
|
||
try { showAuth(false); } catch (_) { }
|
||
}
|
||
}
|
||
} catch (e) {
|
||
var l2 = document.getElementById('loader');
|
||
if (l2) l2.style.display = 'none';
|
||
var appFallback = document.getElementById('app');
|
||
if (appFallback) appFallback.style.display = 'block';
|
||
}
|
||
};
|
||
</script>
|
||
</div>
|
||
|
||
<section id="authView" class="view">
|
||
<div class="card" style="max-width:520px;margin:80px auto">
|
||
<h1 id="authTitle" data-i18n="auth_title">Connexion</h1>
|
||
<p id="authIntro" class="muted"><span data-i18n="auth_intro_prefix">Connectez-vous pour accéder à</span> <span
|
||
class="app-title" data-i18n="auth_intro_title">l’administration de l’AP Wi‑Fi</span>.</p>
|
||
<label class="label" for="authUsername" data-i18n="auth_username">Utilisateur</label>
|
||
<input id="authUsername" type="text" autocomplete="username" maxlength="32">
|
||
<label class="label" for="authPassword" data-i18n="auth_password">Mot de passe</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="authPassword" type="password" autocomplete="current-password" maxlength="128" style="margin:0">
|
||
<button id="toggleAuthPassword" class="secondary" type="button" aria-label="Afficher le mot de passe"
|
||
title="Afficher le mot de passe" data-i18n-title="btn_show_pwd" data-i18n-aria-label="btn_show_pwd"><svg width="20" height="20"
|
||
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
|
||
stroke-linejoin="round" aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
<div id="authOtpBox" style="display:none">
|
||
<label class="label" for="authOtp" data-i18n="auth_otp">Code de double identification (TOTP ou secours)</label>
|
||
<input id="authOtp" type="text" autocomplete="one-time-code" maxlength="11"
|
||
placeholder="Code à 6 chiffres ou code de secours (ex: ABCDE-12345)" data-i18n-placeholder="auth_otp_placeholder">
|
||
</div>
|
||
<label id="rememberUserBox" class="check" style="margin:16px 0 22px"><input id="rememberUser" type="checkbox">
|
||
<span data-i18n="auth_remember">Se rappeler de moi</span></label>
|
||
<button id="authSubmit" type="button" data-i18n="auth_submit"
|
||
style="width:100%;display:flex;align-items:center;justify-content:center;gap:10px;padding:12px 16px;font-size:14px;font-weight:600;border-radius:8px">Se connecter</button>
|
||
<div id="authMessage" class="muted" style="font-size:13px;text-align:center;margin-top:10px;min-height:18px"></div>
|
||
<div id="authPasskeyDivider"
|
||
style="display:flex;align-items:center;margin:22px 0 16px;gap:12px;color:var(--muted);font-size:12px">
|
||
<div style="flex:1;height:1px;background:var(--line)"></div>
|
||
<span style="font-weight:600;letter-spacing:0.5px" data-i18n="auth_passkey_or">OU SANS MOT DE PASSE</span>
|
||
<div style="flex:1;height:1px;background:var(--line)"></div>
|
||
</div>
|
||
<button id="btnAuthPasskey" type="button" class="secondary"
|
||
style="width:100%;display:flex;align-items:center;justify-content:center;gap:10px;padding:12px 16px;font-size:14px;font-weight:600;border-radius:8px">
|
||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||
<circle cx="7.5" cy="15.5" r="5.5" />
|
||
<path d="m21 2-9.6 9.6" />
|
||
<path d="m15.5 7.5 3 3L22 7l-3-3" />
|
||
</svg>
|
||
<span data-i18n="auth_passkey_btn">Se connecter avec une Passkey</span>
|
||
</button>
|
||
<div id="authPasskeyInfo" class="muted" style="font-size:12px;text-align:center;margin-top:8px"
|
||
data-i18n="auth_passkey_desc">Touch ID, Face ID, Windows Hello ou clé physique sans mot de passe ni 2FA</div>
|
||
|
||
</div>
|
||
</section>
|
||
|
||
<main id="app" class="wrap" style="display:none">
|
||
<header>
|
||
<div>
|
||
<h1><span class="app-title" data-i18n="app_main_heading">Administration de l’AP Wi‑Fi</span></h1>
|
||
<div class="sub"><span class="app-short-title">AP Manageur</span> <span class="app-version"
|
||
style="font-weight:700;background:var(--panel2);padding:2px 8px;border-radius:6px;border:1px solid var(--line);color:var(--blue);font-size:12px;margin-left:4px">V5.5</span>
|
||
</div>
|
||
</div>
|
||
<div class="header-actions">
|
||
<button id="apControl" type="button" data-i18n="btn_start">Démarrer</button>
|
||
<button id="apRestart" class="secondary" type="button" data-i18n="btn_restart">Redémarrer</button>
|
||
<button id="refresh" data-i18n="btn_refresh">Actualiser</button>
|
||
<button id="headerLangBtn" class="secondary" type="button" onclick="openLanguageSettings()"
|
||
title="Paramètres de langue / Language settings">
|
||
<span id="headerLangFlag" style="display:inline-flex;align-items:center;line-height:1"></span>
|
||
<span id="headerLangText" style="font-weight:700">FR</span>
|
||
</button>
|
||
<button id="logout" class="secondary" type="button" data-i18n="btn_logout">Déconnexion</button>
|
||
</div>
|
||
</header>
|
||
|
||
<nav id="nav">
|
||
<button id="dashboardTab" class="secondary active" aria-selected="true" data-i18n="nav_dashboard">Tableau de
|
||
bord</button>
|
||
<button id="statsTab" class="secondary" aria-selected="false" data-i18n="nav_stats">Statistiques</button>
|
||
<button id="devicesTab" class="secondary" aria-selected="false" data-i18n="nav_devices">Appareils</button>
|
||
<button id="settingsTab" class="secondary" aria-selected="false" data-i18n="nav_settings">Réglages</button>
|
||
<button id="logsTab" class="secondary" aria-selected="false" data-i18n="nav_logs">Journaux</button>
|
||
<button id="blockedTab" class="secondary" aria-selected="false" data-i18n="nav_blocked">Appareils bloqués</button>
|
||
<button id="advancedTab" class="secondary" aria-selected="false" data-i18n="nav_advanced">Avancé</button>
|
||
</nav>
|
||
|
||
<section id="dashboardView" class="view active">
|
||
<div class="grid">
|
||
<div class="card">
|
||
<div class="label" data-i18n="dash_state_title">État de l’AP</div>
|
||
<div id="state" class="metric status"><i class="dot"></i> Chargement</div>
|
||
<div id="networkModeBadge" class="pill" style="margin-top:8px;width:fit-content;max-width:100%">—</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="dash_clients_title">Clients connectés</div>
|
||
<div id="clientCount" class="metric">—</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="dash_ssid_title">SSID</div>
|
||
<div id="ssid" class="metric" style="font-size:21px">—</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="dash_uptime_title">Uptime du SSID</div>
|
||
<div id="uptime" class="metric">—</div>
|
||
</div>
|
||
</div>
|
||
<div class="layout">
|
||
<section class="card">
|
||
<div class="topline">
|
||
<h2 data-i18n="dash_connected_clients">Clients connectés</h2><span id="updated" class="pill pill-updated"
|
||
data-i18n="dash_updated_initial">Dernière actualisation : —</span>
|
||
</div>
|
||
<div class="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th data-i18n="th_device">APPAREIL</th>
|
||
<th data-i18n="th_ip">IP</th>
|
||
<th data-i18n="th_mac">MAC</th>
|
||
<th data-i18n="th_routing">ROUTAGE INTERNET</th>
|
||
<th data-i18n="th_signal">SIGNAL</th>
|
||
<th data-i18n="th_speed">DÉBIT (TEMPS RÉEL)</th>
|
||
<th data-i18n="th_action">ACTION</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="clients"></tbody>
|
||
</table>
|
||
</div>
|
||
<div id="clientsPagination" class="pagination"></div>
|
||
</section>
|
||
<aside class="card">
|
||
<div class="qr-card-content">
|
||
<h2 data-i18n="qr_title">Rejoindre le réseau</h2>
|
||
<div id="qrcode"></div>
|
||
<div class="label" data-i18n="qr_pwd_label">Mot de passe récupéré par l’API</div>
|
||
<input id="qrPassword" type="password" readonly style="margin:8px 0 16px;text-align:center">
|
||
<button id="showPassword" class="secondary" type="button"
|
||
style="display:block;width:100%;margin-bottom:12px" data-i18n="btn_show_pwd">Afficher le mot de
|
||
passe</button>
|
||
<p class="muted" style="font-size:12px" data-i18n="qr_info">Le QR code utilise le SSID et le mot de passe
|
||
réels de l’AP.</p>
|
||
</div>
|
||
</aside>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="statsView" class="view">
|
||
<div class="settings-nav" role="tablist" style="margin-bottom:20px">
|
||
<button id="tabStatsMetrics" class="settings-nav-btn active" type="button" role="tab" aria-selected="true"
|
||
onclick="selectStatsSubTab('metrics')">
|
||
<span>📊</span> <span data-i18n="stats_subtab_metrics">Fréquentation & Métriques</span>
|
||
</button>
|
||
<button id="tabStatsTopology" class="settings-nav-btn" type="button" role="tab" aria-selected="false"
|
||
onclick="selectStatsSubTab('topology')">
|
||
<span>🗺️</span> <span data-i18n="stats_subtab_topology">Topologie du réseau</span>
|
||
</button>
|
||
</div>
|
||
|
||
<!-- 1. Métriques & Fréquentation -->
|
||
<div id="panelStatsMetrics" class="stats-subpanel">
|
||
<div class="grid">
|
||
<div class="card">
|
||
<div class="muted" data-i18n="stats_today">Aujourd’hui</div>
|
||
<div class="metric" id="statsTodayUnique" style="color:var(--blue)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px"><span id="statsTodayTotal">0</span> <span
|
||
data-i18n="stats_connections_total">connexion(s) au total</span></div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="muted" data-i18n="stats_this_week">Cette semaine</div>
|
||
<div class="metric" id="statsWeekUnique" style="color:var(--green)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px"><span id="statsWeekTotal">0</span> <span
|
||
data-i18n="stats_connections_total">connexion(s) au total</span></div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="muted" data-i18n="stats_this_month">Ce mois-ci</div>
|
||
<div class="metric" id="statsMonthUnique" style="color:var(--blue)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px"><span id="statsMonthTotal">0</span> <span
|
||
data-i18n="stats_connections_total">connexion(s) au total</span></div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="muted" data-i18n="stats_this_year">Cette année</div>
|
||
<div class="metric" id="statsYearUnique" style="color:var(--green)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px"><span id="statsYearTotal">0</span> <span
|
||
data-i18n="stats_connections_total">connexion(s) au total</span></div>
|
||
</div>
|
||
</div>
|
||
<div class="card" style="margin-bottom:18px">
|
||
<div class="topline" style="flex-wrap:wrap;gap:12px;margin-bottom:16px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="stats_chart_title">Fréquentation & Connexions</h2>
|
||
<div class="muted" style="font-size:13px" id="statsChartSubtitle" data-i18n="stats_chart_sub_day">
|
||
Fréquentation par heure (aujourd’hui)</div>
|
||
</div>
|
||
<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
|
||
<div class="stats-range-container">
|
||
<button id="statsRangeDay" class="stats-range-btn active" type="button" data-i18n="stats_range_day">Par
|
||
jour</button>
|
||
<button id="statsRangeWeek" class="stats-range-btn" type="button" data-i18n="stats_range_week">Par
|
||
semaine</button>
|
||
<button id="statsRangeMonth" class="stats-range-btn" type="button" data-i18n="stats_range_month">Par
|
||
mois</button>
|
||
<button id="statsRangeYear" class="stats-range-btn" type="button" data-i18n="stats_range_year">Par
|
||
année</button>
|
||
</div>
|
||
<span id="statsChartUpdated" class="pill" style="font-size:12px" data-i18n="dash_updated_initial">Dernière
|
||
actualisation : —</span>
|
||
</div>
|
||
</div>
|
||
<div class="chart-box" id="statsChartBox"><canvas id="statsChartCanvas"></canvas>
|
||
<div id="statsSvgFallback" style="display:none;width:100%;height:100%"></div>
|
||
</div>
|
||
</div>
|
||
<div class="card" style="margin-bottom:18px">
|
||
<div class="topline" style="flex-wrap:wrap;gap:12px;margin-bottom:12px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="stats_top_clients_title">Top des clients (Consommation de données)
|
||
</h2>
|
||
<div id="statsTopClientsSubtitle" class="muted" style="font-size:13px" data-i18n="stats_top_clients_sub">
|
||
Appareils ayant le plus consommé aujourd’hui (Par jour)</div>
|
||
</div>
|
||
<span id="statsTrafficUpdated" class="pill" style="font-size:12px" data-i18n="dash_updated_initial">Dernière
|
||
actualisation : —</span>
|
||
</div>
|
||
<div class="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th>#</th>
|
||
<th data-i18n="th_device">APPAREIL</th>
|
||
<th data-i18n="th_ip">IP</th>
|
||
<th data-i18n="th_mac">MAC</th>
|
||
<th data-i18n="th_downloaded">TÉLÉCHARGÉ (↓)</th>
|
||
<th data-i18n="th_uploaded">UPLOADÉ (↑)</th>
|
||
<th data-i18n="th_total_transferred">TOTAL TRANSFÉRÉ</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="statsTopClientsBody">
|
||
<tr>
|
||
<td colspan="7" class="empty">Chargement…</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div id="statsTopClientsPagination" class="pagination"></div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="topline" style="flex-wrap:wrap;gap:12px;margin-bottom:12px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="stats_details_title">Détail des connexions</h2><span
|
||
id="statsTableSub" class="muted" style="font-size:13px" data-i18n="stats_today">Aujourd’hui</span>
|
||
</div>
|
||
<span id="statsHistoryUpdated" class="pill" style="font-size:12px" data-i18n="dash_updated_initial">Dernière
|
||
actualisation : —</span>
|
||
</div>
|
||
<div class="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th data-i18n="th_period">PÉRIODE</th>
|
||
<th data-i18n="th_unique_devices">APPAREILS UNIQUES</th>
|
||
<th data-i18n="th_total_connections">CONNEXIONS TOTALES</th>
|
||
<th data-i18n="th_identified_devices">APPAREILS IDENTIFIÉS</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="statsTableBody">
|
||
<tr>
|
||
<td colspan="4" class="empty">Chargement…</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div id="statsTablePagination" class="pagination"></div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 2. Topologie du Réseau -->
|
||
<div id="panelStatsTopology" class="stats-subpanel" style="display:none">
|
||
<div class="topline" style="flex-wrap:wrap;gap:12px;margin-bottom:16px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="topo_title">Topologie du réseau Wi‑Fi</h2>
|
||
<div class="muted" style="font-size:13px" data-i18n="topo_subtitle">Cartographie interactive des équipements
|
||
et liaisons réseau en temps réel</div>
|
||
</div>
|
||
<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
|
||
<span id="topoStatusWan" class="pill pill-green" data-i18n="topo_status_wan">Passerelle : En ligne</span>
|
||
<span id="topoStatusAp" class="pill" style="background:var(--panel2)">AP : wlan0 (Canal 6)</span>
|
||
<span id="topoClientsCount" class="pill" style="background:var(--panel2)"
|
||
data-i18n="topo_clients_connected_count">0 connecté(s)</span>
|
||
<span id="topoStatusVpn" class="pill"
|
||
style="display:none;background:rgba(255,107,107,.18);color:var(--red);border:1px solid rgba(255,107,107,.35)">🛡️
|
||
VPN : 0 actif</span>
|
||
<span id="topoTrafficRate" class="pill" style="background:var(--panel2)">↓ 0 o/s • ↑ 0 o/s</span>
|
||
<span id="topoUpdated" class="pill" style="font-size:12px" data-i18n="dash_updated_initial">Dernière
|
||
actualisation : —</span>
|
||
<div class="dropdown" style="position:relative;display:inline-block">
|
||
<button id="topoExportBtn" type="button" class="secondary"
|
||
style="display:inline-flex;align-items:center;gap:6px;padding:6px 14px;font-size:13px;border-radius:8px"
|
||
onclick="toggleTopoExportMenu(event)">
|
||
<span>📥</span> <span data-i18n="topo_export">Exporter la topologie ▾</span>
|
||
</button>
|
||
<div id="topoExportMenu"
|
||
style="display:none;position:absolute;right:0;top:calc(100% + 6px);background:var(--panel2);border:1px solid var(--line);border-radius:10px;box-shadow:0 10px 28px rgba(0,0,0,.5);z-index:100;min-width:190px;padding:6px;overflow:hidden">
|
||
<button type="button" class="secondary"
|
||
style="width:100%;text-align:left;display:flex;align-items:center;gap:8px;padding:8px 12px;border:none;background:transparent;border-radius:6px;font-size:13px;cursor:pointer;color:var(--text)"
|
||
onclick="exportTopologyImage('png')">
|
||
<span>🖼️</span> Format PNG (.png)
|
||
</button>
|
||
<button type="button" class="secondary"
|
||
style="width:100%;text-align:left;display:flex;align-items:center;gap:8px;padding:8px 12px;border:none;background:transparent;border-radius:6px;font-size:13px;cursor:pointer;color:var(--text)"
|
||
onclick="exportTopologyImage('jpg')">
|
||
<span>📷</span> Format JPG (.jpg)
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="filter-bar"
|
||
style="margin-bottom:16px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px">
|
||
<div class="filter-input-wrap" style="max-width:340px">
|
||
<span class="filter-icon">🔍</span>
|
||
<input id="topoSearchInput" type="text" placeholder="Filtrer un appareil (nom, IP, MAC)…"
|
||
data-i18n-placeholder="topo_search_ph" oninput="filterTopologyNodes(this.value)">
|
||
<button id="topoClearSearch" class="clear-filter-btn" type="button"
|
||
onclick="$('topoSearchInput').value='';filterTopologyNodes('');">✕</button>
|
||
</div>
|
||
<div style="display:flex;gap:12px;align-items:center;font-size:12px;color:var(--muted);flex-wrap:wrap">
|
||
<span data-i18n="topo_links_legend">Liaisons :</span>
|
||
<span style="color:var(--red);font-weight:700" data-i18n="topo_link_vpn">● Rouge : Tunnel VPN actif</span>
|
||
<span style="color:var(--green);font-weight:600" data-i18n="topo_link_wifi">● Vert : Wi‑Fi > -50
|
||
dBm</span>
|
||
<span style="color:#68d391;font-weight:600" data-i18n="topo_link_good">● Bon (-60 dBm)</span>
|
||
<span style="color:#f6ad55;font-weight:600" data-i18n="topo_link_fair">● Moyen (-70 dBm)</span>
|
||
<span style="color:var(--red);font-weight:600" data-i18n="topo_link_weak">● Faible (< -70 dBm)</span>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Carte interactive de la topologie -->
|
||
<div class="card topo-map-card">
|
||
<svg id="topoSvgLines"
|
||
style="position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:1"></svg>
|
||
|
||
<div
|
||
style="position:relative;z-index:2;display:flex;flex-direction:column;align-items:center;gap:32px;width:100%">
|
||
<!-- Niveau 1: Passerelle Internet & Tunnels VPN (VPN à gauche, WAN à droite) -->
|
||
<div id="topoLevel1" class="topo-level1-single">
|
||
<div id="topoVpnNodes" style="display:none;flex-direction:column;gap:12px;width:100%"></div>
|
||
<div id="topoNodeWan" class="topo-node topo-node-wan" onclick="openTopologyModal('wan')">
|
||
<div class="topo-node-icon">🌐</div>
|
||
<div class="topo-node-content" style="flex:1">
|
||
<div class="topo-node-title" data-i18n="topo_wan_gateway_label">Passerelle Internet</div>
|
||
<div id="topoWanIp" class="topo-node-sub">192.168.1.1 (WAN)</div>
|
||
</div>
|
||
<span class="dot" title="Passerelle joignable"></span>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Liaison WAN -> AP -->
|
||
<div id="topoWanVerticalLink" class="topo-vertical-link">
|
||
<div class="topo-link-line"></div>
|
||
<div class="topo-link-badge" data-i18n="topo_wan_link_badge">⚡ Liaison Filaire / WAN</div>
|
||
<div class="topo-link-line"></div>
|
||
</div>
|
||
|
||
<!-- Niveau 2: Point d'Accès Wi-Fi (Hub) -->
|
||
<div id="topoNodeAp" class="topo-node topo-node-ap" onclick="openTopologyModal('ap')">
|
||
<div class="topo-node-icon">📡</div>
|
||
<div class="topo-node-content" style="flex:1">
|
||
<div style="display:flex;align-items:center;gap:8px">
|
||
<strong id="topoApSsid" style="font-size:16px">AP Wi-Fi</strong>
|
||
<span id="topoApBadge" class="pill pill-green" style="font-size:11px">Actif</span>
|
||
</div>
|
||
<div id="topoApIp" class="topo-node-sub" style="margin-top:2px">10.42.0.1 • Canal 6 (2.4 GHz)</div>
|
||
<div id="topoApMeta" class="muted" style="font-size:11px;margin-top:4px">WPA2 • Mode NAT • 0 appareil(s)
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Liaison AP -> Clients -->
|
||
<div style="display:flex;flex-direction:column;align-items:center;gap:4px">
|
||
<span
|
||
style="font-size:12px;font-weight:600;color:var(--muted);background:var(--panel);padding:4px 14px;border:1px solid var(--line);border-radius:12px"
|
||
data-i18n="topo_wifi_links">
|
||
📶 Liaisons Wi‑Fi sans fil (802.11)
|
||
</span>
|
||
</div>
|
||
|
||
<!-- Niveau 3: Appareils Clients -->
|
||
<div id="topoClientsGrid" class="topo-clients-grid">
|
||
<!-- Rempli en direct -->
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Cartes de synthèse de la topologie -->
|
||
<div class="grid" style="margin-top:18px">
|
||
<div class="card">
|
||
<div class="label" data-i18n="topo_signal_quality">Qualité du Signal Wi-Fi</div>
|
||
<div id="topoSignalStats" style="margin-top:10px;display:flex;flex-direction:column;gap:8px">
|
||
<div class="muted" style="font-size:13px" data-i18n="topo_no_clients_desc">Aucun client connecté</div>
|
||
</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="topo_device_repartition">Répartition des Appareils</div>
|
||
<div id="topoDeviceStats" style="margin-top:10px;display:flex;flex-direction:column;gap:8px">
|
||
<div class="muted" style="font-size:13px" data-i18n="topo_no_clients_desc">Aucun client connecté</div>
|
||
</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="topo_live_bandwidth">Bande Passante en Direct</div>
|
||
<div style="margin-top:8px">
|
||
<div style="font-size:13px;color:var(--muted)" data-i18n="topo_down_tx">Débit descendant cumulé (TX)</div>
|
||
<div id="topoLiveDown" class="metric" style="color:var(--blue);font-size:22px">0 o/s</div>
|
||
<div style="font-size:13px;color:var(--muted);margin-top:8px" data-i18n="topo_up_rx">Débit montant cumulé
|
||
(RX)</div>
|
||
<div id="topoLiveUp" class="metric" style="color:var(--green);font-size:22px">0 o/s</div>
|
||
</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="topo_security_filtering">Sécurité & Filtrage</div>
|
||
<div style="margin-top:8px">
|
||
<div style="font-size:13px;color:var(--muted)" data-i18n="topo_blocked_devices">Appareils bloqués / isolés
|
||
</div>
|
||
<div id="topoBlockedCount" class="metric" style="color:var(--red);font-size:22px">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:6px" data-i18n="clients_mac_filtering_desc">Filtrage
|
||
matériel par adresse MAC</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<!-- Section Appareils (Tous les appareils ayant déjà été connectés) -->
|
||
<section id="devicesView" class="view">
|
||
<div class="grid" style="margin-bottom:16px">
|
||
<div class="card">
|
||
<div class="label" data-i18n="dev_total_registered">Total appareils enregistrés</div>
|
||
<div class="metric" id="metricDevicesTotal" style="color:var(--blue)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px" data-i18n="clients_saved_sqlite_desc">Mémorisés en
|
||
base SQLite</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="dev_currently_connected">Actuellement connectés</div>
|
||
<div class="metric" id="metricDevicesConnected" style="color:var(--green)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px" data-i18n="clients_online_wifi_desc">En ligne sur le
|
||
Wi‑Fi</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="dev_offline_count">Appareils hors ligne</div>
|
||
<div class="metric" id="metricDevicesOffline" style="color:var(--muted)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px" data-i18n="clients_offline_desc">Non connectés
|
||
actuellement</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="dev_blocked_count">Appareils bloqués</div>
|
||
<div class="metric" id="metricDevicesBlocked" style="color:var(--red)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px" data-i18n="clients_blocked_desc">Accès Wi‑Fi interdit
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="card">
|
||
<div class="topline" style="flex-wrap:wrap;gap:12px;margin-bottom:14px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="dev_history_title">Historique de tous les appareils</h2>
|
||
<div class="muted" style="font-size:13px" data-i18n="dev_history_desc">Consultez l'ensemble des équipements
|
||
s’étant déjà connectés au point d'accès Wi‑Fi (récupérés depuis la base de données).</div>
|
||
</div>
|
||
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
|
||
<span id="devicesUpdated" class="pill pill-updated" style="font-size:12px"
|
||
data-i18n="dash_updated_initial">Dernière actualisation : —</span>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Barre d'outils de recherche et filtres -->
|
||
<div
|
||
style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-bottom:14px;background:var(--panel2);padding:10px 14px;border-radius:10px;border:1px solid var(--line)">
|
||
<div style="display:flex;align-items:center;gap:8px;flex:1;min-width:240px">
|
||
<span style="font-size:15px;color:var(--muted)">🔍</span>
|
||
<input id="devicesSearchInput" type="text" placeholder="Filtrer par nom, adresse MAC, IP..."
|
||
data-i18n-placeholder="dev_search_ph"
|
||
style="margin:0;padding:6px 10px;font-size:13px;background:transparent;border:0;color:var(--text);width:100%"
|
||
oninput="onDevicesSearch(this.value)">
|
||
</div>
|
||
<div style="display:flex;gap:6px;flex-wrap:wrap">
|
||
<button id="btnFilterDevAll" class="secondary active" type="button"
|
||
style="padding:5px 11px;font-size:12px;border-radius:6px" onclick="setDevicesFilter('all')"><span
|
||
data-i18n="dev_filter_all">Tous</span> (<span id="filterCountAll">0</span>)</button>
|
||
<button id="btnFilterDevConn" class="secondary" type="button"
|
||
style="padding:5px 11px;font-size:12px;border-radius:6px" onclick="setDevicesFilter('connected')"><span
|
||
data-i18n="dev_filter_conn">🟢 Connectés</span> (<span id="filterCountConn">0</span>)</button>
|
||
<button id="btnFilterDevOff" class="secondary" type="button"
|
||
style="padding:5px 11px;font-size:12px;border-radius:6px" onclick="setDevicesFilter('offline')"><span
|
||
data-i18n="dev_filter_off">⚪ Hors ligne</span> (<span id="filterCountOff">0</span>)</button>
|
||
<button id="btnFilterDevBlock" class="secondary" type="button"
|
||
style="padding:5px 11px;font-size:12px;border-radius:6px" onclick="setDevicesFilter('blocked')"><span
|
||
data-i18n="dev_filter_block">🔴 Bloqués</span> (<span id="filterCountBlock">0</span>)</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th data-i18n="th_device">APPAREIL</th>
|
||
<th data-i18n="th_mac">ADRESSE MAC</th>
|
||
<th data-i18n="th_last_ip">DERNIÈRE IP</th>
|
||
<th data-i18n="th_status">STATUT ACTUEL</th>
|
||
<th data-i18n="th_quota">QUOTA & DÉBIT</th>
|
||
<th data-i18n="th_last_activity">DERNIÈRE ACTIVITÉ</th>
|
||
<th data-i18n="th_first_connection">PREMIÈRE CONNEXION</th>
|
||
<th style="text-align:right" data-i18n="th_actions">ACTIONS</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="devicesTableBody">
|
||
<!-- Lignes injectées dynamiquement par JS -->
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div id="devicesPagination" class="pagination"></div>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="advancedView" class="view">
|
||
<div class="settings-nav" role="tablist" style="margin-bottom:18px">
|
||
<button id="tabAdvVpnRouting" class="settings-nav-btn active" type="button" role="tab"
|
||
onclick="selectAdvSubTab('vpn')">
|
||
<span>🛡️</span> <span data-i18n="adv_subtab_vpn">Routage VPN par client</span>
|
||
</button>
|
||
<button id="tabAdvPcap" class="settings-nav-btn" type="button" role="tab" onclick="selectAdvSubTab('pcap')">
|
||
<span>📡</span> <span data-i18n="adv_subtab_pcap">Capture de paquets (PCAP)</span>
|
||
</button>
|
||
</div>
|
||
|
||
<!-- Sous-panneau 1 : Routage VPN par client -->
|
||
<div id="panelAdvVpnRouting">
|
||
<div class="grid" style="margin-bottom:16px">
|
||
<div class="card">
|
||
<div class="label" data-i18n="settings_vpn_profiles_count">Profils VPN disponibles</div>
|
||
<div class="metric" id="metricVpnProfilesCount" style="color:var(--blue)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px" id="metricVpnActiveCount"
|
||
data-i18n="topo_clients_connected_count">0 connecté(s)</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="settings_vpn_routed_clients">Clients routés via VPN</div>
|
||
<div class="metric" id="metricVpnRoutedClients" style="color:var(--green)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px" data-i18n="clients_vpn_tunneled_desc">Trafic
|
||
acheminé par tunnel</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="settings_vpn_direct_clients">Clients en WAN direct</div>
|
||
<div class="metric" id="metricVpnDirectClients" style="color:var(--muted)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px" data-i18n="vpn_direct_clients_desc">Sans VPN (connexion normale)</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="settings_vpn_killswitch_active">Kill-Switch actifs</div>
|
||
<div class="metric" id="metricVpnKillswitchCount" style="color:#f6ad55">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px" data-i18n="vpn_killswitch_active_desc">Protection anti-fuite</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="card">
|
||
<div
|
||
style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-bottom:14px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="adv_routing_title">Routage réseau Wi‑Fi par client</h2>
|
||
<div class="muted" style="font-size:13px" data-i18n="adv_routing_desc">Choisissez quel profil VPN chaque
|
||
équipement doit emprunter, ou laissez-le en accès direct Internet.</div>
|
||
<div
|
||
style="margin-top:8px;padding:7px 12px;background:rgba(56,189,248,0.08);border:1px solid rgba(56,189,248,0.25);border-radius:8px;font-size:12px;color:var(--text);display:flex;align-items:center;gap:8px">
|
||
<span>🔒</span> <span data-i18n-html="adv_lan_isolation_full"><strong>Isolation LAN active :</strong>
|
||
Tout équipement connecté à un VPN est strictement isolé du réseau local (aucun accès aux box, NAS,
|
||
imprimantes ou à l'AP Manageur). Tout son trafic transite exclusivement par le tunnel VPN.</span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Barre d'outils de recherche et filtres pour routage VPN -->
|
||
<div
|
||
style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-bottom:14px;background:var(--panel2);padding:10px 14px;border-radius:10px;border:1px solid var(--line)">
|
||
<div style="display:flex;align-items:center;gap:8px;flex:1;min-width:240px">
|
||
<span style="font-size:15px;color:var(--muted)">🔍</span>
|
||
<input id="vpnClientsSearchInput" type="text" placeholder="Filtrer par nom, adresse MAC, IP, profil..."
|
||
data-i18n-placeholder="placeholder_filter_clients"
|
||
style="margin:0;padding:6px 10px;font-size:13px;background:transparent;border:0;color:var(--text);width:100%"
|
||
oninput="onVpnClientsSearch(this.value)">
|
||
</div>
|
||
<div style="display:flex;gap:6px;flex-wrap:wrap">
|
||
<button id="btnFilterVpnAll" class="secondary active" type="button"
|
||
style="padding:5px 11px;font-size:12px;border-radius:6px" onclick="setVpnClientsFilter('all')"><span
|
||
data-i18n="vpn_btn_filter_all">Tous</span> (<span id="filterCountVpnAll">0</span>)</button>
|
||
<button id="btnFilterVpnRouted" class="secondary" type="button"
|
||
style="padding:5px 11px;font-size:12px;border-radius:6px" onclick="setVpnClientsFilter('routed')"><span
|
||
data-i18n="vpn_btn_filter_routed">🛡️ Routés</span> (<span
|
||
id="filterCountVpnRouted">0</span>)</button>
|
||
<button id="btnFilterVpnOnline" class="secondary" type="button"
|
||
style="padding:5px 11px;font-size:12px;border-radius:6px" onclick="setVpnClientsFilter('online')"><span
|
||
data-i18n="vpn_btn_filter_online">🟢 En ligne</span> (<span
|
||
id="filterCountVpnOnline">0</span>)</button>
|
||
<button id="btnFilterVpnOffline" class="secondary" type="button"
|
||
style="padding:5px 11px;font-size:12px;border-radius:6px" onclick="setVpnClientsFilter('offline')"><span
|
||
data-i18n="vpn_btn_filter_offline">⚪ Hors ligne</span> (<span id="filterCountVpnOffline">0</span>)</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div style="overflow-x:auto">
|
||
<table style="width:100%;border-collapse:collapse;font-size:13px">
|
||
<thead>
|
||
<tr style="border-bottom:1px solid var(--line);text-align:left;color:var(--muted);font-size:12px">
|
||
<th style="padding:10px 8px" data-i18n="th_device">ÉQUIPEMENT</th>
|
||
<th style="padding:10px 8px" data-i18n="th_ip_mac">ADRESSES IP & MAC</th>
|
||
<th style="padding:10px 8px;min-width:220px" data-i18n="th_vpn_assigned">PROFIL VPN ASSIGNÉ</th>
|
||
<th style="padding:10px 8px;text-align:center" data-i18n="th_killswitch">KILL-SWITCH</th>
|
||
<th style="padding:10px 8px" data-i18n="th_effective_status">STATUT EFFECTIF</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="vpnClientsTableBody">
|
||
<!-- Lignes injectées par JS -->
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div id="vpnClientsPagination" class="pagination"></div>
|
||
<div id="vpnClientsEmpty" style="display:none;text-align:center;padding:30px;color:var(--muted)"
|
||
data-i18n="vpn_clients_empty_msg">
|
||
Aucun équipement Wi‑Fi détecté pour le moment.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Sous-panneau 2 : Capture de paquets (PCAP) -->
|
||
<div id="panelAdvPcap" style="display:none">
|
||
<div class="grid">
|
||
<div class="card">
|
||
<div class="label" data-i18n="adv_pcap_state_label">État Analyseur Wireshark</div>
|
||
<div style="display:flex;align-items:center;gap:10px;margin-top:6px"><span id="captureStatusBadge"
|
||
class="pill" style="background:var(--panel2);color:var(--muted);font-weight:700"
|
||
data-i18n="adv_pcap_inactive">Inactif</span></div>
|
||
<div class="muted" style="font-size:12px;margin-top:6px" id="captureIfaceInfo"
|
||
data-i18n="packet_iface_info">Interface Wi-Fi : —</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="adv_pcap_captured_label">Paquets capturés</div>
|
||
<div class="metric" id="captureTotalCount" style="color:var(--blue)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px" id="captureBufferSize"
|
||
data-i18n="adv_pcap_buffer_size">Tous les paquets conservés</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="adv_pcap_domains_detected">Domaines détectés</div>
|
||
<div class="metric" id="captureDomainsCount" style="color:var(--green)">0</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px" data-i18n="adv_pcap_domains_desc">Noms de domaine
|
||
uniques</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="adv_pcap_export_size">Taille export PCAP</div>
|
||
<div class="metric" id="capturePcapSize" style="font-size:22px">24 B</div>
|
||
<div class="muted" style="font-size:12px;margin-top:4px" data-i18n="adv_pcap_format_desc">Format Libpcap 2.4 (Wireshark)</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="label" data-i18n="adv_pcap_proto_label">Protocoles détectés</div>
|
||
<div style="display:flex;gap:4px;flex-wrap:wrap;margin-top:6px"><span class="proto-badge proto-dns">DNS:
|
||
<strong id="statDns">0</strong></span><span class="proto-badge proto-icmp">ICMP: <strong
|
||
id="statIcmp">0</strong></span><span class="proto-badge proto-tcp">TCP: <strong
|
||
id="statTcp">0</strong></span><span class="proto-badge proto-udp">UDP: <strong
|
||
id="statUdp">0</strong></span><span class="proto-badge proto-arp">ARP: <strong
|
||
id="statArp">0</strong></span><span class="proto-badge proto-tls">TLS: <strong
|
||
id="statTls">0</strong></span><span class="proto-badge proto-dhcp">DHCP: <strong
|
||
id="statDhcp">0</strong></span></div>
|
||
</div>
|
||
</div>
|
||
<div class="card">
|
||
<div class="topline" style="flex-wrap:wrap;gap:12px;margin-bottom:12px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="adv_pcap_title">Analyseur Réseau Wi-Fi (Wireshark)</h2>
|
||
<div class="muted" style="font-size:13px" data-i18n="adv_pcap_desc">Capture et analyse des flux réseau en
|
||
temps réel sur l’interface Wi-Fi</div>
|
||
</div>
|
||
<div class="capture-actions">
|
||
<button id="startCaptureBtn" type="button" style="background:var(--blue);color:var(--blue-text,#071326)"
|
||
data-i18n="adv_pcap_start">▶ Démarrer</button>
|
||
<button id="stopCaptureBtn" type="button"
|
||
style="background:var(--red);color:white;display:none;align-items:center;justify-content:center;gap:8px"
|
||
title="Arrêter l’analyse de trames Wireshark" data-i18n-title="pcap_stop_capture_title"><span
|
||
data-i18n="adv_pcap_stop_btn">■ Arrêter</span><span id="captureDurationBadge"
|
||
style="background:rgba(0,0,0,0.3);color:#fff;border:1px solid rgba(255,255,255,0.3);font-family:monospace;font-size:12px;font-weight:700;padding:2px 7px;border-radius:6px;letter-spacing:0.5px">00:00</span></button>
|
||
<button id="clearCaptureBtn" class="secondary" type="button" data-i18n="adv_pcap_clear">🗑️
|
||
Effacer</button>
|
||
<button id="exportPcapBtn" type="button" style="background:var(--green);color:white"
|
||
title="Télécharger le fichier .pcap compatible Wireshark Desktop" data-i18n-title="pcap_export_pcap_title"
|
||
data-i18n="adv_pcap_export_pcap">📥 Exporter PCAP</button>
|
||
<button id="exportCsvBtn" class="secondary" type="button" title="Exporter au format CSV"
|
||
data-i18n-title="pcap_export_csv_title" data-i18n="adv_pcap_export_csv">📄 Exporter CSV</button>
|
||
</div>
|
||
</div>
|
||
<div class="filter-chips">
|
||
<span class="muted" style="font-size:12px;margin-right:4px" data-i18n="adv_pcap_quick_filters">Filtres rapides :</span>
|
||
<button type="button" class="filter-chip active" data-filter=""
|
||
data-i18n="adv_pcap_filter_all">Tous</button>
|
||
<button type="button" class="filter-chip" data-filter="domain:" data-i18n="adv_pcap_filter_domains">🌐
|
||
Domaines uniquement</button>
|
||
<button type="button" class="filter-chip" data-filter="dns">DNS</button>
|
||
<button type="button" class="filter-chip" data-filter="icmp" data-i18n="adv_pcap_filter_icmp">ICMP (Ping)</button>
|
||
<button type="button" class="filter-chip" data-filter="tcp">TCP</button>
|
||
<button type="button" class="filter-chip" data-filter="udp">UDP</button>
|
||
<button type="button" class="filter-chip" data-filter="arp">ARP</button>
|
||
<button type="button" class="filter-chip" data-filter="dhcp">DHCP</button>
|
||
<button type="button" class="filter-chip" data-filter="tls" data-i18n="adv_pcap_filter_tls">TLS / HTTPS</button>
|
||
<button type="button" class="filter-chip" data-filter="http">HTTP</button>
|
||
</div>
|
||
<div class="wireshark-filter-bar">
|
||
<div class="filter-input-wrap">
|
||
<span class="filter-icon">🔍</span>
|
||
<input id="packetFilterInput" type="text"
|
||
placeholder="Filtrer paquets ou domaine (ex: google.com, dns, icmp, 10.42.0.1...)"
|
||
data-i18n-placeholder="placeholder_filter_packets" autocomplete="off">
|
||
<button id="clearFilterBtn" class="clear-filter-btn" type="button" title="Effacer" data-i18n-title="btn_clear">✕</button>
|
||
</div>
|
||
<div class="filter-side-controls">
|
||
<label class="check" style="margin:0;white-space:nowrap;font-size:13px"><input id="autoScrollCheck"
|
||
type="checkbox" checked> <span data-i18n="adv_pcap_autoscroll">Défilement live</span></label>
|
||
<span id="packetFilterCount" class="pill" style="font-size:12px">0 paquet(s)</span>
|
||
</div>
|
||
</div>
|
||
<div class="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th style="width:60px" data-i18n="th_num">N°</th>
|
||
<th style="width:100px" data-i18n="th_time">HEURE</th>
|
||
<th style="width:175px" data-i18n="th_src">SOURCE</th>
|
||
<th style="width:175px" data-i18n="th_dst">DESTINATION</th>
|
||
<th style="width:75px" data-i18n="th_proto">PROTO</th>
|
||
<th style="width:180px" data-i18n="th_domain">NOM DE DOMAINE</th>
|
||
<th style="width:70px" data-i18n="th_size">TAILLE</th>
|
||
<th data-i18n="th_info">INFO & DÉTAILS</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="capturePacketsBody">
|
||
<tr>
|
||
<td colspan="8" class="empty" data-i18n="adv_pcap_empty">Aucun paquet capturé. Cliquez sur « Démarrer
|
||
» pour lancer l’analyse Wireshark.</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div id="capturePagination" class="pagination"></div>
|
||
<p class="muted" style="font-size:12px;margin-top:10px" data-i18n="adv_pcap_hint">💡 Cliquez sur un paquet
|
||
pour inspecter l’en-tête décodé et le dump hexadécimal / ASCII style Wireshark.</p>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="settingsView" class="view">
|
||
<div id="setupCard" style="display:none"></div>
|
||
|
||
<div class="settings-nav" role="tablist">
|
||
<button id="tabSettingsWifi" class="settings-nav-btn active" type="button" role="tab" aria-selected="true"
|
||
onclick="selectSettingsTab('wifi')">
|
||
<span>📶</span> <span data-i18n="settings_tab_wifi">Wi‑Fi & Réseau</span>
|
||
</button>
|
||
<button id="tabSettingsAdmin" class="settings-nav-btn" type="button" role="tab" aria-selected="false"
|
||
onclick="selectSettingsTab('admin')">
|
||
<span>🔒</span> <span data-i18n="settings_tab_admin">Compte Admin</span>
|
||
</button>
|
||
<button id="tabSettingsVpn" class="settings-nav-btn" type="button" role="tab" aria-selected="false"
|
||
onclick="selectSettingsTab('vpn')">
|
||
<span>🌐</span> <span data-i18n="settings_tab_vpn">Profils VPN</span>
|
||
</button>
|
||
<button id="tabSettingsProxy" class="settings-nav-btn" type="button" role="tab" aria-selected="false"
|
||
onclick="selectSettingsTab('proxy')">
|
||
<span>🔀</span> <span data-i18n="settings_tab_proxy">Proxy inversé</span>
|
||
</button>
|
||
<button id="tabSettingsNotif" class="settings-nav-btn" type="button" role="tab" aria-selected="false"
|
||
onclick="selectSettingsTab('notif')">
|
||
<span>🔔</span> <span data-i18n="settings_tab_notif">Notifications</span>
|
||
</button>
|
||
<button id="tabSettingsCustom" class="settings-nav-btn" type="button" role="tab" aria-selected="false"
|
||
onclick="selectSettingsTab('custom')">
|
||
<span>🎨</span> <span data-i18n="settings_tab_custom">Personnalisation</span>
|
||
</button>
|
||
<button id="tabSettingsBackup" class="settings-nav-btn" type="button" role="tab" aria-selected="false"
|
||
onclick="selectSettingsTab('backup')">
|
||
<span>📦</span> <span data-i18n="settings_tab_backup">Sauvegardes</span>
|
||
</button>
|
||
<button id="tabSettingsDanger" class="settings-nav-btn" type="button" role="tab" aria-selected="false"
|
||
onclick="selectSettingsTab('danger')">
|
||
<span>⚠️</span> <span data-i18n="settings_tab_danger">Zone dangereuse</span>
|
||
</button>
|
||
</div>
|
||
|
||
<!-- 1. Wi-Fi & Réseau -->
|
||
<div id="panelSettingsWifi" class="settings-panel card">
|
||
<h2 data-i18n="settings_wifi_title">Réglages AP</h2>
|
||
<p class="muted" data-i18n="settings_wifi_subtitle">Les changements redémarrent la connexion Wi‑Fi active.</p>
|
||
<label class="label" for="settingsSsid" data-i18n="settings_ssid_label">Nom du SSID</label>
|
||
<input id="settingsSsid" type="text" maxlength="32">
|
||
<label class="label" for="settingsPassword" data-i18n="settings_pwd_label">Mot de passe Wi‑Fi</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="settingsPassword" type="password" minlength="8" maxlength="63" style="margin:0">
|
||
<button id="toggleSettingsPassword" class="secondary" type="button" aria-label="Afficher le mot de passe"
|
||
title="Afficher le mot de passe" data-i18n-title="btn_show_pwd" data-i18n-aria-label="btn_show_pwd"><svg id="passwordEye" width="20" height="20" viewBox="0 0 24 24"
|
||
fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
|
||
aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
<label class="label" for="settingsSecurity" data-i18n="settings_security_label">Sécurité Wi‑Fi</label>
|
||
<select id="settingsSecurity"
|
||
style="display:block;width:100%;margin:7px 0 16px;padding:12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-size:15px">
|
||
<option value="wpa1">WPA1</option>
|
||
<option value="wpa2" selected>WPA2</option>
|
||
<option value="wpa3">WPA3</option>
|
||
</select>
|
||
<label class="label" data-i18n="settings_mode_label">Mode de fonctionnement</label>
|
||
<div class="mode-selector-grid">
|
||
<label
|
||
style="display:flex;align-items:center;gap:10px;padding:12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);cursor:pointer"><input
|
||
type="radio" name="settingsMode" id="settingsModeAp" value="ap" checked style="width:auto;margin:0">
|
||
<div><strong data-i18n="setup_mode_ap">Mode AP (Routeur)</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="setup_mode_ap_desc">DHCP interne (10.42.0.x) & NAT</div>
|
||
</div>
|
||
</label>
|
||
<label
|
||
style="display:flex;align-items:center;gap:10px;padding:12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);cursor:pointer"><input
|
||
type="radio" name="settingsMode" id="settingsModeBridge" value="bridge" style="width:auto;margin:0">
|
||
<div><strong data-i18n="setup_mode_bridge">Mode Bridge (Pont)</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="setup_mode_bridge_desc">Utilise le DHCP de la box
|
||
</div>
|
||
</div>
|
||
</label>
|
||
</div>
|
||
<div id="settingsBridgeBlock" style="display:none;margin-bottom:16px"><label class="label"
|
||
for="settingsBridgeEth" data-i18n="settings_bridge_eth_label">Interface Ethernet de la box (mode
|
||
pont)</label><select id="settingsBridgeEth"
|
||
style="display:block;width:100%;margin:7px 0 8px;padding:12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-size:15px"></select>
|
||
<p class="muted" style="font-size:12px;margin:0" data-i18n="settings_bridge_desc">Les clients Wi‑Fi recevront
|
||
directement leur adresse IP de votre box Internet.</p>
|
||
</div>
|
||
<label class="label" for="settingsMaxClients" data-i18n="settings_max_clients_label">Limite de clients
|
||
simultanés (0 = illimité)</label>
|
||
<input id="settingsMaxClients" type="number" min="0" max="250" placeholder="0 pour illimité"
|
||
data-i18n-placeholder="placeholder_0_unlimited">
|
||
<label class="check" style="margin:16px 0 22px"><input id="settingsAutoconnect" type="checkbox"> <span
|
||
data-i18n="settings_autoconnect">Démarrer automatiquement au démarrage</span></label>
|
||
<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
|
||
<button id="saveSettings" type="button" data-i18n="settings_save_wifi">Enregistrer les réglages</button>
|
||
<span id="message" class="muted"></span>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 2. Compte Administrateur & Double Authentification (2FA) -->
|
||
<div id="panelSettingsAdmin" class="settings-panel card" style="display:none">
|
||
<h2 data-i18n="settings_admin_title">Compte Administrateur</h2>
|
||
<p class="muted" data-i18n="settings_admin_subtitle">Modifier l’identifiant et le mot de passe de connexion au
|
||
tableau de bord.</p>
|
||
<label class="label" for="authSettingsUsername" data-i18n="settings_admin_user_label">Utilisateur
|
||
administrateur</label>
|
||
<input id="authSettingsUsername" type="text" maxlength="32">
|
||
<label class="label" for="authSettingsPassword" data-i18n="settings_admin_new_pwd_label">Nouveau mot de
|
||
passe</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="authSettingsPassword" type="password" minlength="8" maxlength="128"
|
||
placeholder="Nouveau mot de passe" data-i18n-placeholder="placeholder_new_pwd" style="margin:0">
|
||
<button id="toggleAuthSettingsPassword" class="secondary" type="button"
|
||
aria-label="Afficher le nouveau mot de passe" title="Afficher le nouveau mot de passe" data-i18n-title="settings_show_new_pwd" data-i18n-aria-label="settings_show_new_pwd"><svg width="20"
|
||
height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
|
||
stroke-linejoin="round" aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
<label class="label" for="authSettingsPasswordConfirm" data-i18n="settings_admin_confirm_pwd_label">Confirmation
|
||
du mot de passe</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="authSettingsPasswordConfirm" type="password" minlength="8" maxlength="128"
|
||
placeholder="Confirmation du mot de passe" data-i18n-placeholder="placeholder_pwd_confirm" style="margin:0">
|
||
<button id="toggleAuthSettingsPasswordConfirm" class="secondary" type="button"
|
||
aria-label="Afficher la confirmation du mot de passe" title="Afficher la confirmation du mot de passe" data-i18n-title="settings_show_confirm_pwd" data-i18n-aria-label="settings_show_confirm_pwd"><svg
|
||
width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
<label class="label" for="authCurrentPassword" data-i18n="settings_admin_current_pwd_label">Mot de passe
|
||
actuel</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="authCurrentPassword" type="password" autocomplete="current-password" maxlength="128"
|
||
placeholder="Mot de passe actuel" data-i18n-placeholder="placeholder_current_pwd" style="margin:0">
|
||
<button id="toggleCurrentPassword" class="secondary" type="button"
|
||
aria-label="Afficher le mot de passe actuel" title="Afficher le mot de passe actuel" data-i18n-title="settings_show_cur_pwd" data-i18n-aria-label="settings_show_cur_pwd"><svg width="20"
|
||
height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
|
||
stroke-linejoin="round" aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
|
||
<button id="saveAuth" type="button" data-i18n="settings_admin_save_btn">Modifier les identifiants</button>
|
||
<span id="authSettingsMessage" class="muted"></span>
|
||
</div>
|
||
|
||
<div id="twoFaBox" style="margin-top:24px;padding-top:20px;border-top:1px solid var(--line)">
|
||
<h2 data-i18n="settings_2fa_title">Double identification (2FA) & Codes de secours</h2>
|
||
<p id="twoFaState" class="muted" data-i18n="twofa_loading">Chargement…</p>
|
||
<div id="twoFaSetup" style="display:none">
|
||
<p class="muted" data-i18n="twofa_qr_scan_prompt">Scannez ce QR code avec votre application
|
||
d’authentification, ou saisissez la clé manuellement :</p>
|
||
<div id="twoFaQr"></div>
|
||
<p class="muted"><span data-i18n="twofa_key_label">Clé :</span> <strong id="twoFaSecret"
|
||
style="color:var(--text);word-break:break-all"></strong></p>
|
||
</div>
|
||
<div id="twoFaRecoveryDisplay" class="recovery-card" style="display:none">
|
||
<div style="font-weight:700;color:var(--blue);margin-bottom:6px" data-i18n="twofa_recovery_title">⚠️ Codes
|
||
de récupération (secours)</div>
|
||
<p class="muted" style="font-size:13px;margin:0 0 10px" data-i18n="twofa_recovery_desc">Conservez ces 8
|
||
codes en lieu sûr. En cas de perte de votre application 2FA, chaque code vous permet de vous connecter une
|
||
seule fois :</p>
|
||
<div id="twoFaRecoveryGrid" class="recovery-grid"></div>
|
||
<div class="recovery-actions">
|
||
<button id="copyRecoveryCodes" class="secondary" type="button" data-i18n="settings_2fa_copy_btn">📋 Copier
|
||
les codes</button>
|
||
<button id="downloadRecoveryCodes" class="secondary" type="button"
|
||
data-i18n="settings_2fa_download_btn">💾 Télécharger (.txt)</button>
|
||
</div>
|
||
</div>
|
||
<div id="twoFaInputGroup" style="margin-top:12px">
|
||
<input id="twoFaCode" type="text" autocomplete="off" placeholder="Code TOTP à 6 chiffres ou code de secours"
|
||
data-i18n-placeholder="placeholder_totp_code" style="display:none">
|
||
<p id="twoFaHelpText" class="muted" style="font-size:12px;display:none" data-i18n="twofa_help_text">Le mot
|
||
de passe actuel saisi ci-dessus et un code (TOTP ou secours) sont requis.</p>
|
||
</div>
|
||
<div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:12px">
|
||
<button id="twoFaEnable" type="button" data-i18n="settings_2fa_enable_btn">Activer la 2FA</button>
|
||
<button id="twoFaConfirm" type="button" style="display:none" data-i18n="settings_2fa_confirm_btn">Valider le
|
||
code 2FA</button>
|
||
<button id="twoFaDownloadMenuBtn" class="secondary" type="button" style="display:none"
|
||
data-i18n="twofa_download_codes_btn">💾 Télécharger les codes de récupération</button>
|
||
<button id="twoFaRegenRecovery" class="secondary" type="button" style="display:none"
|
||
data-i18n="settings_2fa_regen_btn">Régénérer les codes</button>
|
||
<button id="twoFaDisable" class="secondary" type="button" style="display:none"
|
||
data-i18n="settings_2fa_disable_btn">Désactiver la 2FA</button>
|
||
</div>
|
||
<span id="twoFaMessage" class="muted" style="margin-top:10px;display:block"></span>
|
||
</div>
|
||
|
||
<div id="passkeyBox" style="margin-top:24px;padding-top:20px;border-top:1px solid var(--line)">
|
||
<div class="topline" style="flex-wrap:wrap;gap:12px;margin-bottom:12px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="settings_passkeys_title">🔑 Clés de sécurité & Passkeys (FIDO2 /
|
||
Biométrie)</h2>
|
||
<p class="muted" style="margin:0;font-size:13px" data-i18n-html="settings_passkeys_desc">Connectez-vous
|
||
instantanément <strong>sans mot de passe et sans double vérification</strong> avec Touch ID, Face ID,
|
||
Windows Hello ou une clé USB physique (YubiKey).</p>
|
||
</div>
|
||
<button id="btnAddPasskey" type="button"
|
||
style="display:inline-flex;align-items:center;gap:6px;font-size:13px"
|
||
data-i18n="settings_passkeys_add_btn">
|
||
➕ Enregistrer une nouvelle Passkey
|
||
</button>
|
||
</div>
|
||
<div id="passkeySupportAlert"
|
||
style="display:none;background:rgba(255,107,107,0.12);border:1px solid rgba(255,107,107,0.3);color:var(--red);padding:10px 14px;border-radius:8px;font-size:13px;margin-bottom:12px">
|
||
</div>
|
||
<div id="passkeyListContainer" class="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th data-i18n="th_passkey_name">NOM DE LA PASSKEY</th>
|
||
<th data-i18n="th_added_date">DATE D’AJOUT</th>
|
||
<th data-i18n="th_last_used">DERNIÈRE UTILISATION</th>
|
||
<th style="text-align:right" data-i18n="th_action">ACTION</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="passkeyTableBody">
|
||
<tr>
|
||
<td colspan="4" class="empty" data-i18n="loading_passkeys">Chargement des Passkeys…</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<span id="passkeyMessage" class="muted" style="margin-top:10px;display:block"></span>
|
||
</div>
|
||
|
||
<div id="adminSessionsBox" style="margin-top:24px;padding-top:20px;border-top:1px solid var(--line)">
|
||
<div class="topline" style="flex-wrap:wrap;gap:12px;margin-bottom:12px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="settings_sessions_title">Sessions connectées au compte
|
||
administrateur</h2>
|
||
<p class="muted" style="margin:0;font-size:13px" data-i18n="settings_sessions_desc">Appareils et
|
||
navigateurs actuellement connectés avec les identifiants d’administration.</p>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th data-i18n="th_device">APPAREIL / MACHINE</th>
|
||
<th data-i18n="th_ip">ADRESSE IP</th>
|
||
<th data-i18n="th_os">SYSTÈME (OS)</th>
|
||
<th data-i18n="th_browser">NAVIGATEUR</th>
|
||
<th data-i18n="th_last_activity">DERNIÈRE ACTIVITÉ</th>
|
||
<th data-i18n="th_action">ACTION</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="adminSessionsBody">
|
||
<tr>
|
||
<td colspan="6" class="empty" data-i18n="sessions_loading">Chargement des sessions…</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<span id="sessionsMessage" class="muted" style="margin-top:10px;display:block"></span>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 2b. Profils VPN (WireGuard & OpenVPN) -->
|
||
<div id="panelSettingsVpn" class="settings-panel card" style="display:none">
|
||
<div
|
||
style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-bottom:16px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="settings_vpn_title">Profils VPN WireGuard & OpenVPN</h2>
|
||
<div class="muted" style="font-size:13px" data-i18n="settings_vpn_subtitle">Gérez vos profils VPN pour
|
||
router le trafic Internet de vos équipements Wi‑Fi via des tunnels chiffrés.</div>
|
||
</div>
|
||
<button type="button" onclick="openVpnModal()" style="display:inline-flex;align-items:center;gap:6px">
|
||
<span>➕</span> <span data-i18n="vpn_add_profile_btn">Ajouter un profil VPN</span>
|
||
</button>
|
||
</div>
|
||
|
||
<div id="vpnProfilesList"
|
||
style="display:grid;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));gap:14px;margin-top:14px">
|
||
<!-- Cartes de profils injectées par JS -->
|
||
</div>
|
||
<div id="vpnProfilesEmpty"
|
||
style="display:none;text-align:center;padding:40px 20px;border:1px dashed var(--line);border-radius:12px;margin-top:14px">
|
||
<div style="font-size:36px;margin-bottom:10px">🌐</div>
|
||
<div style="font-weight:600;font-size:16px" data-i18n="vpn_no_profiles_title">Aucun profil VPN configuré</div>
|
||
<div class="muted" style="font-size:13px;margin:6px 0 16px" data-i18n="vpn_no_profiles_desc">Importez un
|
||
fichier .conf (WireGuard) ou .ovpn (OpenVPN) pour commencer.</div>
|
||
<button type="button" onclick="openVpnModal()" style="display:inline-flex;align-items:center;gap:6px">
|
||
<span>➕</span> <span data-i18n="vpn_add_first_profile_btn">Ajouter un premier profil</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 2c. Configuration du Proxy Inversé (Reverse Proxy & IP réelle) -->
|
||
<div id="panelSettingsProxy" class="settings-panel card" style="display:none">
|
||
<div
|
||
style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-bottom:14px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="settings_proxy_title">🔀 Configuration du Proxy Inversé (Reverse
|
||
Proxy)</h2>
|
||
<p class="muted" style="margin:0;font-size:13px" data-i18n="settings_proxy_desc">Définissez la détection de
|
||
la véritable adresse IP cliente lorsque votre point d’accès est placé derrière un reverse proxy (Nginx,
|
||
Traefik, Caddy, Cloudflare, HAProxy, etc.). Cela garantit que les journaux de connexion et sessions
|
||
affichent la vraie IP de la machine cliente plutôt que celle du proxy.</p>
|
||
</div>
|
||
<button id="btnRefreshProxyDiag" class="secondary" type="button" onclick="loadReverseProxySettings()"
|
||
style="display:inline-flex;align-items:center;gap:6px;font-size:13px" data-i18n="settings_proxy_btn_test">
|
||
🔄 Tester la détection
|
||
</button>
|
||
</div>
|
||
|
||
<!-- Carte Diagnostic en temps réel -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-bottom:20px">
|
||
<div
|
||
style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<strong style="font-size:14px;color:var(--text)" data-i18n="proxy_live_diag_title">🔍 Détection de l'IP en
|
||
direct (Votre connexion actuelle)</strong>
|
||
<span id="proxyDiagBadge" class="pill pill-green pill-no-dot" style="font-size:11px"
|
||
data-i18n="proxy_live_diag_badge">● Détection active</span>
|
||
</div>
|
||
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px">
|
||
<div style="background:var(--panel);border:1px solid var(--line);padding:10px 14px;border-radius:8px">
|
||
<span class="muted" style="font-size:11px;font-weight:600;display:block"
|
||
data-i18n="proxy_label_real_client_ip">IP CLIENT RÉELLE ENREGISTRÉE</span>
|
||
<code id="proxyDiagRealIp" style="font-size:15px;color:var(--green);font-weight:700">—</code>
|
||
</div>
|
||
<div style="background:var(--panel);border:1px solid var(--line);padding:10px 14px;border-radius:8px">
|
||
<span class="muted" style="font-size:11px;font-weight:600;display:block"
|
||
data-i18n="proxy_label_raw_socket_ip">IP BRUTE REÇUE (PROXY OU SOCKET)</span>
|
||
<code id="proxyDiagRawIp" style="font-size:14px;color:var(--blue)">—</code>
|
||
</div>
|
||
<div style="background:var(--panel);border:1px solid var(--line);padding:10px 14px;border-radius:8px">
|
||
<span class="muted" style="font-size:11px;font-weight:600;display:block"
|
||
data-i18n="proxy_label_xff">EN-TÊTE X-FORWARDED-FOR</span>
|
||
<code id="proxyDiagXff" style="font-size:13px;word-break:break-all">—</code>
|
||
</div>
|
||
<div style="background:var(--panel);border:1px solid var(--line);padding:10px 14px;border-radius:8px">
|
||
<span class="muted" style="font-size:11px;font-weight:600;display:block"
|
||
data-i18n="proxy_label_xrealip">EN-TÊTE X-REAL-IP</span>
|
||
<code id="proxyDiagXri" style="font-size:13px;word-break:break-all">—</code>
|
||
</div>
|
||
</div>
|
||
<div style="margin-top:10px;font-size:12px;color:var(--muted);display:flex;gap:16px;flex-wrap:wrap">
|
||
<span><span data-i18n="proxy_label_cf_ip">En-tête Cloudflare (CF-Connecting-IP) :</span> <code
|
||
id="proxyDiagCf">—</code></span>
|
||
<span><span data-i18n="proxy_label_proto">Protocole amont (X-Forwarded-Proto) :</span> <code id="proxyDiagProto">—</code></span>
|
||
<span><span data-i18n="proxy_label_host">Hôte :</span> <code id="proxyDiagHost">—</code></span>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Formulaire de réglages -->
|
||
<form id="formProxySettings" onsubmit="event.preventDefault();saveReverseProxySettings();"
|
||
style="display:flex;flex-direction:column;gap:16px">
|
||
<div class="row check" style="margin-top:0">
|
||
<input id="proxyEnabled" type="checkbox" checked>
|
||
<label for="proxyEnabled" style="cursor:pointer;font-weight:600" data-i18n="settings_proxy_enable_chk">
|
||
Activer la prise en charge du Reverse Proxy
|
||
</label>
|
||
</div>
|
||
<p class="muted" style="font-size:12px;margin:-8px 0 0 24px">
|
||
<span data-i18n="proxy_enable_desc_full">Lorsque cette option est activée, AP Manageur extrait l'adresse IP
|
||
réelle de la machine cliente à partir des en-têtes HTTP transmis par votre reverse proxy au lieu de
|
||
consigner l'adresse IP locale du proxy lui-même.</span>
|
||
</p>
|
||
|
||
<div>
|
||
<label class="label" for="proxyHeaderSelect" style="display:block;margin-bottom:6px;font-weight:600"
|
||
data-i18n="settings_proxy_header_label">En-tête HTTP prioritaire pour l'IP réelle</label>
|
||
<select id="proxyHeaderSelect"
|
||
style="max-width:420px;padding:8px 12px;background:var(--panel2);color:var(--text);border:1px solid var(--line);border-radius:8px;width:100%">
|
||
<option value="auto" data-i18n="proxy_opt_auto">Détection automatique intelligente (Recommandé : CF >
|
||
XFF > X-Real-IP)</option>
|
||
<option value="x-forwarded-for" data-i18n="proxy_opt_xff">X-Forwarded-For (Standard RFC 7239 / Nginx / Traefik / Caddy)</option>
|
||
<option value="x-real-ip" data-i18n="proxy_opt_xrealip">X-Real-IP (Commun avec Nginx / Apache)</option>
|
||
<option value="cf-connecting-ip" data-i18n="proxy_opt_cf">CF-Connecting-IP (Spécifique Cloudflare)
|
||
</option>
|
||
<option value="true-client-ip" data-i18n="proxy_opt_true_client_ip">True-Client-IP (Cloudflare Enterprise / Akamai)</option>
|
||
</select>
|
||
<div class="muted" style="font-size:12px;margin-top:4px">
|
||
<span data-i18n="proxy_auto_hint_full">En mode automatique, le système examine dans l'ordre les en-têtes
|
||
Cloudflare, X-Forwarded-For (le premier IP client non mandataire) puis X-Real-IP.</span>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="row check" style="margin-top:6px">
|
||
<input id="proxyTrustPrivate" type="checkbox" checked>
|
||
<label for="proxyTrustPrivate" style="cursor:pointer;font-weight:600"
|
||
data-i18n="settings_proxy_trust_private">
|
||
Faire confiance à tous les réseaux privés et conteneurs Docker
|
||
</label>
|
||
</div>
|
||
<p class="muted" style="font-size:12px;margin:-8px 0 0 24px">
|
||
<span data-i18n="proxy_trusted_desc_full">Autorise les en-têtes de proxy provenant des réseaux privés locaux
|
||
(10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.1). Recommandé si votre reverse proxy est un conteneur
|
||
Docker ou une passerelle LAN.</span>
|
||
</p>
|
||
|
||
<div>
|
||
<label class="label" for="proxyTrustedIps" style="display:block;margin-bottom:6px;font-weight:600"
|
||
data-i18n="settings_proxy_trusted_ips_label">Adresses IP ou plages CIDR des proxys de confiance
|
||
supplémentaires</label>
|
||
<textarea id="proxyTrustedIps" rows="2" placeholder="Ex: 172.18.0.0/16, 192.168.1.254, 10.0.4.1"
|
||
data-i18n-placeholder="placeholder_trusted_proxies"
|
||
style="width:100%;padding:8px 12px;background:var(--panel2);color:var(--text);border:1px solid var(--line);border-radius:8px;font-family:monospace;font-size:13px;resize:vertical"></textarea>
|
||
<div class="muted" style="font-size:12px;margin-top:4px">
|
||
<span data-i18n="proxy_trusted_ips_hint_full">Séparez plusieurs adresses IP ou sous-réseaux CIDR par des
|
||
virgules ou retours à la ligne. Si votre proxy n'est pas sur une IP privée, vous DEVEZ indiquer son IP
|
||
publique ici pour éviter toute usurpation d'adresse IP (IP spoofing).</span>
|
||
</div>
|
||
</div>
|
||
|
||
<div style="display:flex;align-items:center;gap:12px;margin-top:8px">
|
||
<button id="btnSaveProxySettings" class="primary" type="submit"
|
||
style="display:inline-flex;align-items:center;gap:6px" data-i18n="settings_proxy_save_btn">
|
||
💾 Enregistrer les réglages du proxy
|
||
</button>
|
||
<span id="proxySettingsMsg" style="font-size:13px"></span>
|
||
</div>
|
||
</form>
|
||
|
||
<!-- Bloc Conseils & Exemples de configuration -->
|
||
<div style="margin-top:24px;border-top:1px solid var(--line);padding-top:18px">
|
||
<h3 style="margin:0 0 10px;font-size:14px;color:var(--text)" data-i18n="proxy_examples_title">💡 Exemples de
|
||
configuration pour votre Reverse Proxy</h3>
|
||
<div style="font-size:12px;color:var(--muted);margin-bottom:12px">
|
||
<span data-i18n="proxy_examples_desc_full">Pour que votre reverse proxy transmette correctement l'IP de la
|
||
machine cliente à AP Manageur, assurez-vous d'avoir configuré ces en-têtes :</span>
|
||
</div>
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:12px;font-family:monospace;font-size:12px;line-height:1.6;overflow-x:auto">
|
||
<div style="color:var(--blue);font-weight:600;margin-bottom:4px"># Exemple Nginx :</div>
|
||
<div>proxy_set_header Host $host;</div>
|
||
<div>proxy_set_header X-Real-IP $remote_addr;</div>
|
||
<div>proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;</div>
|
||
<div>proxy_set_header X-Forwarded-Proto $scheme;</div>
|
||
<div style="color:var(--blue);font-weight:600;margin-top:8px;margin-bottom:4px"># Exemple Caddy :</div>
|
||
<div>reverse_proxy http://ip-du-conteneur:80</div>
|
||
<div style="color:var(--blue);font-weight:600;margin-top:8px;margin-bottom:4px"># Exemple Traefik :</div>
|
||
<div># Traefik transmet automatiquement X-Forwarded-For et X-Real-IP par défaut.</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 3. Notifications (Mail, Gotify, Discord) -->
|
||
<div id="panelSettingsNotif" class="settings-panel card" style="display:none">
|
||
<h2 data-i18n="settings_notif_title">Notifications & Alertes</h2>
|
||
<p class="muted" data-i18n="settings_notif_desc">Recevez des alertes en temps réel par Email, Gotify ou Discord
|
||
lors d’événements réseau ou d’accès.</p>
|
||
|
||
<div class="settings-nav" role="tablist" style="margin:16px 0 20px">
|
||
<button id="tabNotifServices" class="settings-nav-btn active" type="button" role="tab" aria-selected="true"
|
||
onclick="selectNotifSubTab('services')">
|
||
<span>📡</span> <span data-i18n="settings_notif_tab_services">Services de notification (9)</span>
|
||
</button>
|
||
<button id="tabNotifAlerts" class="settings-nav-btn" type="button" role="tab" aria-selected="false"
|
||
onclick="selectNotifSubTab('alerts')">
|
||
<span>✏️</span> <span data-i18n="settings_notif_tab_alerts">Personnalisation des alertes</span>
|
||
</button>
|
||
</div>
|
||
|
||
<!-- Sous-onglet 1 : Services de notification (Email, Gotify, Discord, ntfy, etc.) -->
|
||
<div id="panelNotifServices" style="display:block">
|
||
<!-- Canal 1 : Email (SMTP) -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-bottom:16px">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<div style="width:32px;height:32px;flex-shrink:0;display:flex;align-items:center;justify-content:center"><svg width="28" height="28" viewBox="0 0 24 24" fill="none"><rect width="24" height="24" rx="6" fill="#2563EB"/><path d="M4 7.5A2.5 2.5 0 0 1 6.5 5h11A2.5 2.5 0 0 1 20 7.5v9a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 4 16.5v-9zm2.2-.5a1 1 0 0 0-.7 1.7l6 5a1 1 0 0 0 1.3 0l6-5a1 1 0 0 0-.7-1.7H6.2z" fill="#FFFFFF"/></svg></div>
|
||
<div>
|
||
<strong style="font-size:15px" data-i18n="notif_email_title">Notification par Email (SMTP)</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="notif_email_desc">Envoi direct via votre serveur
|
||
de messagerie</div>
|
||
</div>
|
||
</div>
|
||
<label class="check" style="margin:0;font-weight:700"><input id="notifEmailEnabled" type="checkbox"
|
||
onchange="toggleNotifFields('email')"> <span data-i18n="notif_email_enable">Activer
|
||
Email</span></label>
|
||
</div>
|
||
|
||
<div id="notifEmailFields" style="display:none;padding-top:10px;border-top:1px solid var(--line)">
|
||
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="notifEmailHost" style="margin-top:4px"
|
||
data-i18n="notif_email_host_label">Hôte SMTP</label>
|
||
<input id="notifEmailHost" type="text" placeholder="smtp.gmail.com">
|
||
</div>
|
||
<div>
|
||
<label class="label" for="notifEmailPort" style="margin-top:4px"
|
||
data-i18n="notif_email_port_label">Port SMTP</label>
|
||
<input id="notifEmailPort" type="number" placeholder="587">
|
||
</div>
|
||
</div>
|
||
|
||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="notifEmailSecure" data-i18n="notif_email_sec_label">Sécurité</label>
|
||
<select id="notifEmailSecure"
|
||
style="display:block;width:100%;margin:7px 0 16px;padding:12px;border-radius:9px;border:1px solid var(--line);background:var(--panel);color:var(--text);font-size:14px">
|
||
<option value="starttls" data-i18n="notif_email_starttls_hint">STARTTLS (recommandé port 587)
|
||
</option>
|
||
<option value="ssl" data-i18n="notif_email_sec_ssl_465">SSL / TLS (port 465)</option>
|
||
<option value="none" data-i18n="notif_email_none_hint">Aucune (port 25 non chiffré)</option>
|
||
</select>
|
||
</div>
|
||
<div>
|
||
<label class="label" for="notifEmailUser" data-i18n="notif_email_user_label">Identifiant SMTP</label>
|
||
<input id="notifEmailUser" type="text" placeholder="utilisateur@exemple.com">
|
||
</div>
|
||
</div>
|
||
|
||
<label class="label" for="notifEmailPass" data-i18n="notif_email_pass_label">Mot de passe SMTP</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="notifEmailPass" type="password" placeholder="Mot de passe ou mot de passe d’application"
|
||
data-i18n-placeholder="placeholder_email_pass" style="margin:0">
|
||
<button id="toggleNotifEmailPass" class="secondary" type="button" aria-label="Afficher le mot de passe"
|
||
title="Afficher le mot de passe" data-i18n-title="btn_show_pwd" data-i18n-aria-label="btn_show_pwd"><svg width="20" height="20" viewBox="0 0 24 24" fill="none"
|
||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
|
||
aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
|
||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="notifEmailFrom" data-i18n="notif_email_from_full">Expéditeur (From)</label>
|
||
<input id="notifEmailFrom" type="text" placeholder="AP Manageur <alerte@exemple.com>">
|
||
</div>
|
||
<div>
|
||
<label class="label" for="notifEmailTo" data-i18n="notif_email_to_label">Destinataire(s) (To)</label>
|
||
<input id="notifEmailTo" type="text" placeholder="destinataire@exemple.com">
|
||
</div>
|
||
</div>
|
||
<div style="display:flex;justify-content:flex-end;margin-top:8px">
|
||
<button type="button" class="secondary" onclick="testNotificationChannel('email')"
|
||
style="font-size:13px;padding:6px 14px" data-i18n="notif_email_test_btn">Tester l’envoi Email</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Canal 2 : Gotify -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-bottom:16px">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<div style="width:32px;height:32px;flex-shrink:0;display:flex;align-items:center;justify-content:center"><svg width="32" height="32" viewBox="46.6 113.46 377.2 307.81" fill="none" xmlns="http://www.w3.org/2000/svg"><style>.gtf-paw{fill:#ddcba2;stroke:#000;stroke-width:2;stroke-linecap:round;stroke-miterlimit:10}.gtf-body{fill:#71caee;stroke:#000;stroke-width:2;stroke-linecap:round;stroke-miterlimit:10}.gtf-white{fill:#fff;stroke:#000;stroke-width:2;stroke-linecap:round;stroke-miterlimit:10}.gtf-env{fill:#f0f0f0;stroke:#000;stroke-width:2;stroke-linecap:round;stroke-miterlimit:10}.gtf-none{fill:none;stroke:#000;stroke-width:2;stroke-linecap:round;stroke-miterlimit:10}</style><path d="M317.7 376.2c6.2-1.7 15.8 0 19.5 3.2 5.5 4.8 4.9 20.9 1.1 29-.8 1.7-1.8 3.4-3.2 4.4s-3.4 1.2-4.7 0-1.7-3.3-1.9-5.2c-.2-3.1-.2-6.2.3-9.2.2-1.3.2-2.9-.2-4.2-.6-2.2-2.5-3.1-4.5-3.5-3.4-.8-14.3-.7-19.5-.7-.8 0 1.5-9.1 2-9.7 2.6-2.9 7.5-3.1 11.1-4.1z" class="gtf-paw"/><path d="m258.9 119.7-9-2.7c-4.6-1.4-9.2-2.8-14-2.5-2.8.2-6.1 1.3-6.9 4-.6 2-1.6 7.3-1.3 7.9 1.5 3.4 13.9 6.7 18.3 6.7" class="gtf-body"/><path d="M392.6 177.9c-1.4 1.4-2.2 3.5-2.5 5.5-.2 1.4-.1 3 .5 4.3s1.8 2.3 3.1 3c1.3.6 2.8.9 4.3.9 1.1 0 2.3-.1 3.1-.9.6-.7.8-1.6.9-2.5.2-2.3-.1-4.7-.9-6.9-.4-1.1-.9-2.3-1.8-3.1-1.7-1.8-4.5-2.2-6.4-.5-.1 0-.2.1-.3.2" fill="#000"/><path d="M358.5 164.2c-1-1 0-2.7 1-3.7 5.8-5.2 15.1-4.6 21.8-.6 10.9 6.6 15.6 19.9 17.2 32.5.6 5.2.9 10.6-.5 15.7s-4.6 9.9-9.3 12.1c-1.1.5-2.3.9-3.4.5s-1.9-1.8-1.2-2.8c-9.4-13.6-19-26.8-20.9-43.2-.5-4.1-1.8-7.4-4.7-10.5z" class="gtf-white"/><path d="M134.7 328.4c-5.1-3.1-9.9-6.6-14.3-10.6-1.3-1.2-2.6-2.5-2.6-4.3 0-1.2.6-2.2 1.2-3.2.8-1.4 1.7-2.8 2.5-4.1 1.1-1.8 2.9-3.9 4.9-3.2.9.3 1.5 1.1 2 1.8 2.4 3.3 4.9 6.6 7.3 9.8 1.5 2 3.7 4.3 6.1 3.5" class="gtf-body"/><path d="M209.6 133c33.2-18 77.8-19.6 111.5-8.7 24.3 7.9 43.4 26.7 53.3 50 8.7 20.6 10.5 43.6 8.1 65.7-4.4 40.2-20.2 77.9-40.3 112.6-11.1 19-21.8 36-40.5 48.5-36.8 24.6-87.2 22.1-128.4 11.5-19.9-5.1-39.7-17.3-47.2-37.3-4.8-12.8-4.2-27.6 1.5-40 11.6-24.8 43.2-38.4 45.6-67.9.7-8.7-1.6-17.3-3.6-25.7-5.6-23.4-8.9-45.8 1.4-68.7 8.1-17.7 21.9-31 38.6-40z" class="gtf-body"/><path d="M189.8 151.4c-5.4-5.2-11.9-8.8-19-10.3-2.2-.5-4.7-.7-6.9.7-1.8 1.2-3.1 3.3-4.2 5.3-1.6 3-3 6.2-4.1 9.4-.4 1.2-.6 2.5 0 3.5.3.6.9.9 1.5 1.2 8.1 4.2 16.8 7.1 25.5 9.8" class="gtf-body"/><path d="M183.7 158.7c-2.5-1.8-16.8-12.1-18.7-4.8-.4 1.6.5 3.9 1.5 4.8" class="gtf-body"/><path d="M264.5 174.9c-.5.5-.9 1-1.3 1.6-9 11.6-12 27.9-9.3 42.1 1.7 9 5.9 17.9 13.2 23.4 19.3 14.6 51.5 13.5 68.4-1.5 24.4-21.7 13-67.6-14-78.8-17.6-7.2-43.7-1.6-57 13.2zm117.6 62.2c1.4-.1 2.9-.1 4.3.1.3 0 .7.1 1 .4.2.3.4.7.5 1.1 1 3.9.5 8.2.1 12.4-.1.9-.2 1.8-.6 2.6-1 2.1-3.1 2.7-4.7 2.7-.1 0-.2 0-.3-.1-.3-.2-.3-.7-.2-1.2.3-5.9-.1-11.9-.1-18q0 .15 0 0z" class="gtf-white"/><path d="M378.7 236.8c-1.4.4-2.5 2-2.8 4.4-.5 4.4-.7 8.9-.5 13.4 0 .9.1 1.9.5 2.4.2.3.5.4.8.4 1.6.3 4.1-.6 5.6-1 0 0 0-5.2-.1-8s-.1-6.1-.2-8.9v-2.2c.1-.7-2.6-.7-3.3-.5z" class="gtf-white"/><path d="M358.3 231.8c-.3 2.2.1 4.7 1.7 7.4 2.6 4.4 7 6.1 11.9 5.8 8.9-.6 25.3-5.4 27.5-15.7.6-3-.3-6.1-2.2-8.5-6.2-7.8-17.8-5.7-25.6-2-5.9 2.7-12.4 7-13.3 13z" class="gtf-paw"/><path d="M386.4 208.6c2.2 1.4 3.7 3.8 4 7 .3 3.6-1.4 7.5-5 8.8-2.9 1.1-6.2.6-9.1-.4s-5.8-2.8-6.8-5.7c-.7-2-.3-4.3.7-6.1 1.1-1.8 2.8-3.2 4.7-4.1 3.9-1.8 8.4-1.6 11.5.5z" fill="#888e93" stroke="#000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10"/><path d="M414.7 262.6c2.4.6 4.8 2.1 5.6 4.4s.1 4.9-1.6 6.7-4.2 2.5-6.6 2.5c-.8 0-1.7-.1-2.4-.5-2.5-1.1-3.5-4-4.2-6.6-1.8-6.8 3.6-7.8 9.2-6.5z" class="gtf-paw"/><path d="M267.1 284.7c2.3-4.5 141.3-36.2 144.7-31.6 3.4 4.5 15.8 88.2 9 90.4-6.8 2.3-119.8 37.3-126.6 35s-29.4-89.3-27.1-93.8z" class="gtf-env"/><path d="M294.2 378.5s54.3-74.6 59.9-76.9c5.7-2.3 67.3 41.3 67.3 41.3" class="gtf-none"/><path d="M267 287.7s86 38.8 91.6 36.6c5.7-2.3 53.1-71.2 53.1-71.2" class="gtf-env"/><path d="M132.8 375.6c-3.5 3.8-7.3 7.8-13 9.2-4.6 1.2-10 .2-13.6-2.3-1.4-1-2.6-2.2-4-3.2-1.5-1-3.4-1.7-5.3-1.3-2.7.5-4.1 3.1-3.6 5.3 2 8.8 17 15.6 27.5 15.5 9 0 19-4.6 21.4-11.8" class="gtf-paw"/><path d="M261.9 283.5c-.1 4.2 4.3 7.3 8.4 7.6s8.2-1.3 12.2-2.6c1.4-.4 2.9-.8 4.2-.2 1.8.9 2.7 4.1 1.8 5.9s-3.4 3.5-5.3 4.4c-6.5 3-12.9 3.6-19.9 2-5.3-1.2-11.3-4.3-13-13.5" class="gtf-paw"/><path d="M318.4 198.4c-2-.3-4.1.1-5.9 1.3-3.2 2.1-4.7 6.2-4.7 9.9 0 1.9.4 3.8 1.4 5.3 1.2 1.7 3.1 2.9 5.2 3.4 3.4.8 8.2.7 10.5-2.5 1-1.5 1.4-3.3 1.5-5.1.5-5.7-1.8-11.4-8-12.3" fill="#000"/><path d="M320.4 203.3c.9.3 1.7.8 2.1 1.7.4.8.4 1.7.3 2.5-.1 1-.6 2-1.5 2.7-.7.5-1.7.7-2.6.5s-1.7-.8-2.2-1.6c-1.1-1.6-.9-4.4.9-5.5.9-.4 2-.6 3-.3" fill="#fff"/><path d="M81.6 222.4s56.5 68.4 123.9 42.4l6.6-29.7C150 272.2 82.8 214.3 82.8 214.3z" fill="#575756" opacity="0.3"/><path d="M64.2 234.9s63.1 101.5 157.8 78.9l14.2-38.5c-89.5 38.3-168.9-51-168.9-51z" fill="#575756" opacity="0.3"/><path d="M46.6 251.5s61.1 130.9 178 117.5l22.6-44.2c-113 33-195.3-85.7-195.3-85.7z" fill="#575756" opacity="0.3"/></svg></div>
|
||
<div>
|
||
<strong style="font-size:15px" data-i18n="notif_gotify_title">Notification Gotify</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="notif_gotify_desc">Serveur de push auto-hébergé
|
||
léger et instantané (Compatible Gotify v2 & v3.1.1+)</div>
|
||
</div>
|
||
</div>
|
||
<label class="check" style="margin:0;font-weight:700"><input id="notifGotifyEnabled" type="checkbox"
|
||
onchange="toggleNotifFields('gotify')"> <span data-i18n="notif_gotify_enable">Activer
|
||
Gotify</span></label>
|
||
</div>
|
||
|
||
<div id="notifGotifyFields" style="display:none;padding-top:10px;border-top:1px solid var(--line)">
|
||
<label class="label" for="notifGotifyUrl" style="margin-top:4px" data-i18n="notif_gotify_url_label">URL du
|
||
serveur Gotify</label>
|
||
<input id="notifGotifyUrl" type="text"
|
||
placeholder="http://192.168.1.50:8080 ou https://gotify.mon-domaine.fr">
|
||
|
||
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="notifGotifyToken" data-i18n="notif_gotify_token_apps">Jeton d’application
|
||
(Token APPS)</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="notifGotifyToken" type="password" placeholder="gtfya.xxxx ou Axxxx" style="margin:0">
|
||
<button id="toggleNotifGotifyToken" class="secondary" type="button" aria-label="Afficher le jeton"
|
||
title="Afficher le jeton" data-i18n-title="settings_show_token" data-i18n-aria-label="settings_show_token"><svg width="20" height="20" viewBox="0 0 24 24" fill="none"
|
||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
|
||
aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
</div>
|
||
<div>
|
||
<label class="label" for="notifGotifyPriority" data-i18n="notif_gotify_priority_range">Priorité (1 -
|
||
10)</label>
|
||
<input id="notifGotifyPriority" type="number" min="1" max="10" placeholder="5">
|
||
</div>
|
||
</div>
|
||
|
||
<div
|
||
style="font-size:12px;color:var(--muted);background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:10px 12px;margin-bottom:12px;line-height:1.5"
|
||
data-i18n-html="notif_gotify_alert_box">
|
||
⚠️ <strong>Important pour Gotify 3.1.1 :</strong> Le jeton doit provenir de l'onglet
|
||
<strong>APPS</strong> de Gotify (commençant par <code>gtfya...</code> en v3 ou <code>A...</code> en v2).
|
||
Les jetons de l'onglet <strong>CLIENTS</strong> (commençant par <code>gtfyc...</code> ou
|
||
<code>C...</code>) ne permettent pas de publier des alertes. Le HTTPS avec certificat auto-signé est
|
||
supporté.
|
||
</div>
|
||
|
||
<div style="display:flex;justify-content:flex-end;margin-top:8px">
|
||
<button type="button" class="secondary" onclick="testNotificationChannel('gotify')"
|
||
style="font-size:13px;padding:6px 14px" data-i18n="notif_gotify_test_btn">Tester Gotify</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Canal 3 : Discord Webhook -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-bottom:16px">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<div style="width:32px;height:32px;flex-shrink:0;display:flex;align-items:center;justify-content:center"><svg width="28" height="28" viewBox="0 0 24 24" fill="none"><rect width="24" height="24" rx="6" fill="#5865F2"/><path d="M18.8 6.5A14.2 14.2 0 0 0 15.3 5.4a.2.2 0 0 0-.2.1 9.9 9.9 0 0 0-.4.9 13.1 13.1 0 0 0-5.4 0 10.1 10.1 0 0 0-.4-.9.2.2 0 0 0-.2-.1A14.2 14.2 0 0 0 5.2 6.5a.2.2 0 0 0-.1.1C3.3 9.4 2.8 12.2 3.1 15a.2.2 0 0 0 .1.1 14.3 14.3 0 0 0 4.3 2.2.2.2 0 0 0 .2-.1 10.2 10.2 0 0 0 .9-1.4.2.2 0 0 0-.1-.2 9.3 9.3 0 0 1-1.3-.6.2.2 0 0 1 0-.3c.1-.1.2-.1.3-.2a10.2 10.2 0 0 0 9 0c.1.1.2.1.3.2a.2.2 0 0 1 0 .3 9.3 9.3 0 0 1-1.3.6.2.2 0 0 0-.1.2c.3.5.6 1 .9 1.4a.2.2 0 0 0 .2.1 14.3 14.3 0 0 0 4.3-2.2.2.2 0 0 0 .1-.1c.3-3.3-.6-6.1-2.2-8.4a.2.2 0 0 0-.1-.1zM9.5 13.1c-.8 0-1.5-.7-1.5-1.6s.7-1.6 1.5-1.6 1.5.7 1.5 1.6-.7 1.6-1.5 1.6zm5 0c-.8 0-1.5-.7-1.5-1.6s.7-1.6 1.5-1.6 1.5.7 1.5 1.6-.7 1.6-1.5 1.6z" fill="#FFFFFF"/></svg></div>
|
||
<div>
|
||
<strong style="font-size:15px" data-i18n="notif_discord_title">Notification Discord</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="notif_discord_desc">Envoi direct sur un canal de
|
||
salon via Webhook</div>
|
||
</div>
|
||
</div>
|
||
<label class="check" style="margin:0;font-weight:700"><input id="notifDiscordEnabled" type="checkbox"
|
||
onchange="toggleNotifFields('discord')"> <span data-i18n="notif_discord_enable">Activer
|
||
Discord</span></label>
|
||
</div>
|
||
|
||
<div id="notifDiscordFields" style="display:none;padding-top:10px;border-top:1px solid var(--line)">
|
||
<label class="label" for="notifDiscordWebhook" style="margin-top:4px"
|
||
data-i18n="notif_discord_url_label">URL du Webhook Discord</label>
|
||
<input id="notifDiscordWebhook" type="text"
|
||
placeholder="https://discord.com/api/webhooks/123456789/abcdef...">
|
||
|
||
<label class="label" for="notifDiscordBotName" data-i18n="notif_discord_bot_label">Nom du Bot
|
||
(optionnel)</label>
|
||
<input id="notifDiscordBotName" type="text" placeholder="AP Manageur">
|
||
|
||
<div style="display:flex;justify-content:flex-end;margin-top:8px">
|
||
<button type="button" class="secondary" onclick="testNotificationChannel('discord')"
|
||
style="font-size:13px;padding:6px 14px" data-i18n="notif_discord_test_btn">Tester Discord</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Canal 4 : ntfy.sh -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-bottom:16px">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<div style="width:32px;height:32px;flex-shrink:0;display:flex;align-items:center;justify-content:center"><svg width="28" height="28" viewBox="0 0 24 24" fill="none"><rect width="24" height="24" rx="6" fill="#1E40AF"/><path d="M12 4a5 5 0 0 0-5 5v3.2L5.6 14.8A1 1 0 0 0 6.4 16h11.2a1 1 0 0 0 .8-1.2L17 12.2V9a5 5 0 0 0-5-5zm-2 13a2 2 0 0 0 4 0h-4z" fill="#FFFFFF"/></svg></div>
|
||
<div>
|
||
<strong style="font-size:15px" data-i18n="notif_ntfy_title">Notification ntfy.sh</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="notif_ntfy_desc">Notifications push via ntfy.sh
|
||
ou serveur auto-hébergé</div>
|
||
</div>
|
||
</div>
|
||
<label class="check" style="margin:0;font-weight:700"><input id="notifNtfyEnabled" type="checkbox"
|
||
onchange="toggleNotifFields('ntfy')"> <span data-i18n="notif_ntfy_enable">Activer ntfy</span></label>
|
||
</div>
|
||
|
||
<div id="notifNtfyFields" style="display:none;padding-top:10px;border-top:1px solid var(--line)">
|
||
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="notifNtfyUrl" style="margin-top:4px"
|
||
data-i18n="notif_ntfy_server_label">Serveur ntfy</label>
|
||
<input id="notifNtfyUrl" type="text" placeholder="https://ntfy.sh">
|
||
</div>
|
||
<div>
|
||
<label class="label" for="notifNtfyTopic" style="margin-top:4px"
|
||
data-i18n="notif_ntfy_topic_label">Topic (sujet)</label>
|
||
<input id="notifNtfyTopic" type="text" placeholder="mon_topic_secret">
|
||
</div>
|
||
</div>
|
||
|
||
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="notifNtfyToken" data-i18n="notif_ntfy_token_opt">Jeton / Mot de passe
|
||
(optionnel pour topic privé)</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="notifNtfyToken" type="password" placeholder="tk_xxxxxxxxxxxx" style="margin:0">
|
||
<button id="toggleNotifNtfyToken" class="secondary" type="button" aria-label="Afficher le jeton"
|
||
title="Afficher le jeton" data-i18n-title="settings_show_token" data-i18n-aria-label="settings_show_token"><svg width="20" height="20" viewBox="0 0 24 24" fill="none"
|
||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
|
||
aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
</div>
|
||
<div>
|
||
<label class="label" for="notifNtfyPriority" data-i18n="notif_ntfy_priority_range">Priorité (1 -
|
||
5)</label>
|
||
<input id="notifNtfyPriority" type="number" min="1" max="5" placeholder="3">
|
||
</div>
|
||
</div>
|
||
|
||
<div style="display:flex;justify-content:flex-end;margin-top:8px">
|
||
<button type="button" class="secondary" onclick="testNotificationChannel('ntfy')"
|
||
style="font-size:13px;padding:6px 14px" data-i18n="notif_ntfy_test_btn">Tester ntfy</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Canal 5 : Pushbullet -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-bottom:16px">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<div style="width:32px;height:32px;flex-shrink:0;display:flex;align-items:center;justify-content:center"><svg width="28" height="28" viewBox="0 0 24 24" fill="none"><rect width="24" height="24" rx="6" fill="#4AB367"/><path d="M12 4.5A7.5 7.5 0 0 0 4.5 12 7.5 7.5 0 0 0 12 19.5 7.5 7.5 0 0 0 19.5 12 7.5 7.5 0 0 0 12 4.5zm-3.5 4h4a3.5 3.5 0 1 1 0 7h-1.5v2h-2.5v-9zm2.5 2v3h1.5a1.5 1.5 0 0 0 0-3H11z" fill="#FFFFFF"/></svg></div>
|
||
<div>
|
||
<strong style="font-size:15px" data-i18n="notif_pushbullet_title">Notification Pushbullet</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="notif_pushbullet_desc">Push instantané sur
|
||
téléphones, tablettes et navigateurs</div>
|
||
</div>
|
||
</div>
|
||
<label class="check" style="margin:0;font-weight:700"><input id="notifPushbulletEnabled" type="checkbox"
|
||
onchange="toggleNotifFields('pushbullet')"> <span data-i18n="notif_pushbullet_enable">Activer
|
||
Pushbullet</span></label>
|
||
</div>
|
||
|
||
<div id="notifPushbulletFields" style="display:none;padding-top:10px;border-top:1px solid var(--line)">
|
||
<label class="label" for="notifPushbulletToken" style="margin-top:4px"
|
||
data-i18n="notif_pushbullet_token_label">Jeton d’accès (Access Token)</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="notifPushbulletToken" type="password" placeholder="o.xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
|
||
style="margin:0">
|
||
<button id="toggleNotifPushbulletToken" class="secondary" type="button" aria-label="Afficher le jeton"
|
||
title="Afficher le jeton" data-i18n-title="settings_show_token" data-i18n-aria-label="settings_show_token"><svg width="20" height="20" viewBox="0 0 24 24" fill="none"
|
||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
|
||
aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
|
||
<label class="label" for="notifPushbulletDevice" data-i18n="notif_pushbullet_device_iden">ID de l’appareil
|
||
(Device Iden, optionnel — laisser vide pour tous)</label>
|
||
<input id="notifPushbulletDevice" type="text" placeholder="ujpah72o0sjAoStArDw">
|
||
|
||
<div style="display:flex;justify-content:flex-end;margin-top:8px">
|
||
<button type="button" class="secondary" onclick="testNotificationChannel('pushbullet')"
|
||
style="font-size:13px;padding:6px 14px" data-i18n="notif_pushbullet_test_btn">Tester
|
||
Pushbullet</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Canal 6 : Pushover -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-bottom:16px">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<div style="width:32px;height:32px;flex-shrink:0;display:flex;align-items:center;justify-content:center"><svg width="28" height="28" viewBox="0 0 24 24" fill="none"><rect width="24" height="24" rx="6" fill="#0A85B5"/><path d="M7.5 5h5.2c3 0 5.3 1.8 5.3 4.5 0 3-2.4 4.8-5.5 4.8H9.8L8.2 19H5.8L7.5 5zm2.8 2.2L9.2 12.1h3c1.7 0 3.2-.9 3.2-2.5 0-1.5-1.2-2.4-2.8-2.4h-2.3z" fill="#FFFFFF"/></svg></div>
|
||
<div>
|
||
<strong style="font-size:15px" data-i18n="notif_pushover_title">Notification Pushover</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="notif_pushover_desc">Push pour Android, iOS et
|
||
Desktop</div>
|
||
</div>
|
||
</div>
|
||
<label class="check" style="margin:0;font-weight:700"><input id="notifPushoverEnabled" type="checkbox"
|
||
onchange="toggleNotifFields('pushover')"> <span data-i18n="notif_pushover_enable">Activer
|
||
Pushover</span></label>
|
||
</div>
|
||
|
||
<div id="notifPushoverFields" style="display:none;padding-top:10px;border-top:1px solid var(--line)">
|
||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="notifPushoverUser" style="margin-top:4px"
|
||
data-i18n="notif_pushover_user_label">Clé utilisateur (User Key)</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="notifPushoverUser" type="password" placeholder="uQiRzpo4DXghDmr9Qnoxf5p6Bp3..."
|
||
style="margin:0">
|
||
<button id="toggleNotifPushoverUser" class="secondary" type="button" aria-label="Afficher la clé"
|
||
title="Afficher la clé" data-i18n-title="settings_show_key" data-i18n-aria-label="settings_show_key"><svg width="20" height="20" viewBox="0 0 24 24" fill="none"
|
||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
|
||
aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
</div>
|
||
<div>
|
||
<label class="label" for="notifPushoverToken" style="margin-top:4px"
|
||
data-i18n="notif_pushover_token_label">Jeton d’application (API Token)</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="notifPushoverToken" type="password" placeholder="azGDORePK8gMaC0QOYAMyEEuzJ3..."
|
||
style="margin:0">
|
||
<button id="toggleNotifPushoverToken" class="secondary" type="button" aria-label="Afficher le jeton"
|
||
title="Afficher le jeton" data-i18n-title="settings_show_token" data-i18n-aria-label="settings_show_token"><svg width="20" height="20" viewBox="0 0 24 24" fill="none"
|
||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
|
||
aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<label class="label" for="notifPushoverPriority" data-i18n="notif_pushover_priority_label">Priorité (-2 à
|
||
2 : 0 = Normal, 1 = Élevée)</label>
|
||
<input id="notifPushoverPriority" type="number" min="-2" max="2" placeholder="0">
|
||
|
||
<div style="display:flex;justify-content:flex-end;margin-top:8px">
|
||
<button type="button" class="secondary" onclick="testNotificationChannel('pushover')"
|
||
style="font-size:13px;padding:6px 14px" data-i18n="notif_pushover_test_btn">Tester Pushover</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Canal 7 : Slack -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-bottom:16px">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<div style="width:32px;height:32px;flex-shrink:0;display:flex;align-items:center;justify-content:center"><svg width="28" height="28" viewBox="0 0 24 24" fill="none"><rect width="24" height="24" rx="6" fill="#4A154B"/><path d="M6 10.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm2.5 0a1.5 1.5 0 0 1-1.5-1.5V5.5a1.5 1.5 0 1 1 3 0V9a1.5 1.5 0 0 1-1.5 1.5z" fill="#36C5F0"/><path d="M10.5 18a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm0-2.5a1.5 1.5 0 0 1-1.5 1.5H5.5a1.5 1.5 0 1 1 0-3H9a1.5 1.5 0 0 1 1.5 1.5z" fill="#2EB67D"/><path d="M18 13.5a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3zm-2.5 0a1.5 1.5 0 0 1 1.5 1.5v3.5a1.5 1.5 0 1 1-3 0V15a1.5 1.5 0 0 1 1.5-1.5z" fill="#ECB22E"/><path d="M13.5 6a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0zm0 2.5a1.5 1.5 0 0 1 1.5-1.5h3.5a1.5 1.5 0 1 1 0 3H15a1.5 1.5 0 0 1-1.5-1.5z" fill="#E01E5A"/></svg></div>
|
||
<div>
|
||
<strong style="font-size:15px" data-i18n="notif_slack_title">Notification Slack</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="notif_slack_desc">Alertes sur un canal Slack via
|
||
Webhook entrant (Incoming Webhook)</div>
|
||
</div>
|
||
</div>
|
||
<label class="check" style="margin:0;font-weight:700"><input id="notifSlackEnabled" type="checkbox"
|
||
onchange="toggleNotifFields('slack')"> <span data-i18n="notif_slack_enable">Activer
|
||
Slack</span></label>
|
||
</div>
|
||
|
||
<div id="notifSlackFields" style="display:none;padding-top:10px;border-top:1px solid var(--line)">
|
||
<label class="label" for="notifSlackWebhook" style="margin-top:4px" data-i18n="notif_slack_url_label">URL
|
||
du Webhook entrant Slack</label>
|
||
<input id="notifSlackWebhook" type="text"
|
||
placeholder="https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX">
|
||
|
||
<label class="label" for="notifSlackBotName" data-i18n="notif_slack_bot_label">Nom d’expéditeur du bot
|
||
(optionnel)</label>
|
||
<input id="notifSlackBotName" type="text" placeholder="AP Manageur">
|
||
|
||
<div style="display:flex;justify-content:flex-end;margin-top:8px">
|
||
<button type="button" class="secondary" onclick="testNotificationChannel('slack')"
|
||
style="font-size:13px;padding:6px 14px" data-i18n="notif_slack_test_btn">Tester Slack</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Canal 8 : Telegram -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-bottom:16px">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<div style="width:32px;height:32px;flex-shrink:0;display:flex;align-items:center;justify-content:center"><svg width="28" height="28" viewBox="0 0 24 24" fill="none"><rect width="24" height="24" rx="6" fill="#24A1DE"/><path d="M5.2 11.8l11.6-4.7c.6-.2 1.1.1 1 .8l-2 9.5c-.2.7-.6.9-1.2.6l-3.3-2.4-1.6 1.5c-.2.2-.4.4-.8.4l.2-3.3 6-5.4c.3-.3-.1-.4-.4-.2l-7.4 4.7-3.2-1c-.7-.2-.7-.7.1-1z" fill="#FFFFFF"/></svg></div>
|
||
<div>
|
||
<strong style="font-size:15px" data-i18n="notif_telegram_title">Notification Telegram</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="notif_telegram_desc">Alertes instantanées par bot
|
||
Telegram (canal, groupe ou privé)</div>
|
||
</div>
|
||
</div>
|
||
<label class="check" style="margin:0;font-weight:700"><input id="notifTelegramEnabled" type="checkbox"
|
||
onchange="toggleNotifFields('telegram')"> <span data-i18n="notif_telegram_enable">Activer
|
||
Telegram</span></label>
|
||
</div>
|
||
|
||
<div id="notifTelegramFields" style="display:none;padding-top:10px;border-top:1px solid var(--line)">
|
||
<label class="label" for="notifTelegramToken" style="margin-top:4px"
|
||
data-i18n="notif_telegram_token_label">Jeton du Bot (Bot Token @BotFather)</label>
|
||
<div style="display:flex;gap:8px;margin:7px 0 16px">
|
||
<input id="notifTelegramToken" type="password" placeholder="123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ"
|
||
style="margin:0">
|
||
<button id="toggleNotifTelegramToken" class="secondary" type="button" aria-label="Afficher le jeton"
|
||
title="Afficher le jeton" data-i18n-title="settings_show_token" data-i18n-aria-label="settings_show_token"><svg width="20" height="20" viewBox="0 0 24 24" fill="none"
|
||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
|
||
aria-hidden="true">
|
||
<path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z" />
|
||
<circle cx="12" cy="12" r="3" />
|
||
</svg></button>
|
||
</div>
|
||
|
||
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="notifTelegramChatId" data-i18n="notif_telegram_chat_label">Identifiant de
|
||
discussion (Chat ID)</label>
|
||
<input id="notifTelegramChatId" type="text" placeholder="123456789 ou -100123456789">
|
||
</div>
|
||
<div>
|
||
<label class="label" for="notifTelegramThreadId" data-i18n="notif_telegram_thread_label">Fil / Topic
|
||
(optionnel)</label>
|
||
<input id="notifTelegramThreadId" type="text" placeholder="12">
|
||
</div>
|
||
</div>
|
||
|
||
<div style="display:flex;justify-content:flex-end;margin-top:8px">
|
||
<button type="button" class="secondary" onclick="testNotificationChannel('telegram')"
|
||
style="font-size:13px;padding:6px 14px" data-i18n="notif_telegram_test_btn">Tester Telegram</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Canal 9 : Webhook personnalisé -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-bottom:16px">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<div style="width:32px;height:32px;flex-shrink:0;display:flex;align-items:center;justify-content:center"><svg width="28" height="28" viewBox="0 0 24 24" fill="none"><rect width="24" height="24" rx="6" fill="#6366F1"/><path d="M17 12a3 3 0 1 1-2.8-2h-4.4a3 3 0 1 1 0-2h4.4A3 3 0 0 1 17 12zm-8.8 4a3 3 0 1 1 2.8 2h3.6a1 1 0 1 1 0 2H11a3 3 0 0 1-2.8-4z" fill="#FFFFFF"/></svg></div>
|
||
<div>
|
||
<strong style="font-size:15px" data-i18n="notif_custom_title">Webhook personnalisé (HTTP)</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="notif_custom_desc">Requête HTTP vers n’importe
|
||
quelle API, domotique ou service cloud</div>
|
||
</div>
|
||
</div>
|
||
<label class="check" style="margin:0;font-weight:700"><input id="notifWebhookEnabled" type="checkbox"
|
||
onchange="toggleNotifFields('webhook')"> <span data-i18n="notif_custom_enable">Activer
|
||
Webhook</span></label>
|
||
</div>
|
||
|
||
<div id="notifWebhookFields" style="display:none;padding-top:10px;border-top:1px solid var(--line)">
|
||
<div style="display:grid;grid-template-columns:3fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="notifWebhookUrl" style="margin-top:4px"
|
||
data-i18n="notif_custom_url_label">URL de destination</label>
|
||
<input id="notifWebhookUrl" type="text" placeholder="https://api.mon-domaine.fr/webhook">
|
||
</div>
|
||
<div>
|
||
<label class="label" for="notifWebhookMethod" style="margin-top:4px"
|
||
data-i18n="notif_custom_method_label">Méthode</label>
|
||
<select id="notifWebhookMethod"
|
||
style="display:block;width:100%;margin:7px 0 16px;padding:12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-size:15px">
|
||
<option value="POST" selected>POST</option>
|
||
<option value="PUT">PUT</option>
|
||
<option value="GET">GET</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
|
||
<label class="label" for="notifWebhookHeaders" data-i18n="notif_custom_headers_label">En-têtes
|
||
personnalisés (optionnel, JSON ou Clé: Valeur)</label>
|
||
<textarea id="notifWebhookHeaders" rows="2"
|
||
placeholder='{"Authorization": "Bearer secret123", "X-Custom": "val"}'
|
||
style="width:100%;margin:4px 0 16px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
|
||
<div style="display:flex;justify-content:flex-end;margin-top:8px">
|
||
<button type="button" class="secondary" onclick="testNotificationChannel('webhook')"
|
||
style="font-size:13px;padding:6px 14px" data-i18n="notif_custom_test_btn">Tester le Webhook</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Sous-onglet 2 : Événements déclencheurs et Personnalisation des alertes -->
|
||
<div id="panelNotifAlerts" style="display:none">
|
||
<!-- Événements déclencheurs -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin:16px 0">
|
||
<h3 style="margin:0 0 8px;font-size:15px;display:flex;align-items:center;gap:8px">
|
||
<span>⚡</span> <span data-i18n="notif_events_title">Événements déclencheurs d’alerte</span>
|
||
</h3>
|
||
<p class="muted" style="font-size:12px;margin:0 0 14px" data-i18n="notif_events_desc">Sélectionnez les
|
||
événements qui déclencheront l’envoi d’une notification :</p>
|
||
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:10px">
|
||
<label class="check" style="margin:0"><input id="notifEvtNewDevice" type="checkbox" checked><span
|
||
data-i18n="notif_evt_new_device">📱 Nouvel appareil Wi‑Fi (première connexion)</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtDeviceConnected" type="checkbox"> <span
|
||
data-i18n="notif_evt_device_connected">📶 Reconnexion d’un appareil Wi‑Fi connu</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtDeviceDisconnected" type="checkbox"> <span
|
||
data-i18n="notif_evt_device_disconnected">📴 Déconnexion d’un appareil Wi‑Fi</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtAdminLogin" type="checkbox" checked><span
|
||
data-i18n="notif_evt_admin_login">🔒 Connexion au compte administrateur</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtAdminLoginFailed" type="checkbox" checked><span
|
||
data-i18n="notif_evt_admin_login_failed">⚠️ Échec de connexion administrateur</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtDeviceBlocked" type="checkbox" checked><span
|
||
data-i18n="notif_evt_device_blocked">🛑 Équipement bloqué ou débloqué</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtSettingsChanged" type="checkbox" checked><span
|
||
data-i18n="notif_evt_settings_changed">⚙️ Modification réglages Wi‑Fi / AP</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtVpnClientConnected" type="checkbox" checked><span
|
||
data-i18n="notif_evt_vpn_client_connected">🛡️ Client routé via VPN</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtVpnClientDisconnected" type="checkbox"
|
||
checked><span data-i18n="notif_evt_vpn_client_disconnected">🌐 Déconnexion / Retrait client du
|
||
VPN</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtVpnProfileConnected" type="checkbox"
|
||
checked><span data-i18n="notif_evt_vpn_profile_connected">🛡️ Profil VPN connecté (tunnel
|
||
actif)</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtVpnProfileDisconnected" type="checkbox"
|
||
checked><span data-i18n="notif_evt_vpn_profile_disconnected">⚠️ Déconnexion profil VPN (tunnel
|
||
coupé)</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtQuotaExceeded" type="checkbox" checked><span
|
||
data-i18n="notif_evt_quota_exceeded">⚖️ Quota de données dépassé par un appareil</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtBackupSuccess" type="checkbox" checked><span
|
||
data-i18n="notif_evt_backup_success">💾 Sauvegarde créée avec succès</span></label>
|
||
<label class="check" style="margin:0"><input id="notifEvtBackupRemoteSuccess" type="checkbox" checked><span
|
||
data-i18n="notif_evt_backup_remote_success">☁️ Sauvegarde envoyée sur l’hôte distant (si configuré)</span></label>
|
||
<label class="check"
|
||
style="margin:0;grid-column:1/-1;background:var(--panel);padding:10px 14px;border-radius:10px;border:1px solid var(--line);font-weight:600">
|
||
<input id="notifEvtStatsReport" type="checkbox" onchange="toggleStatsReportSchedule(this.checked)">
|
||
<span data-i18n="stats_cron_tab_title">📊 Rapport planifié des statistiques et métriques (Tâche
|
||
Cron)</span>
|
||
</label>
|
||
</div>
|
||
|
||
<!-- Configuration Tâche Cron pour le rapport statistiques & métriques (Jour, Heure, Minute) -->
|
||
<div id="statsReportScheduleBox"
|
||
style="display:none;background:var(--panel);border:1px solid var(--blue);border-radius:12px;padding:16px;margin-top:14px">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<span style="font-size:22px">⏰</span>
|
||
<div>
|
||
<strong style="font-size:15px;color:var(--text)" data-i18n="stats_cron_title">Planification Cron du
|
||
rapport statistique</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="stats_cron_desc">Configurez la périodicité
|
||
d'envoi automatique (Jour, Heure, Minute)</div>
|
||
</div>
|
||
</div>
|
||
<span id="statsReportCronHuman" class="pill pill-blue pill-no-dot"
|
||
style="font-size:12px;padding:3px 10px" data-i18n="stats_report_cron_default">📅 Tous les jours à
|
||
08:00</span>
|
||
</div>
|
||
|
||
<div
|
||
style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;align-items:end">
|
||
<div>
|
||
<label class="label" for="statsReportDay" style="font-size:12px;margin-top:0"
|
||
data-i18n="stats_cron_day_label">📅 Jour d’exécution</label>
|
||
<select id="statsReportDay" onchange="updateStatsReportCronFromFields()"
|
||
style="width:100%;margin:4px 0 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-size:13px">
|
||
<option value="*" data-i18n="stats_cron_day_all">Tous les jours (*)</option>
|
||
<option value="1-5" data-i18n="stats_cron_day_workdays">Jours ouvrés (Lundi à Vendredi)</option>
|
||
<option value="6,7" data-i18n="stats_cron_day_weekend">Week-end (Samedi & Dimanche)</option>
|
||
<option value="1" data-i18n="stats_cron_day_mon">Chaque Lundi</option>
|
||
<option value="2" data-i18n="stats_cron_day_tue">Chaque Mardi</option>
|
||
<option value="3" data-i18n="stats_cron_day_wed">Chaque Mercredi</option>
|
||
<option value="4" data-i18n="stats_cron_day_thu">Chaque Jeudi</option>
|
||
<option value="5" data-i18n="stats_cron_day_fri">Chaque Vendredi</option>
|
||
<option value="6" data-i18n="stats_cron_day_sat">Chaque Samedi</option>
|
||
<option value="0" data-i18n="stats_cron_day_sun">Chaque Dimanche</option>
|
||
</select>
|
||
</div>
|
||
|
||
<div>
|
||
<label class="label" for="statsReportHour" style="font-size:12px;margin-top:0"
|
||
data-i18n="stats_report_hour_label">🕐 Heure (00 - 23)</label>
|
||
<select id="statsReportHour" onchange="updateStatsReportCronFromFields()"
|
||
style="width:100%;margin:4px 0 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-size:13px">
|
||
</select>
|
||
</div>
|
||
|
||
<div>
|
||
<label class="label" for="statsReportMinute" style="font-size:12px;margin-top:0"
|
||
data-i18n="stats_report_minute_label">⏱️ Minute (00 - 59)</label>
|
||
<select id="statsReportMinute" onchange="updateStatsReportCronFromFields()"
|
||
style="width:100%;margin:4px 0 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-size:13px">
|
||
</select>
|
||
</div>
|
||
|
||
<div>
|
||
<label class="label" for="statsReportTopRange" style="font-size:12px;margin-top:0"
|
||
data-i18n="stats_cron_top_range_label">📊 Période Top clients</label>
|
||
<select id="statsReportTopRange"
|
||
style="width:100%;margin:4px 0 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-size:13px">
|
||
<option value="day" data-i18n="stats_cron_range_day">Aujourd’hui (Par jour)</option>
|
||
<option value="week" data-i18n="stats_cron_range_week">Cette semaine (Par semaine)</option>
|
||
<option value="month" data-i18n="stats_cron_range_month">Ce mois-ci (Par mois)</option>
|
||
<option value="year" data-i18n="stats_cron_range_year">Cette année (Par année)</option>
|
||
<option value="all_ranges" data-i18n="stats_cron_range_all">Toutes les périodes (Jour, Sem., Mois,
|
||
An)</option>
|
||
</select>
|
||
</div>
|
||
|
||
<div>
|
||
<label class="label" for="statsReportCronExpr" style="font-size:12px;margin-top:0" data-i18n="stats_cron_expr_label">⚙️ Expression Cron
|
||
standard</label>
|
||
<input id="statsReportCronExpr" type="text" value="0 8 * * *"
|
||
oninput="updateStatsReportFieldsFromCron()"
|
||
style="width:100%;margin:4px 0 0;padding:9px 12px;font-family:ui-monospace,monospace;font-size:13px;border-radius:8px;background:var(--panel2);color:var(--text);border:1px solid var(--line)">
|
||
</div>
|
||
</div>
|
||
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-top:14px;padding-top:12px;border-top:1px solid var(--line)">
|
||
<div class="muted" style="font-size:12px" data-i18n-html="stats_cron_format_hint">
|
||
Format Cron : <code>minute heure jour mois jour_semaine</code> (ex : <code>0 8 * * *</code> = 08h00
|
||
chaque jour, <code>30 18 * * 5</code> = 18h30 chaque vendredi).
|
||
</div>
|
||
<div style="display:flex;align-items:center;gap:8px">
|
||
<button type="button" class="secondary" onclick="triggerManualStatsReport()"
|
||
style="font-size:12px;padding:6px 14px;display:inline-flex;align-items:center;gap:6px">
|
||
<span>📤</span> <span data-i18n="stats_cron_send_now_btn">Envoyer le rapport maintenant
|
||
(Test)</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
<div id="statsReportTriggerMsg" style="margin-top:8px;font-size:12px;display:none"></div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Personnalisation des modèles de messages -->
|
||
<div
|
||
style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin:16px 0">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-bottom:12px">
|
||
<div>
|
||
<h3 style="margin:0;font-size:15px;display:flex;align-items:center;gap:8px">
|
||
<span>✏️</span> <span data-i18n="notif_tmpl_main_title">Personnalisation des messages d’alerte</span>
|
||
</h3>
|
||
<p class="muted" style="font-size:12px;margin:4px 0 0" data-i18n="notif_tmpl_main_desc">Modifiez le
|
||
titre et le texte des alertes. Cliquez sur une variable pour l’insérer dans le message.</p>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:12px;padding:6px 12px;display:inline-flex;align-items:center;gap:6px"
|
||
onclick="toggleAllNotifTemplates()">
|
||
<span id="notifTmplToggleIcon">▾</span> <span id="notifTmplToggleText"
|
||
data-i18n="notif_tmpl_toggle_expand">Tout déplier</span>
|
||
</button>
|
||
</div>
|
||
|
||
<div id="notifTemplatesAccordion" style="display:flex;flex-direction:column;gap:10px">
|
||
<!-- 1. Nouvel appareil -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="new_device">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_new_device">📱 Nouvel appareil Wi‑Fi (première connexion)</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_new_device"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_new_device" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_new_device"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_new_device" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('new_device','{name}')">{name}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('new_device','{ip}')">{ip}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('new_device','{mac}')">{mac}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('new_device','{date}')">{date}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('new_device')" data-i18n="notif_tmpl_reset_btn">↺ Rétablir par
|
||
défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 2. Reconnexion appareil -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="device_connected">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_device_connected">📶 Reconnexion d’un appareil Wi‑Fi connu</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_device_connected"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_device_connected" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_device_connected"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_device_connected" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_connected','{name}')">{name}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_connected','{ip}')">{ip}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_connected','{mac}')">{mac}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_connected','{date}')">{date}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('device_connected')" data-i18n="notif_tmpl_reset_btn">↺
|
||
Rétablir par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 3. Déconnexion appareil -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="device_disconnected">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_device_disconnected">📴 Déconnexion d’un appareil Wi‑Fi</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_device_disconnected"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_device_disconnected" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_device_disconnected"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_device_disconnected" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_disconnected','{name}')">{name}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_disconnected','{ip}')">{ip}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_disconnected','{mac}')">{mac}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_disconnected','{date}')">{date}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('device_disconnected')" data-i18n="notif_tmpl_reset_btn">↺
|
||
Rétablir par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 4. Connexion admin -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="admin_login">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_admin_login">🔒 Connexion au compte administrateur</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_admin_login"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_admin_login" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_admin_login"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_admin_login" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('admin_login','{user}')">{user}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('admin_login','{device}')">{device}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('admin_login','{ip}')">{ip}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('admin_login','{browser}')">{browser}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('admin_login','{date}')">{date}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('admin_login')" data-i18n="notif_tmpl_reset_btn">↺ Rétablir par
|
||
défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 5. Échec connexion admin -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="admin_login_failed">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_admin_login_failed">⚠️ Échec de connexion administrateur</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_admin_login_failed"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_admin_login_failed" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_admin_login_failed"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_admin_login_failed" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('admin_login_failed','{user}')">{user}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('admin_login_failed','{ip}')">{ip}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('admin_login_failed','{browser}')">{browser}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('admin_login_failed','{date}')">{date}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('admin_login_failed')" data-i18n="notif_tmpl_reset_btn">↺
|
||
Rétablir par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 6. Équipement bloqué / débloqué -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="device_blocked">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_device_blocked">🛑 Équipement bloqué ou débloqué</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_device_blocked"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_device_blocked" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_device_blocked"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_device_blocked" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_blocked','{name}')">{name}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_blocked','{ip}')">{ip}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_blocked','{mac}')">{mac}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_blocked','{action}')">{action}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('device_blocked','{date}')">{date}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('device_blocked')" data-i18n="notif_tmpl_reset_btn">↺ Rétablir
|
||
par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 7. Paramètres Wi-Fi modifiés -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="settings_changed">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_settings_changed">⚙️ Modification réglages Wi‑Fi / AP</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_settings_changed"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_settings_changed" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_settings_changed"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_settings_changed" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('settings_changed','{ssid}')">{ssid}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('settings_changed','{mode}')">{mode}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('settings_changed','{security}')">{security}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('settings_changed','{date}')">{date}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('settings_changed')" data-i18n="notif_tmpl_reset_btn">↺
|
||
Rétablir par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 8. Connexion / Assignation client au VPN -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="vpn_client_connected">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span>🛡️ Connexion / Assignation client au VPN</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_vpn_client_connected"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_vpn_client_connected" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_vpn_client_connected"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_vpn_client_connected" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_client_connected','{name}')">{name}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_client_connected','{ip}')">{ip}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_client_connected','{mac}')">{mac}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_client_connected','{vpn}')">{vpn}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_client_connected','{date}')">{date}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('vpn_client_connected')" data-i18n="notif_tmpl_reset_btn">↺
|
||
Rétablir par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 9. Déconnexion / Retrait client du VPN -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="vpn_client_disconnected">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_vpn_client_disconnected">🌐 Déconnexion / Retrait client du VPN</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_vpn_client_disconnected"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_vpn_client_disconnected" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_vpn_client_disconnected"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_vpn_client_disconnected" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_client_disconnected','{name}')">{name}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_client_disconnected','{ip}')">{ip}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_client_disconnected','{mac}')">{mac}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_client_disconnected','{vpn}')">{vpn}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_client_disconnected','{date}')">{date}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('vpn_client_disconnected')" data-i18n="notif_tmpl_reset_btn">↺
|
||
Rétablir par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 10. Connexion profil VPN (tunnel actif) -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="vpn_profile_connected">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_vpn_profile_connected">🛡️ Connexion profil VPN (tunnel actif)</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_vpn_profile_connected"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_vpn_profile_connected" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_vpn_profile_connected"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_vpn_profile_connected" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_profile_connected','{name}')">{name}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_profile_connected','{type}')">{type}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_profile_connected','{iface}')">{iface}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_profile_connected','{date}')">{date}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('vpn_profile_connected')" data-i18n="notif_tmpl_reset_btn">↺
|
||
Rétablir par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 11. Déconnexion profil VPN (tunnel coupé) -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="vpn_profile_disconnected">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_vpn_profile_disconnected">⚠️ Déconnexion profil VPN (tunnel coupé)</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_vpn_profile_disconnected"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_vpn_profile_disconnected" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_vpn_profile_disconnected"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_vpn_profile_disconnected" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_profile_disconnected','{name}')">{name}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_profile_disconnected','{type}')">{type}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_profile_disconnected','{iface}')">{iface}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('vpn_profile_disconnected','{date}')">{date}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('vpn_profile_disconnected')" data-i18n="notif_tmpl_reset_btn">↺
|
||
Rétablir par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 12. Rapport statistiques & métriques (Tâche Cron) -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="stats_report">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_stats_report">📊 Rapport statistiques & métriques (Tâche Cron)</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_stats_report"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_stats_report" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_stats_report"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_stats_report" rows="5"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:13px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{clients_count}')">{clients_count}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{today_unique}')">{today_unique}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{today_total}')">{today_total}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{traffic_down}')">{traffic_down}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{traffic_up}')">{traffic_up}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{active_vpns}')">{active_vpns}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{vpn_routed_clients}')">{vpn_routed_clients}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{gateway_status}')">{gateway_status}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{top_clients}')">{top_clients}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{top_clients_day}')">{top_clients_day}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{top_clients_week}')">{top_clients_week}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{top_clients_month}')">{top_clients_month}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{top_clients_year}')">{top_clients_year}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{top_clients_all}')">{top_clients_all}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{top_clients_compact}')">{top_clients_compact}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{week_unique}')">{week_unique}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{month_unique}')">{month_unique}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{ssid}')">{ssid}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{date}')">{date}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('stats_report','{heure}')">{heure}</button>
|
||
</div>
|
||
<div style="display:flex;align-items:center;gap:8px">
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="triggerManualStatsReport()">📤 Envoyer maintenant</button>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('stats_report')" data-i18n="notif_tmpl_reset_btn">↺ Rétablir
|
||
par défaut</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 13. Quota de données dépassé -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="quota_exceeded">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_quota_exceeded">⚖️ Quota de données dépassé par un appareil</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_quota_exceeded"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_quota_exceeded" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_quota_exceeded"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_quota_exceeded" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('quota_exceeded','{name}')">{name}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('quota_exceeded','{ip}')">{ip}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('quota_exceeded','{mac}')">{mac}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('quota_exceeded','{quota}')">{quota}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('quota_exceeded','{consumption}')">{consumption}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('quota_exceeded','{action}')">{action}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('quota_exceeded','{date}')">{date}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('quota_exceeded','{heure}')">{heure}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('quota_exceeded')" data-i18n="notif_tmpl_reset_btn">↺ Rétablir
|
||
par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 14. Sauvegarde créée avec succès -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="backup_success">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_backup_success">💾 Sauvegarde créée avec succès</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_backup_success"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_backup_success" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_backup_success"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_backup_success" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('backup_success','{filename}')">{filename}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('backup_success','{size}')">{size}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('backup_success','{trigger}')">{trigger}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('backup_success','{date}')">{date}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('backup_success','{heure}')">{heure}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('backup_success')" data-i18n="notif_tmpl_reset_btn">↺ Rétablir
|
||
par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<!-- 15. Sauvegarde envoyée sur l'hôte distant -->
|
||
<details class="notif-tmpl-item card" style="padding:10px 14px;background:var(--panel);border-radius:10px"
|
||
data-event="backup_remote_success">
|
||
<summary
|
||
style="font-weight:700;font-size:14px;cursor:pointer;user-select:none;display:flex;align-items:center;justify-content:space-between">
|
||
<span data-i18n="notif_event_backup_remote_success">☁️ Sauvegarde téléversée sur le stockage distant</span>
|
||
<span class="muted" style="font-size:12px" data-i18n="notif_tmpl_customize">Personnaliser ▾</span>
|
||
</summary>
|
||
<div style="padding-top:12px">
|
||
<label class="label" data-i18n="notif_tmpl_title_label" for="notifTmplTitle_backup_remote_success"
|
||
style="font-size:12px">Titre / Sujet</label>
|
||
<input id="notifTmplTitle_backup_remote_success" type="text"
|
||
style="margin:4px 0 10px;padding:9px 12px;font-size:14px">
|
||
<label class="label" data-i18n="notif_tmpl_msg_label" for="notifTmplMsg_backup_remote_success"
|
||
style="font-size:12px">Contenu du message</label>
|
||
<textarea id="notifTmplMsg_backup_remote_success" rows="2"
|
||
style="width:100%;margin:4px 0 8px;padding:9px 12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-family:inherit;font-size:14px;resize:vertical"></textarea>
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:4px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="notif_tmpl_vars_label">Variables :</span>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('backup_remote_success','{filename}')">{filename}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('backup_remote_success','{size}')">{size}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('backup_remote_success','{provider}')">{provider}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('backup_remote_success','{host}')">{host}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('backup_remote_success','{date}')">{date}</button>
|
||
<button type="button" class="secondary"
|
||
style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer"
|
||
onclick="insertNotifVariable('backup_remote_success','{heure}')">{heure}</button>
|
||
</div>
|
||
<button type="button" class="secondary"
|
||
style="font-size:11px;padding:3px 10px;border-radius:6px;cursor:pointer"
|
||
onclick="resetNotificationTemplate('backup_remote_success')" data-i18n="notif_tmpl_reset_btn">↺ Rétablir
|
||
par défaut</button>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Actions Enregistrer & Test global -->
|
||
<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-top:20px">
|
||
<button id="saveNotifBtn" type="button" onclick="saveNotificationSettings()"
|
||
data-i18n="notif_save_btn">Enregistrer les notifications</button>
|
||
<button type="button" class="secondary" onclick="testNotificationChannel('all')" data-i18n="notif_test_all">🧪
|
||
Tester tous les canaux actifs</button>
|
||
<span id="notifMessage" class="muted"></span>
|
||
</div>
|
||
<div id="notifTestDetails" style="margin-top:12px"></div>
|
||
</div>
|
||
|
||
<!-- 4. Personnalisation -->
|
||
<div id="panelSettingsCustom" class="settings-panel card" style="display:none">
|
||
<h2 data-i18n="custom_title">Personnalisation</h2>
|
||
<p class="muted" data-i18n="custom_subtitle">Personnalisez le titre du service, la langue et l’apparence
|
||
visuelle.</p>
|
||
|
||
<label class="label" data-i18n="custom_lang">Langue de l’interface</label>
|
||
|
||
<!-- Cartes visuelles avec logos des drapeaux en SVG -->
|
||
<div id="langCardsContainer"
|
||
style="display:grid;grid-template-columns:repeat(auto-fit, minmax(180px, 1fr));gap:10px;margin:8px 0 20px">
|
||
<div class="lang-card" id="langCard_fr" onclick="setLanguage('fr', false)"
|
||
style="display:flex;align-items:center;gap:12px;padding:10px 14px;border-radius:10px;border:1px solid var(--blue);background:rgba(56,189,248,0.1);cursor:pointer;transition:all .18s ease;user-select:none">
|
||
<span class="lang-card-flag" style="display:inline-flex;align-items:center;line-height:1">
|
||
<svg viewBox="0 0 30 20" width="32" height="22"
|
||
style="display:inline-block;vertical-align:middle;border-radius:3px;box-shadow:0 1px 3px rgba(0,0,0,0.4);border:1px solid rgba(255,255,255,0.2);flex-shrink:0">
|
||
<rect width="10" height="20" fill="#002654" />
|
||
<rect x="10" width="10" height="20" fill="#ffffff" />
|
||
<rect x="20" width="10" height="20" fill="#ce1126" />
|
||
</svg>
|
||
</span>
|
||
<div style="flex:1;min-width:0">
|
||
<div style="font-weight:700;font-size:13px;line-height:1.2" data-i18n="lang_card_fr_name">Français</div>
|
||
<div class="muted" style="font-size:11px" data-i18n="lang_card_fr_country">France</div>
|
||
</div>
|
||
<span class="lang-card-check" id="langCheck_fr"
|
||
style="font-size:15px;font-weight:700;color:var(--blue)">✓</span>
|
||
</div>
|
||
|
||
<div class="lang-card" id="langCard_en-us" onclick="setLanguage('en-us', false)"
|
||
style="display:flex;align-items:center;gap:12px;padding:10px 14px;border-radius:10px;border:1px solid var(--line);background:var(--panel2);cursor:pointer;transition:all .18s ease;user-select:none">
|
||
<span class="lang-card-flag" style="display:inline-flex;align-items:center;line-height:1">
|
||
<svg viewBox="0 0 190 100" width="32" height="22"
|
||
style="display:inline-block;vertical-align:middle;border-radius:3px;box-shadow:0 1px 3px rgba(0,0,0,0.4);border:1px solid rgba(255,255,255,0.2);flex-shrink:0">
|
||
<rect width="190" height="100" fill="#b22234" />
|
||
<path d="M0,7.7h190M0,23h190M0,38.5h190M0,53.8h190M0,69.2h190M0,84.6h190" stroke="#ffffff"
|
||
stroke-width="7.7" />
|
||
<rect width="76" height="53.8" fill="#3c3b6e" />
|
||
<g fill="#ffffff">
|
||
<circle cx="15" cy="11" r="3.5" />
|
||
<circle cx="38" cy="11" r="3.5" />
|
||
<circle cx="61" cy="11" r="3.5" />
|
||
<circle cx="26.5" cy="22" r="3.5" />
|
||
<circle cx="49.5" cy="22" r="3.5" />
|
||
<circle cx="15" cy="33" r="3.5" />
|
||
<circle cx="38" cy="33" r="3.5" />
|
||
<circle cx="61" cy="33" r="3.5" />
|
||
<circle cx="26.5" cy="44" r="3.5" />
|
||
<circle cx="49.5" cy="44" r="3.5" />
|
||
</g>
|
||
</svg>
|
||
</span>
|
||
<div style="flex:1;min-width:0">
|
||
<div style="font-weight:700;font-size:13px;line-height:1.2" data-i18n="lang_card_enus_name">English (US)</div>
|
||
<div class="muted" style="font-size:11px" data-i18n="lang_card_enus_country">United States</div>
|
||
</div>
|
||
<span class="lang-card-check" id="langCheck_en-us"
|
||
style="font-size:15px;font-weight:700;color:var(--blue);display:none">✓</span>
|
||
</div>
|
||
|
||
<div class="lang-card" id="langCard_en-gb" onclick="setLanguage('en-gb', false)"
|
||
style="display:flex;align-items:center;gap:12px;padding:10px 14px;border-radius:10px;border:1px solid var(--line);background:var(--panel2);cursor:pointer;transition:all .18s ease;user-select:none">
|
||
<span class="lang-card-flag" style="display:inline-flex;align-items:center;line-height:1">
|
||
<svg viewBox="0 0 60 30" width="32" height="22"
|
||
style="display:inline-block;vertical-align:middle;border-radius:3px;box-shadow:0 1px 3px rgba(0,0,0,0.4);border:1px solid rgba(255,255,255,0.2);flex-shrink:0">
|
||
<path d="M0 0v30h60V0z" fill="#012169" />
|
||
<path d="M0 0l60 30M60 0L0 30" stroke="#fff" stroke-width="6" />
|
||
<path d="M0 0l60 30M60 0L0 30" stroke="#C8102E" stroke-width="4" />
|
||
<path d="M30 0v30M0 15h60" stroke="#fff" stroke-width="10" />
|
||
<path d="M30 0v30M0 15h60" stroke="#C8102E" stroke-width="6" />
|
||
</svg>
|
||
</span>
|
||
<div style="flex:1;min-width:0">
|
||
<div style="font-weight:700;font-size:13px;line-height:1.2" data-i18n="lang_card_engb_name">English (UK)</div>
|
||
<div class="muted" style="font-size:11px" data-i18n="lang_card_engb_country">United Kingdom</div>
|
||
</div>
|
||
<span class="lang-card-check" id="langCheck_en-gb"
|
||
style="font-size:15px;font-weight:700;color:var(--blue);display:none">✓</span>
|
||
</div>
|
||
</div>
|
||
|
||
<label class="label" for="appNameInput" data-i18n="custom_app_name">Nom complet de l’application</label>
|
||
<input id="appNameInput" type="text" maxlength="64" placeholder="Administration de l’AP Wi‑Fi" data-i18n-placeholder="placeholder_app_name">
|
||
<label class="label" for="appShortNameInput" data-i18n="custom_short_name">Nom court (onglet navigateur)</label>
|
||
<input id="appShortNameInput" type="text" maxlength="32" placeholder="AP Manageur" data-i18n-placeholder="placeholder_app_short_name">
|
||
<label class="label" for="themeSelect" data-i18n="custom_theme">Thème</label>
|
||
<select id="themeSelect"
|
||
style="display:block;width:100%;margin:7px 0 16px;padding:12px;border-radius:9px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-size:15px">
|
||
<option value="dark" data-i18n="custom_theme_dark">Sombre</option>
|
||
<option value="light" data-i18n="custom_theme_light">Clair</option>
|
||
<option value="winxp" data-i18n="custom_theme_winxp">Windows XP (Luna)</option>
|
||
<option value="futuristic" data-i18n="custom_theme_futuristic">Futuriste (Cyber / Néon)</option>
|
||
<option value="macos" data-i18n="custom_theme_macos">macOS (Adaptatif Clair / Sombre)</option>
|
||
<option value="hacker" data-i18n="custom_theme_hacker">Hacker (Terminal Matrix)</option>
|
||
<option value="auto" data-i18n="custom_theme_auto">Automatique (selon l’appareil)</option>
|
||
</select>
|
||
<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
|
||
<button id="saveCustomization" type="button" data-i18n="custom_save_btn">Enregistrer la
|
||
personnalisation</button>
|
||
<span id="themeMessage" class="muted"></span>
|
||
</div>
|
||
<p class="muted" style="font-size:12px;margin-top:12px" data-i18n="custom_db_notice">Enregistré dans la base de
|
||
données : le nom, la langue et le thème se retrouvent sur tous vos appareils.</p>
|
||
|
||
<div style="margin-top:28px;padding-top:22px;border-top:1px solid var(--line)">
|
||
<div
|
||
style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div>
|
||
<h3 style="margin:0 0 4px;font-size:16px" data-i18n="custom_dev_types_title">🏷️ Types et catégories
|
||
d’appareils</h3>
|
||
<p class="muted" style="margin:0;font-size:12px" data-i18n="custom_dev_types_desc">Gérez les catégories
|
||
d’appareils (nom, logo/emoji, identifiant) et personnalisez leur affichage.</p>
|
||
</div>
|
||
<div style="display:flex;gap:8px;flex-wrap:wrap">
|
||
<button type="button" class="secondary" onclick="resetDefaultDeviceTypes()"
|
||
style="display:inline-flex;align-items:center;gap:6px;font-size:13px;padding:6px 12px"
|
||
data-i18n="btn_reset_defaults">↺ Réinitialiser par défaut</button>
|
||
<button type="button" onclick="openDeviceTypeEditorModal()"
|
||
style="display:inline-flex;align-items:center;gap:6px;font-size:13px;padding:6px 14px"
|
||
data-i18n="btn_add_category">➕ Ajouter une catégorie</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="deviceTypesListContainer" class="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th style="width:70px;text-align:center" data-i18n="th_logo">LOGO</th>
|
||
<th data-i18n="th_category_name">NOM DE LA CATÉGORIE</th>
|
||
<th data-i18n="th_category_id">IDENTIFIANT</th>
|
||
<th data-i18n="th_category_desc">DESCRIPTION</th>
|
||
<th style="text-align:right;width:170px" data-i18n="th_action">ACTION</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="deviceTypesTableBody">
|
||
<tr>
|
||
<td colspan="5" class="empty" data-i18n="loading_categories">Chargement des catégories…</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div id="deviceTypesMsg" class="muted" style="font-size:12px;margin-top:8px"></div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 5. Zone dangereuse -->
|
||
<!-- 7. Sauvegardes & Automatisation Cron -->
|
||
<div id="panelSettingsBackup" class="settings-panel card" style="display:none;max-width:960px">
|
||
<div style="display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:10px">
|
||
<div>
|
||
<h2 style="margin:0 0 4px" data-i18n="backup_tab_title">Sauvegardes & Restauration</h2>
|
||
<p class="muted" style="margin:0" data-i18n="backup_tab_subtitle">Créez, planifiez (Cron), exportez, restaurez ou supprimez vos sauvegardes stockées dans le volume Docker.</p>
|
||
</div>
|
||
<span id="backupDirBadge" class="pill pill-blue pill-no-dot" style="font-size:12px;font-family:monospace">📁 /backups</span>
|
||
</div>
|
||
|
||
<!-- Actions rapides : Créer / Exporter / Importer -->
|
||
<div style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:16px;margin-top:16px">
|
||
<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
|
||
<button id="btnCreateServerBackup" type="button" onclick="createServerBackupNow()"
|
||
style="display:inline-flex;align-items:center;gap:8px" data-i18n="backup_create_now_btn">
|
||
💾 Créer une sauvegarde maintenant
|
||
</button>
|
||
<button id="btnExportBackup" type="button" class="secondary" onclick="exportBackup()"
|
||
style="display:inline-flex;align-items:center;gap:8px" data-i18n="danger_export_btn">
|
||
📥 Exporter la configuration & base de données
|
||
</button>
|
||
<button id="btnTriggerImport" type="button" class="secondary" onclick="triggerImportBackup()"
|
||
style="display:inline-flex;align-items:center;gap:8px;border-color:var(--blue);color:var(--blue)"
|
||
data-i18n="danger_import_btn">
|
||
📤 Importer une sauvegarde…
|
||
</button>
|
||
<input type="file" id="backupFileInput" accept=".zip,application/zip,.json,application/json,.sqlite3,.db"
|
||
style="display:none" onchange="handleBackupFileSelected(event)">
|
||
</div>
|
||
<div id="backupActionMsg"
|
||
style="margin-top:12px;font-size:12px;display:none;padding:8px 12px;border-radius:6px"></div>
|
||
</div>
|
||
|
||
<!-- Automatisation Cron -->
|
||
<div style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:18px;margin-top:16px">
|
||
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div>
|
||
<strong style="font-size:15px;display:flex;align-items:center;gap:8px" data-i18n="backup_cron_title">
|
||
⏱️ Automatisation des sauvegardes (Cron)
|
||
</strong>
|
||
<p class="muted" style="margin:4px 0 0;font-size:13px" data-i18n="backup_cron_desc">
|
||
Planifiez des sauvegardes automatiques enregistrées dans le dossier configuré via Docker Compose.
|
||
</p>
|
||
</div>
|
||
<label style="display:inline-flex;align-items:center;gap:10px;cursor:pointer;font-weight:600;user-select:none">
|
||
<span data-i18n="backup_cron_enable">Activer la planification</span>
|
||
<input type="checkbox" id="backupCronEnabled" onchange="onBackupCronToggle(true)">
|
||
</label>
|
||
</div>
|
||
|
||
<div id="backupScheduleMsg" style="margin-top:10px;font-size:12px;display:none;padding:8px 12px;border-radius:6px"></div>
|
||
|
||
<div id="backupCronBody" style="display:none">
|
||
<div id="backupCronFields" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin-top:12px">
|
||
<div>
|
||
<label class="label" for="backupCronDay" data-i18n="backup_cron_day_label">Fréquence / Jour</label>
|
||
<select id="backupCronDay" onchange="syncBackupCronFromSelects()">
|
||
<option value="*" data-i18n="stats_cron_day_all_short">Tous les jours</option>
|
||
<option value="1-5" data-i18n="stats_cron_day_workdays_short">Jours ouvrés (Lun-Ven)</option>
|
||
<option value="6,7" data-i18n="stats_cron_day_weekend_short">Week-end (Sam-Dim)</option>
|
||
<option value="1" data-i18n="stats_cron_day_mon">Chaque Lundi</option>
|
||
<option value="2" data-i18n="stats_cron_day_tue">Chaque Mardi</option>
|
||
<option value="3" data-i18n="stats_cron_day_wed">Chaque Mercredi</option>
|
||
<option value="4" data-i18n="stats_cron_day_thu">Chaque Jeudi</option>
|
||
<option value="5" data-i18n="stats_cron_day_fri">Chaque Vendredi</option>
|
||
<option value="6" data-i18n="stats_cron_day_sat">Chaque Samedi</option>
|
||
<option value="0" data-i18n="stats_cron_day_sun">Chaque Dimanche</option>
|
||
</select>
|
||
</div>
|
||
<div>
|
||
<label class="label" for="backupCronHour" data-i18n="backup_cron_hour_label">Heure</label>
|
||
<select id="backupCronHour" onchange="syncBackupCronFromSelects()"></select>
|
||
</div>
|
||
<div>
|
||
<label class="label" for="backupCronMinute" data-i18n="backup_cron_min_label">Minute</label>
|
||
<select id="backupCronMinute" onchange="syncBackupCronFromSelects()"></select>
|
||
</div>
|
||
<div>
|
||
<label class="label" for="backupCronRetention" data-i18n="backup_cron_retention_label">Rétention (0 = illimité)</label>
|
||
<input id="backupCronRetention" type="number" min="0" max="365" value="7">
|
||
</div>
|
||
</div>
|
||
|
||
<div style="display:grid;grid-template-columns:1fr auto;gap:10px;align-items:end;margin-top:12px">
|
||
<div>
|
||
<label class="label" for="backupCronExpr" data-i18n="backup_cron_expr_label">Expression Cron (minute heure jour mois jour_semaine)</label>
|
||
<input id="backupCronExpr" type="text" value="0 3 * * *" placeholder="0 3 * * *" style="font-family:monospace;margin-bottom:0" oninput="updateBackupCronSummary()">
|
||
</div>
|
||
<button id="btnSaveBackupSchedule" type="button" onclick="saveBackupSchedule()" data-i18n="backup_cron_save_btn">
|
||
💾 Enregistrer
|
||
</button>
|
||
</div>
|
||
|
||
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-top:10px">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span id="backupCronHuman" class="pill pill-blue pill-no-dot" style="font-size:12px">📅 Tous les jours à 03:00</span>
|
||
<button type="button" class="secondary" style="padding:3px 9px;font-size:11px" onclick="applyBackupCronPreset('0 3 * * *','*',3,0)" data-i18n="backup_preset_daily">Chaque nuit 03:00</button>
|
||
<button type="button" class="secondary" style="padding:3px 9px;font-size:11px" onclick="applyBackupCronPreset('0 4 * * 0','0',4,0)" data-i18n="backup_preset_weekly">Dimanche 04:00</button>
|
||
<button type="button" class="secondary" style="padding:3px 9px;font-size:11px" onclick="applyBackupCronPreset('0 */6 * * *','*','*',0)" data-i18n="backup_preset_6h">Toutes les 6h</button>
|
||
</div>
|
||
<span id="backupCronLastRun" class="muted" style="font-size:12px"></span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Stockage distant (FTP, SFTP, Google Drive, Dropbox, WebDAV, S3, Webhook) -->
|
||
<div style="background:var(--panel2);border:1px solid var(--line);border-radius:12px;padding:18px;margin-top:16px">
|
||
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div>
|
||
<strong style="font-size:15px;display:flex;align-items:center;gap:8px" data-i18n="backup_remote_title">
|
||
☁️ Stockage distant (FTP, SFTP, Cloud)
|
||
</strong>
|
||
<p class="muted" style="margin:4px 0 0;font-size:13px" data-i18n="backup_remote_desc">
|
||
Exportez automatiquement ou manuellement vos sauvegardes vers un serveur FTP/SFTP, Google Drive, Dropbox, WebDAV (Nextcloud/NAS), S3/MinIO ou Webhook.
|
||
</p>
|
||
</div>
|
||
<label style="display:inline-flex;align-items:center;gap:10px;cursor:pointer;font-weight:600;user-select:none">
|
||
<span data-i18n="backup_remote_enable">Activer le stockage distant</span>
|
||
<input type="checkbox" id="backupRemoteEnabled" onchange="onBackupRemoteToggle()">
|
||
</label>
|
||
</div>
|
||
|
||
<div id="backupRemoteMsg" style="margin-top:10px;font-size:12px;display:none;padding:8px 12px;border-radius:6px"></div>
|
||
|
||
<div id="backupRemoteBody" style="display:none">
|
||
<div style="margin-bottom:14px">
|
||
<label class="label" for="backupRemoteProvider" data-i18n="backup_remote_provider_label" style="margin-bottom:8px">Destination distante</label>
|
||
|
||
<!-- Grille de sélection rapide du fournisseur avec les vrais logos officiels -->
|
||
<div id="backupProviderSelector" style="display:flex;flex-wrap:wrap;gap:8px;margin-bottom:10px">
|
||
<button type="button" class="backup-prov-btn secondary" data-provider="ftp" onclick="selectBackupRemoteProvider('ftp')" style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer">
|
||
📡 <span>FTP / FTPS</span>
|
||
</button>
|
||
<button type="button" class="backup-prov-btn secondary" data-provider="sftp" onclick="selectBackupRemoteProvider('sftp')" style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer">
|
||
🔐 <span>SFTP (SSH)</span>
|
||
</button>
|
||
<button type="button" class="backup-prov-btn secondary" data-provider="gdrive" onclick="selectBackupRemoteProvider('gdrive')" style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer">
|
||
<img src="/images/gdrive.svg" width="16" height="15" alt="Google Drive" style="object-fit:contain;vertical-align:middle">
|
||
<span>Google Drive</span>
|
||
</button>
|
||
<button type="button" class="backup-prov-btn secondary" data-provider="dropbox" onclick="selectBackupRemoteProvider('dropbox')" style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer">
|
||
<img src="/images/dropbox.svg" width="16" height="16" alt="Dropbox" style="object-fit:contain;vertical-align:middle">
|
||
<span>Dropbox</span>
|
||
</button>
|
||
<button type="button" class="backup-prov-btn secondary" data-provider="webdav" onclick="selectBackupRemoteProvider('webdav')" style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer">
|
||
🌐 <span>WebDAV</span>
|
||
</button>
|
||
<button type="button" class="backup-prov-btn secondary" data-provider="s3" onclick="selectBackupRemoteProvider('s3')" style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer">
|
||
🪣 <span>S3 / MinIO</span>
|
||
</button>
|
||
<button type="button" class="backup-prov-btn secondary" data-provider="webhook" onclick="selectBackupRemoteProvider('webhook')" style="padding:6px 12px;font-size:12px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;cursor:pointer">
|
||
🔗 <span>Webhook</span>
|
||
</button>
|
||
</div>
|
||
|
||
<input type="hidden" id="backupRemoteProvider" value="ftp">
|
||
<div style="margin-top:6px;margin-bottom:6px">
|
||
<label style="display:inline-flex;align-items:center;gap:10px;cursor:pointer;font-size:13px;padding:4px 0;user-select:none">
|
||
<input type="checkbox" id="backupRemoteAutoUpload" checked>
|
||
<span data-i18n="backup_remote_autoupload">Transférer automatiquement à chaque sauvegarde (Cron & manuelle)</span>
|
||
</label>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- FTP / FTPS -->
|
||
<div id="remoteFields_ftp" class="remote-provider-fields" style="background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||
<div style="display:grid;grid-template-columns:2fr 1fr 1fr;gap:10px">
|
||
<div><label class="label" for="remoteFtpHost" data-i18n="backup_remote_host">Hôte / IP</label><input id="remoteFtpHost" type="text" placeholder="ftp.exemple.fr ou 192.168.1.10"></div>
|
||
<div><label class="label" for="remoteFtpPort" data-i18n="backup_remote_port">Port</label><input id="remoteFtpPort" type="number" value="21" min="1" max="65535"></div>
|
||
<div>
|
||
<label class="label" for="remoteFtpTls" data-i18n="backup_remote_security">Sécurité</label>
|
||
<select id="remoteFtpTls">
|
||
<option value="none">FTP Standard</option>
|
||
<option value="explicit">FTPS (TLS explicite)</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px">
|
||
<div><label class="label" for="remoteFtpUser" data-i18n="backup_remote_user">Utilisateur</label><input id="remoteFtpUser" type="text" placeholder="backup_user"></div>
|
||
<div>
|
||
<label class="label" for="remoteFtpPass" data-i18n="backup_remote_pass">Mot de passe</label>
|
||
<div style="display:flex;gap:6px;align-items:center">
|
||
<input id="remoteFtpPass" type="password" placeholder="••••••••" style="margin:0;flex:1">
|
||
<button id="toggleRemoteFtpPass" class="secondary" type="button" aria-label="Afficher le mot de passe" title="Afficher le mot de passe" data-i18n-title="btn_show_pwd" data-i18n-aria-label="btn_show_pwd" style="padding:7px 10px;height:38px;display:inline-flex;align-items:center;justify-content:center"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg></button>
|
||
</div>
|
||
</div>
|
||
<div><label class="label" for="remoteFtpPath" data-i18n="backup_remote_path">Dossier distant</label><input id="remoteFtpPath" type="text" value="backups/" placeholder="backups/ ou vide pour la racine"></div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- SFTP (SSH) -->
|
||
<div id="remoteFields_sftp" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||
<div style="display:grid;grid-template-columns:2fr 1fr 1.5fr;gap:10px">
|
||
<div><label class="label" for="remoteSftpHost" data-i18n="backup_remote_host">Hôte / IP</label><input id="remoteSftpHost" type="text" placeholder="nas.exemple.fr ou 192.168.1.10"></div>
|
||
<div><label class="label" for="remoteSftpPort" data-i18n="backup_remote_port">Port</label><input id="remoteSftpPort" type="number" value="22" min="1" max="65535"></div>
|
||
<div><label class="label" for="remoteSftpPath" data-i18n="backup_remote_path">Dossier distant</label><input id="remoteSftpPath" type="text" value="backups/" placeholder="backups/ ou vide pour la racine"></div>
|
||
</div>
|
||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
|
||
<div><label class="label" for="remoteSftpUser" data-i18n="backup_remote_user">Utilisateur</label><input id="remoteSftpUser" type="text" placeholder="root ou backup"></div>
|
||
<div>
|
||
<label class="label" for="remoteSftpPass" data-i18n="backup_remote_pass">Mot de passe (si pas de clé SSH)</label>
|
||
<div style="display:flex;gap:6px;align-items:center">
|
||
<input id="remoteSftpPass" type="password" placeholder="••••••••" style="margin:0;flex:1">
|
||
<button id="toggleRemoteSftpPass" class="secondary" type="button" aria-label="Afficher le mot de passe" title="Afficher le mot de passe" data-i18n-title="btn_show_pwd" data-i18n-aria-label="btn_show_pwd" style="padding:7px 10px;height:38px;display:inline-flex;align-items:center;justify-content:center"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg></button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div>
|
||
<label class="label" for="remoteSftpKey" data-i18n="backup_remote_ssh_key">Clé privée SSH (facultative — format PEM / OpenSSH)</label>
|
||
<textarea id="remoteSftpKey" rows="3" placeholder="-----BEGIN OPENSSH PRIVATE KEY-----" style="width:100%;margin-top:6px;padding:10px 12px;background:var(--panel2);border:1px solid var(--line);border-radius:8px;color:var(--text);font-family:monospace;font-size:12px;resize:vertical;box-sizing:border-box"></textarea>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Google Drive -->
|
||
<div id="remoteFields_gdrive" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||
<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;padding-bottom:10px;border-bottom:1px solid var(--line)">
|
||
<img src="/images/gdrive.svg" width="32" height="29" alt="Google Drive" style="object-fit:contain;flex-shrink:0">
|
||
<div>
|
||
<strong style="font-size:14px;display:flex;align-items:center;gap:8px">Google Drive (API v3)</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="backup_remote_gdrive_hint">Téléversement direct via l’API officielle Google Drive (REST v3 multipart).</div>
|
||
</div>
|
||
</div>
|
||
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="remoteGdriveToken" data-i18n="backup_remote_token">Jeton d’accès OAuth2 (Access Token)</label>
|
||
<div style="display:flex;gap:6px;align-items:center">
|
||
<input id="remoteGdriveToken" type="password" placeholder="ya29.a0..." style="margin:0;flex:1">
|
||
<button id="toggleRemoteGdriveToken" class="secondary" type="button" aria-label="Afficher le jeton" title="Afficher le jeton" data-i18n-title="settings_show_token" data-i18n-aria-label="settings_show_token" style="padding:7px 10px;height:38px;display:inline-flex;align-items:center;justify-content:center"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg></button>
|
||
</div>
|
||
</div>
|
||
<div><label class="label" for="remoteGdriveFolder" data-i18n="backup_remote_gdrive_folder">ID du dossier Drive (facultatif)</label><input id="remoteGdriveFolder" type="text" placeholder="1AbCdEfGhIjKlMnOp..."></div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Dropbox -->
|
||
<div id="remoteFields_dropbox" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||
<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;padding-bottom:10px;border-bottom:1px solid var(--line)">
|
||
<img src="/images/dropbox.svg" width="32" height="32" alt="Dropbox" style="object-fit:contain;flex-shrink:0">
|
||
<div>
|
||
<strong style="font-size:14px;display:flex;align-items:center;gap:8px">Dropbox (API v2)</strong>
|
||
<div class="muted" style="font-size:12px" data-i18n="backup_remote_dropbox_hint">Téléversement direct via l’API officielle Dropbox Content v2.</div>
|
||
</div>
|
||
</div>
|
||
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="remoteDropboxToken" data-i18n="backup_remote_token">Jeton d’accès (Access Token Dropbox)</label>
|
||
<div style="display:flex;gap:6px;align-items:center">
|
||
<input id="remoteDropboxToken" type="password" placeholder="sl.B..." style="margin:0;flex:1">
|
||
<button id="toggleRemoteDropboxToken" class="secondary" type="button" aria-label="Afficher le jeton" title="Afficher le jeton" data-i18n-title="settings_show_token" data-i18n-aria-label="settings_show_token" style="padding:7px 10px;height:38px;display:inline-flex;align-items:center;justify-content:center"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg></button>
|
||
</div>
|
||
</div>
|
||
<div><label class="label" for="remoteDropboxPath" data-i18n="backup_remote_path">Dossier distant</label><input id="remoteDropboxPath" type="text" value="/AP-Manageur-Backups/" placeholder="/AP-Manageur-Backups/"></div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- WebDAV -->
|
||
<div id="remoteFields_webdav" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||
<div><label class="label" for="remoteWebdavUrl" data-i18n="backup_remote_webdav_url">URL WebDAV (Nextcloud / ownCloud / Synology / kDrive)</label><input id="remoteWebdavUrl" type="url" placeholder="https://cloud.exemple.fr/remote.php/dav/files/user/Backups/"></div>
|
||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
|
||
<div><label class="label" for="remoteWebdavUser" data-i18n="backup_remote_user">Utilisateur</label><input id="remoteWebdavUser" type="text" placeholder="utilisateur"></div>
|
||
<div>
|
||
<label class="label" for="remoteWebdavPass" data-i18n="backup_remote_pass">Mot de passe / Mot de passe d’application</label>
|
||
<div style="display:flex;gap:6px;align-items:center">
|
||
<input id="remoteWebdavPass" type="password" placeholder="••••••••" style="margin:0;flex:1">
|
||
<button id="toggleRemoteWebdavPass" class="secondary" type="button" aria-label="Afficher le mot de passe" title="Afficher le mot de passe" data-i18n-title="btn_show_pwd" data-i18n-aria-label="btn_show_pwd" style="padding:7px 10px;height:38px;display:inline-flex;align-items:center;justify-content:center"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg></button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- S3 / MinIO -->
|
||
<div id="remoteFields_s3" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||
<div style="display:grid;grid-template-columns:2fr 1fr 1fr;gap:10px">
|
||
<div><label class="label" for="remoteS3Endpoint" data-i18n="backup_remote_s3_endpoint">Endpoint S3 / MinIO</label><input id="remoteS3Endpoint" type="url" value="https://s3.amazonaws.com" placeholder="https://s3.fr-par.scw.cloud"></div>
|
||
<div><label class="label" for="remoteS3Region" data-i18n="backup_remote_s3_region">Région</label><input id="remoteS3Region" type="text" value="us-east-1" placeholder="fr-par"></div>
|
||
<div><label class="label" for="remoteS3Bucket" data-i18n="backup_remote_s3_bucket">Bucket</label><input id="remoteS3Bucket" type="text" placeholder="ap-backups"></div>
|
||
</div>
|
||
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px">
|
||
<div><label class="label" for="remoteS3AccessKey">Access Key</label><input id="remoteS3AccessKey" type="text" placeholder="AKIA..."></div>
|
||
<div>
|
||
<label class="label" for="remoteS3SecretKey">Secret Key</label>
|
||
<div style="display:flex;gap:6px;align-items:center">
|
||
<input id="remoteS3SecretKey" type="password" placeholder="••••••••" style="margin:0;flex:1">
|
||
<button id="toggleRemoteS3SecretKey" class="secondary" type="button" aria-label="Afficher la clé" title="Afficher la clé" data-i18n-title="settings_show_key" data-i18n-aria-label="settings_show_key" style="padding:7px 10px;height:38px;display:inline-flex;align-items:center;justify-content:center"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg></button>
|
||
</div>
|
||
</div>
|
||
<div><label class="label" for="remoteS3Path" data-i18n="backup_remote_path">Préfixe / Dossier</label><input id="remoteS3Path" type="text" value="backups/" placeholder="backups/"></div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Webhook HTTP -->
|
||
<div id="remoteFields_webhook" class="remote-provider-fields" style="display:none;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px">
|
||
<div style="display:grid;grid-template-columns:2.5fr 1fr 1fr;gap:10px">
|
||
<div><label class="label" for="remoteWebhookUrl">URL Webhook</label><input id="remoteWebhookUrl" type="url" placeholder="https://serveur.exemple.fr/upload"></div>
|
||
<div>
|
||
<label class="label" for="remoteWebhookMethod">Méthode</label>
|
||
<select id="remoteWebhookMethod"><option value="POST">POST (multipart)</option><option value="PUT">PUT (binaire)</option></select>
|
||
</div>
|
||
<div><label class="label" for="remoteWebhookField">Champ fichier</label><input id="remoteWebhookField" type="text" value="backup" placeholder="backup"></div>
|
||
</div>
|
||
<div>
|
||
<label class="label" for="remoteWebhookHeaders" data-i18n="backup_remote_headers">En-têtes HTTP personnalisés (1 par ligne : Clé: Valeur)</label>
|
||
<textarea id="remoteWebhookHeaders" rows="2" placeholder="Authorization: Bearer mon_token" style="width:100%;margin-top:6px;padding:10px 12px;background:var(--panel2);border:1px solid var(--line);border-radius:8px;color:var(--text);font-family:monospace;font-size:12px;resize:vertical;box-sizing:border-box"></textarea>
|
||
</div>
|
||
</div>
|
||
|
||
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-top:12px">
|
||
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
|
||
<button id="btnTestBackupRemote" type="button" class="secondary" onclick="testBackupRemote()" data-i18n="backup_remote_test_btn">
|
||
🧪 Tester la connexion
|
||
</button>
|
||
<button id="btnSaveBackupRemote" type="button" onclick="saveBackupRemoteConfig()" data-i18n="backup_remote_save_btn">
|
||
💾 Enregistrer le stockage distant
|
||
</button>
|
||
</div>
|
||
<span id="backupRemoteLastStatus" class="muted" style="font-size:12px"></span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Liste des sauvegardes enregistrées -->
|
||
<div style="margin-top:20px">
|
||
<div class="topline" style="flex-wrap:wrap;gap:10px;margin-bottom:12px">
|
||
<div>
|
||
<h3 style="margin:0;font-size:16px" data-i18n="backup_list_title">📂 Sauvegardes enregistrées</h3>
|
||
<div id="backupsListSummary" class="muted" style="font-size:12px;margin-top:3px">—</div>
|
||
</div>
|
||
<div style="display:inline-flex;align-items:center;gap:8px;flex-wrap:wrap">
|
||
<button id="btnRefreshBackups" type="button" class="secondary" onclick="refreshBackupsTab()" style="display:inline-flex;align-items:center;gap:6px" data-i18n="btn_refresh">
|
||
🔄 Actualiser
|
||
</button>
|
||
<button id="btnOpenRemoteDriveModal" type="button" class="secondary" onclick="openRemoteDriveModal()" style="display:inline-flex;align-items:center;gap:6px" title="Voir, télécharger et gérer les sauvegardes présentes sur le stockage distant">
|
||
☁️ <span data-i18n="btn_view_remote_drive">Voir les fichiers du drive</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
<div class="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th data-i18n="backup_th_file">FICHIER</th>
|
||
<th data-i18n="backup_th_type">TYPE</th>
|
||
<th data-i18n="backup_th_date">DATE</th>
|
||
<th data-i18n="backup_th_size">TAILLE</th>
|
||
<th data-i18n="backup_th_actions" style="text-align:right">ACTIONS</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="backupsTableBody">
|
||
<tr><td colspan="5" class="empty" data-i18n="loading">Chargement…</td></tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 8. Zone dangereuse -->
|
||
<div id="panelSettingsDanger" class="settings-panel card" style="display:none">
|
||
<h2 data-i18n="danger_title">Zone dangereuse & Maintenance</h2>
|
||
<p class="muted" data-i18n="danger_subtitle">Actions critiques de maintenance et réinitialisation complète du système.</p>
|
||
|
||
<div class="notice" style="margin-top:16px;border-color:rgba(239,68,68,0.3)">
|
||
<strong style="color:var(--red);display:flex;align-items:center;gap:6px" data-i18n="danger_delete_title">⚠️
|
||
Suppression irréversible</strong>
|
||
<p style="margin:8px 0 14px" data-i18n="danger_delete_desc">Supprime l’historique des logs, les appareils
|
||
bloqués et la configuration réseau enregistrée.</p>
|
||
<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
|
||
<button id="clearAllData" type="button" style="background:var(--red);color:white"
|
||
data-i18n="danger_delete_all_btn">Supprimer toutes les données</button>
|
||
<span id="clearDataMessage" class="muted"></span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
</section>
|
||
|
||
<section id="logsView" class="view">
|
||
<div class="card">
|
||
<div class="topline" style="flex-wrap:wrap;gap:12px;margin-bottom:12px">
|
||
<div>
|
||
<h2 style="margin:0" data-i18n="logs_title">Journaux de connexion</h2>
|
||
</div>
|
||
<div style="display:flex;gap:8px"><button id="clearLogs" type="button"
|
||
style="background:var(--red);color:white" data-i18n="btn_delete">Supprimer</button></div>
|
||
</div>
|
||
<div class="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th data-i18n="th_date">DATE</th>
|
||
<th data-i18n="th_event">ÉVÉNEMENT</th>
|
||
<th data-i18n="th_device">APPAREIL</th>
|
||
<th data-i18n="th_ip">IP</th>
|
||
<th data-i18n="th_mac">MAC</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="logs"></tbody>
|
||
</table>
|
||
</div>
|
||
<div id="logsPagination" class="pagination"></div>
|
||
</div>
|
||
</section>
|
||
|
||
<section id="blockedView" class="view">
|
||
<div class="card">
|
||
<div class="topline" style="flex-wrap:wrap;gap:12px;margin-bottom:12px">
|
||
<div>
|
||
<h2 style="margin:0" data-i18n="blocked_title">Appareils bloqués</h2>
|
||
</div>
|
||
</div>
|
||
<p class="muted" data-i18n="blocked_desc">Ces appareils sont enregistrés dans la liste de blocage et peuvent
|
||
être autorisés à nouveau.</p>
|
||
<div class="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th data-i18n="th_device">APPAREIL</th>
|
||
<th data-i18n="th_mac">ADRESSE MAC</th>
|
||
<th data-i18n="th_blocked_on">BLOQUÉ LE</th>
|
||
<th data-i18n="th_action">ACTION</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="blockedClients"></tbody>
|
||
</table>
|
||
</div>
|
||
<div id="blockedPagination" class="pagination"></div>
|
||
</div>
|
||
</section>
|
||
|
||
<div id="packetModal" class="modal-overlay">
|
||
<div class="modal-card">
|
||
<div class="modal-header">
|
||
<h2 style="margin:0;font-size:17px"><span data-i18n="packet_details_title">Détails du paquet #</span><span
|
||
id="modalPacketNum"></span> (<span id="modalPacketProto"></span>)</h2>
|
||
<button id="closePacketModal" class="secondary" type="button"
|
||
style="padding:4px 10px;font-size:16px">✕</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;font-size:12px">
|
||
<div style="background:var(--panel2);padding:8px 10px;border-radius:6px;border:1px solid var(--line)">
|
||
<strong data-i18n="packet_source">Source :</strong> <span id="modalPacketSrc"></span></div>
|
||
<div style="background:var(--panel2);padding:8px 10px;border-radius:6px;border:1px solid var(--line)">
|
||
<strong data-i18n="packet_destination">Destination :</strong> <span id="modalPacketDst"></span></div>
|
||
<div style="background:var(--panel2);padding:8px 10px;border-radius:6px;border:1px solid var(--line)">
|
||
<strong data-i18n="packet_time">Heure :</strong> <span id="modalPacketTime"></span></div>
|
||
<div style="background:var(--panel2);padding:8px 10px;border-radius:6px;border:1px solid var(--line)">
|
||
<strong data-i18n="packet_size">Taille :</strong> <span id="modalPacketLen"></span></div>
|
||
<div style="background:var(--panel2);padding:8px 10px;border-radius:6px;border:1px solid var(--line)"
|
||
id="modalPacketDomainBox"><strong data-i18n="packet_domain">Domaine / Hôte :</strong> <span
|
||
id="modalPacketDomain" style="color:var(--blue);font-weight:700">—</span></div>
|
||
</div>
|
||
<div>
|
||
<strong style="font-size:13px;display:block;margin-bottom:6px" data-i18n="packet_layers">Décodage des
|
||
couches réseau :</strong>
|
||
<pre id="modalPacketDetails"
|
||
style="background:var(--bg);border:1px solid var(--line);border-radius:8px;padding:12px;font-size:12px;overflow:auto;max-height:160px;white-space:pre-wrap;font-family:monospace;margin:0"></pre>
|
||
</div>
|
||
<div>
|
||
<strong style="font-size:13px;display:block;margin-bottom:6px" data-i18n="packet_hexdump">Dump Hexadécimal
|
||
& ASCII (Wireshark) :</strong>
|
||
<pre id="modalPacketHex"
|
||
style="background:var(--bg);border:1px solid var(--line);border-radius:8px;padding:12px;font-size:11px;overflow:auto;max-height:220px;font-family:monospace;color:var(--text);margin:0"></pre>
|
||
</div>
|
||
</div>
|
||
<div class="modal-footer">
|
||
<button type="button" class="secondary" id="closePacketModalBtn" data-i18n="btn_close">Fermer</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="topoDetailModal" class="modal-overlay">
|
||
<div class="modal-card">
|
||
<div class="modal-header">
|
||
<h3 id="topoModalTitle" style="margin:0;display:flex;align-items:center;gap:8px" data-i18n="topo_modal_title">
|
||
Inspection de l'équipement</h3>
|
||
<button type="button" class="secondary" onclick="closeTopologyModal()"
|
||
style="padding:4px 10px;font-size:16px;border-radius:6px">✕</button>
|
||
</div>
|
||
<div id="topoModalBody" class="modal-body">
|
||
<!-- Rempli dynamiquement -->
|
||
</div>
|
||
<div class="modal-footer" id="topoModalFooter">
|
||
<button type="button" class="secondary" onclick="closeTopologyModal()">Fermer</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Modal Profil VPN (Ajout / Modification) -->
|
||
<div id="modalVpnProfile" class="modal-overlay">
|
||
<div class="modal-card" style="max-width:620px">
|
||
<div class="modal-header">
|
||
<h3 id="vpnModalTitle" style="margin:0;display:flex;align-items:center;gap:8px" data-i18n="vpn_modal_title">
|
||
Ajouter un profil VPN</h3>
|
||
<button type="button" class="secondary" onclick="closeVpnModal()"
|
||
style="padding:4px 10px;font-size:16px;border-radius:6px">✕</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<input type="hidden" id="vpnProfileId" value="">
|
||
<div>
|
||
<label class="label" for="vpnProfileName" style="margin-top:0" data-i18n="vpn_profile_name_label">Nom du
|
||
profil</label>
|
||
<input id="vpnProfileName" type="text" placeholder="Ex : ProtonVPN Paris, Mullvad WG, NordVPN..."
|
||
data-i18n-placeholder="placeholder_vpn_name" maxlength="50" style="margin-top:4px">
|
||
</div>
|
||
|
||
<div>
|
||
<label class="label" style="margin-top:6px" data-i18n="vpn_profile_type_label">Type de protocole</label>
|
||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:4px">
|
||
<label
|
||
style="display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--panel2);border:1px solid var(--line);border-radius:8px;cursor:pointer">
|
||
<input type="radio" name="vpnProfileType" id="vpnTypeWg" value="wireguard" checked
|
||
onchange="onVpnTypeChange()" style="width:auto;margin:0">
|
||
<svg class="vpn-type-logo vpn-logo-wg" viewBox="0 0 24 24" width="22" height="22"
|
||
style="vertical-align:middle;flex-shrink:0">
|
||
<path fill="#88171A"
|
||
d="M23.98 11.645S24.533 0 11.735 0C.418 0 .064 11.17.064 11.17S-1.6 24 11.997 24C25.04 24 23.98 11.645 23.98 11.645z" />
|
||
<path fill="#ffffff"
|
||
d="M8.155 7.576c2.4-1.47 5.469-.571 6.618 1.638.218.419.246 1.063.108 1.503-.477 1.516-1.601 2.366-3.145 2.728.455-.39.817-.832.933-1.442a2.112 2.112 0 0 0-.364-1.677 2.14 2.14 0 0 0-2.465-.75c-.95.36-1.47 1.228-1.377 2.294.087.99.839 1.632 2.245 1.876-.21.111-.372.193-.53.281a5.113 5.113 0 0 0-1.644 1.43c-.143.192-.24.208-.458.075-2.827-1.729-3.009-6.067.078-7.956zM6.04 18.258c-.455.116-.895.286-1.359.438.227-1.532 2.021-2.943 3.539-2.782a3.91 3.91 0 0 0-.74 2.072c-.504.093-.98.155-1.44.272zM15.703 3.3c.448.017.898.01 1.347.02a2.324 2.324 0 0 1 .334.047 3.249 3.249 0 0 1-.34.434c-.16.15-.341.296-.573.069-.055-.055-.187-.042-.283-.044-.447-.005-.894-.02-1.34-.003a8.323 8.323 0 0 0-1.154.118c-.072.013-.178.25-.146.338.078.207.191.435.359.567.619.49 1.277.928 1.9 1.413.604.472 1.167.99 1.51 1.7.446.928.46 1.9.267 2.877-.322 1.63-1.147 2.98-2.483 3.962-.538.395-1.205.62-1.821.903-.543.25-1.1.465-1.644.712-.98.446-1.53 1.51-1.369 2.615.149 1.015 1.04 1.862 2.059 2.037 1.223.21 2.486-.586 2.785-1.83.336-1.397-.423-2.646-1.845-3.024l-.256-.066c.38-.17.708-.291 1.012-.458q.793-.437 1.558-.925c.15-.096.231-.096.36.014.977.846 1.56 1.898 1.724 3.187.27 2.135-.74 4.096-2.646 5.101-2.948 1.555-6.557-.215-7.208-3.484-.558-2.8 1.418-5.34 3.797-5.83 1.023-.211 1.958-.637 2.685-1.425.47-.508.697-.944.775-1.141a3.165 3.165 0 0 0 .217-1.158 2.71 2.71 0 0 0-.237-.992c-.248-.566-1.2-1.466-1.435-1.656l-2.24-1.754c-.079-.065-.168-.06-.36-.047-.23.016-.815.048-1.067-.018.204-.155.76-.38 1-.56-.726-.49-1.554-.314-2.315-.46.176-.328 1.046-.831 1.541-.888a7.323 7.323 0 0 0-.135-.822c-.03-.111-.154-.22-.263-.283-.262-.154-.541-.281-.843-.434a1.755 1.755 0 0 1 .906-.28 3.385 3.385 0 0 1 .908.088c.54.123.97.042 1.399-.324-.338-.136-.676-.26-1.003-.407a9.843 9.843 0 0 1-.942-.493c.85.118 1.671.437 2.54.32l.022-.118-2.018-.47c1.203-.11 2.323-.128 3.384.388.299.146.61.266.897.432.14.08.233.24.348.365.09.098.164.23.276.29.424.225.89.234 1.366.223l.01-.16c.479.15 1.017.702 1.017 1.105-.776 0-1.55-.003-2.325.004-.083 0-.165.061-.247.094.078.046.155.128.235.131z M14.703 2.153a.118.118 0 0 0-.016.19.179.179 0 0 0 .246.065c.075-.038.148-.078.238-.125-.072-.062-.13-.114-.19-.163-.106-.087-.193-.032-.278.033z" />
|
||
</svg>
|
||
<div><strong>WireGuard</strong>
|
||
<div class="muted" style="font-size:11px" data-i18n="modal_vpn_wireguard_sub">Fichier .conf moderne
|
||
& rapide</div>
|
||
</div>
|
||
</label>
|
||
<label
|
||
style="display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--panel2);border:1px solid var(--line);border-radius:8px;cursor:pointer">
|
||
<input type="radio" name="vpnProfileType" id="vpnTypeOvpn" value="openvpn" onchange="onVpnTypeChange()"
|
||
style="width:auto;margin:0">
|
||
<svg class="vpn-type-logo vpn-logo-ovpn" viewBox="0 0 24 24" width="22" height="22"
|
||
style="vertical-align:middle;flex-shrink:0" fill="#EA580C">
|
||
<path
|
||
d="M12 .357C5.385.357 0 5.69 0 12.254c0 4.36 2.358 8.153 5.896 10.204l.77-5.076a7.046 7.046 0 01-1.846-4.719c0-3.897 3.18-7.076 7.13-7.076 3.948 0 7.126 3.18 7.126 7.076 0 1.847-.717 3.488-1.846 4.77L18 22.51c3.59-2.05 6-5.899 6-10.258C24 5.69 18.615.357 12 .357zm-.05 8.157a3.786 3.786 0 00-3.796 3.795 3.738 3.738 0 002.461 3.54L9.13 23.643h5.64l-1.435-7.795c1.385-.564 2.41-1.898 2.41-3.54a3.786 3.786 0 00-3.795-3.794z" />
|
||
</svg>
|
||
<div><strong>OpenVPN</strong>
|
||
<div class="muted" style="font-size:11px" data-i18n="modal_vpn_openvpn_sub">Fichier .ovpn standard
|
||
</div>
|
||
</div>
|
||
</label>
|
||
</div>
|
||
</div>
|
||
|
||
<div>
|
||
<div style="display:flex;align-items:center;justify-content:space-between;margin-top:6px">
|
||
<label class="label" for="vpnProfileConfig" style="margin:0" data-i18n="modal_vpn_config_file">Fichier de
|
||
configuration</label>
|
||
<input type="file" id="vpnConfigFile" accept=".conf,.ovpn,.txt" style="display:none"
|
||
onchange="handleVpnConfigFile(event)">
|
||
<button type="button" class="secondary" onclick="$('vpnConfigFile').click()"
|
||
style="padding:4px 10px;font-size:12px;border-radius:6px" data-i18n="modal_vpn_import_btn">
|
||
📁 Importer un fichier (.conf / .ovpn)
|
||
</button>
|
||
</div>
|
||
<textarea id="vpnProfileConfig" rows="8"
|
||
placeholder="Collez ou importez le contenu du fichier WireGuard ou OpenVPN..."
|
||
data-i18n-placeholder="placeholder_vpn_config"
|
||
style="width:100%;margin-top:6px;padding:10px;background:var(--panel2);border:1px solid var(--line);border-radius:8px;color:var(--text);font-family:monospace;font-size:12px;resize:vertical"></textarea>
|
||
</div>
|
||
|
||
<div id="vpnOpenvpnAuthSection"
|
||
style="display:none;padding:12px;background:rgba(92,167,255,.05);border:1px solid var(--line);border-radius:8px">
|
||
<div style="font-weight:600;font-size:13px;margin-bottom:8px" data-i18n="modal_vpn_auth_optional">
|
||
Identifiants de connexion OpenVPN (optionnels)</div>
|
||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
|
||
<div>
|
||
<label class="label" for="vpnAuthUser" style="margin-top:0" data-i18n="vpn_auth_user_label">Nom
|
||
d’utilisateur</label>
|
||
<input id="vpnAuthUser" type="text" placeholder="Utilisateur VPN"
|
||
data-i18n-placeholder="placeholder_vpn_user" style="margin-top:4px">
|
||
</div>
|
||
<div>
|
||
<label class="label" for="vpnAuthPass" style="margin-top:0" data-i18n="vpn_auth_pass_label">Mot de
|
||
passe</label>
|
||
<input id="vpnAuthPass" type="password" placeholder="Laisser vide si inchangé"
|
||
data-i18n-placeholder="placeholder_vpn_pass" style="margin-top:4px">
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<label class="check" style="margin-top:4px">
|
||
<input id="vpnAutoConnect" type="checkbox" style="width:auto"> <span
|
||
data-i18n="modal_vpn_autoconnect">Connecter automatiquement ce profil au démarrage de l'AP</span>
|
||
</label>
|
||
<div id="vpnFormMsg" class="muted" style="font-size:12px"></div>
|
||
</div>
|
||
<div class="modal-footer" style="display:flex;justify-content:flex-end;gap:10px">
|
||
<button type="button" class="secondary" onclick="closeVpnModal()" data-i18n="btn_cancel">Annuler</button>
|
||
<button type="button" id="btnSaveVpnProfile" onclick="saveVpnProfile()"
|
||
data-i18n="modal_vpn_save_btn">Enregistrer le profil</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Modal Affichage Configuration VPN -->
|
||
<div id="modalVpnView" class="modal-overlay">
|
||
<div class="modal-card" style="max-width:680px">
|
||
<div class="modal-header">
|
||
<h3 id="vpnViewTitle" style="margin:0;display:flex;align-items:center;gap:8px"
|
||
data-i18n="modal_vpn_view_title">Configuration VPN</h3>
|
||
<button type="button" class="secondary" onclick="closeVpnViewModal()"
|
||
style="padding:4px 10px;font-size:16px;border-radius:6px">✕</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<pre id="vpnViewContent"
|
||
style="max-height:360px;overflow-y:auto;padding:12px;background:var(--bg);border:1px solid var(--line);border-radius:8px;font-family:monospace;font-size:12px;white-space:pre-wrap;word-break:break-all;margin:0"></pre>
|
||
</div>
|
||
<div class="modal-footer" style="display:flex;justify-content:space-between;align-items:center;width:100%">
|
||
<button type="button" class="secondary" onclick="copyVpnConfigText()" id="btnCopyVpnConfig"
|
||
data-i18n="modal_vpn_copy">📋 Copier</button>
|
||
<div style="display:flex;gap:8px">
|
||
<button type="button" class="secondary" onclick="downloadVpnConfigFile()" data-i18n="modal_vpn_download">💾
|
||
Télécharger</button>
|
||
<button type="button" onclick="closeVpnViewModal()" data-i18n="btn_close">Fermer</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Modal Quota et Limitation de Bande Passante -->
|
||
<div id="modalDeviceLimits" class="modal-overlay">
|
||
<div class="modal-card" style="max-width:540px">
|
||
<div class="modal-header">
|
||
<h3 style="margin:0;font-size:17px;display:flex;align-items:center;gap:8px">
|
||
<span>⚖️</span> <span data-i18n="modal_limits_title">Quota & Limitation de débit</span>
|
||
</h3>
|
||
<button type="button" class="secondary" style="padding:4px 10px;font-size:16px;border-radius:6px"
|
||
onclick="closeDeviceLimitsModal()">✕</button>
|
||
</div>
|
||
<div class="modal-body" style="display:flex;flex-direction:column;gap:14px">
|
||
<input type="hidden" id="limitsModalMac" value="">
|
||
|
||
<!-- Fiche Appareil -->
|
||
<div
|
||
style="background:var(--panel2);padding:12px 14px;border-radius:10px;border:1px solid var(--line);display:flex;align-items:center;gap:12px">
|
||
<div id="limitsDevAvatar" style="font-size:24px">📱</div>
|
||
<div style="flex:1;min-width:0">
|
||
<div id="limitsDevName"
|
||
style="font-weight:bold;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"
|
||
data-i18n="limits_dev_name_label">Nom de l'appareil</div>
|
||
<div class="muted" style="font-size:12px;margin-top:2px">
|
||
MAC : <code id="limitsDevMac" style="font-size:11px">00:00:00:00:00:00</code> • IP : <code
|
||
id="limitsDevIp" style="font-size:11px">—</code>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Section 1 : Quota de données -->
|
||
<div style="padding:14px;background:var(--panel2);border:1px solid var(--line);border-radius:10px">
|
||
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
|
||
<label class="check"
|
||
style="margin:0;font-weight:600;font-size:14px;display:flex;align-items:center;gap:8px;cursor:pointer">
|
||
<input type="checkbox" id="chkLimitsQuotaEnabled" onchange="toggleQuotaInputs()">
|
||
<span>📊 <span data-i18n="modal_quota_chk">Quota de données Internet</span></span>
|
||
</label>
|
||
<span id="quotaExceededBadge" class="pill"
|
||
style="display:none;background:rgba(239,68,68,0.15);color:var(--red);font-size:11px;font-weight:bold">🚫
|
||
<span data-i18n="modal_quota_exceeded">Quota dépassé</span></span>
|
||
</div>
|
||
|
||
<div id="quotaInputsContainer" style="display:none;flex-direction:column;gap:12px;margin-top:10px">
|
||
<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
|
||
<div style="flex:1;min-width:130px">
|
||
<label class="label" style="font-size:12px;margin-bottom:4px" data-i18n="modal_quota_max">Volume max
|
||
autorisé</label>
|
||
<div style="display:flex;gap:6px">
|
||
<input type="number" id="inputQuotaValue" min="0.1" step="0.5" value="10"
|
||
style="margin:0;padding:8px 10px;font-size:14px;flex:1" oninput="updateQuotaPreview()">
|
||
<select id="selectQuotaUnit" style="margin:0;padding:8px;font-size:14px;width:75px"
|
||
onchange="updateQuotaPreview()">
|
||
<option value="GB" selected>Go</option>
|
||
<option value="MB">Mo</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
<div style="flex:1;min-width:140px">
|
||
<label class="label" style="font-size:12px;margin-bottom:4px" data-i18n="modal_quota_period">Période
|
||
de calcul</label>
|
||
<select id="selectQuotaPeriod" style="margin:0;padding:8px 10px;font-size:14px;width:100%"
|
||
onchange="onQuotaPeriodChanged()">
|
||
<option value="total" selected data-i18n="modal_period_total">Total cumulé</option>
|
||
<option value="monthly" data-i18n="modal_period_month">Par mois (réinit. le 1er)</option>
|
||
<option value="daily" data-i18n="modal_period_day">Par jour (réinit. à minuit)</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Raccourcis de quotas -->
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="modal_presets">Préréglages :</span>
|
||
<button type="button" class="secondary" style="padding:2px 7px;font-size:11px;border-radius:6px"
|
||
onclick="setQuotaPreset(1, 'GB')" data-i18n="modal_quota_preset_1">1 Go</button>
|
||
<button type="button" class="secondary" style="padding:2px 7px;font-size:11px;border-radius:6px"
|
||
onclick="setQuotaPreset(5, 'GB')" data-i18n="modal_quota_preset_5">5 Go</button>
|
||
<button type="button" class="secondary" style="padding:2px 7px;font-size:11px;border-radius:6px"
|
||
onclick="setQuotaPreset(10, 'GB')" data-i18n="modal_quota_preset_10">10 Go</button>
|
||
<button type="button" class="secondary" style="padding:2px 7px;font-size:11px;border-radius:6px"
|
||
onclick="setQuotaPreset(20, 'GB')" data-i18n="modal_quota_preset_20">20 Go</button>
|
||
<button type="button" class="secondary" style="padding:2px 7px;font-size:11px;border-radius:6px"
|
||
onclick="setQuotaPreset(50, 'GB')" data-i18n="modal_quota_preset_50">50 Go</button>
|
||
</div>
|
||
|
||
<!-- Jauge de consommation actuelle -->
|
||
<div
|
||
style="background:var(--panel);padding:10px 12px;border-radius:8px;border:1px solid var(--line);margin-top:2px">
|
||
<div style="display:flex;justify-content:space-between;font-size:12px;margin-bottom:6px">
|
||
<span class="muted" data-i18n="modal_current_usage">Consommation actuelle :</span>
|
||
<strong id="quotaUsageLabel">0 o / 10 Go (0%)</strong>
|
||
</div>
|
||
<div style="background:var(--line);height:8px;border-radius:4px;overflow:hidden">
|
||
<div id="quotaUsageBar"
|
||
style="background:var(--blue);height:100%;width:0%;transition:width 0.3s ease"></div>
|
||
</div>
|
||
<div style="display:flex;justify-content:space-between;align-items:center;margin-top:8px">
|
||
<span class="muted" style="font-size:11px" id="quotaRemainingLabel">Reste : 10 Go</span>
|
||
<button type="button" class="secondary" style="padding:2px 8px;font-size:11px;color:var(--muted)"
|
||
onclick="resetDeviceTrafficUsage()" data-i18n="modal_reset_counter">🔄 Réinitialiser le
|
||
compteur</button>
|
||
</div>
|
||
</div>
|
||
|
||
<p class="muted" style="font-size:11px;margin:0;line-height:1.4" data-i18n="modal_quota_action_desc">
|
||
🔒 <strong>Action au dépassement :</strong> L'appareil ne pourra plus naviguer sur Internet (trafic WAN
|
||
coupé automatiquement).
|
||
</p>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Section 2 : Limitation de bande passante -->
|
||
<div style="padding:14px;background:var(--panel2);border:1px solid var(--line);border-radius:10px">
|
||
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
|
||
<label class="check"
|
||
style="margin:0;font-weight:600;font-size:14px;display:flex;align-items:center;gap:8px;cursor:pointer">
|
||
<input type="checkbox" id="chkLimitsBwEnabled" onchange="toggleBwInputs()">
|
||
<span>⚡ <span data-i18n="modal_bw_chk">Limitation de la bande passante (Débit)</span></span>
|
||
</label>
|
||
</div>
|
||
|
||
<div id="bwInputsContainer" style="display:none;flex-direction:column;gap:12px;margin-top:10px">
|
||
<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
|
||
<div style="flex:1;min-width:130px">
|
||
<label class="label" style="font-size:12px;margin-bottom:4px" data-i18n="modal_bw_down">Téléchargement
|
||
max (Download)</label>
|
||
<div style="display:flex;gap:6px">
|
||
<input type="number" id="inputRateDown" min="0" step="1" value="10"
|
||
style="margin:0;padding:8px 10px;font-size:14px;flex:1">
|
||
<select id="selectRateDownUnit" style="margin:0;padding:8px;font-size:14px;width:80px">
|
||
<option value="Mbps" selected>Mbps</option>
|
||
<option value="Kbps">Kbps</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
<div style="flex:1;min-width:130px">
|
||
<label class="label" style="font-size:12px;margin-bottom:4px" data-i18n="modal_bw_up">Téléversement
|
||
max (Upload)</label>
|
||
<div style="display:flex;gap:6px">
|
||
<input type="number" id="inputRateUp" min="0" step="1" value="5"
|
||
style="margin:0;padding:8px 10px;font-size:14px;flex:1">
|
||
<select id="selectRateUpUnit" style="margin:0;padding:8px;font-size:14px;width:80px">
|
||
<option value="Mbps" selected>Mbps</option>
|
||
<option value="Kbps">Kbps</option>
|
||
</select>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Préréglages rapides de débit -->
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted" style="font-size:11px" data-i18n="modal_bw_profiles">Profils rapides :</span>
|
||
<button type="button" class="secondary" style="padding:2px 7px;font-size:11px;border-radius:6px"
|
||
onclick="setBwPreset(2, 1)">2 / 1 Mbps</button>
|
||
<button type="button" class="secondary" style="padding:2px 7px;font-size:11px;border-radius:6px"
|
||
onclick="setBwPreset(5, 2)">5 / 2 Mbps</button>
|
||
<button type="button" class="secondary" style="padding:2px 7px;font-size:11px;border-radius:6px"
|
||
onclick="setBwPreset(10, 5)">10 / 5 Mbps</button>
|
||
<button type="button" class="secondary" style="padding:2px 7px;font-size:11px;border-radius:6px"
|
||
onclick="setBwPreset(25, 10)">25 / 10 Mbps</button>
|
||
<button type="button" class="secondary" style="padding:2px 7px;font-size:11px;border-radius:6px"
|
||
onclick="setBwPreset(50, 20)">50 / 20 Mbps</button>
|
||
</div>
|
||
|
||
<p class="muted" style="font-size:11px;margin:0;line-height:1.4" data-i18n="modal_bw_desc">
|
||
💡 Régulation appliquée par le noyau Linux (QoS / Traffic Control). 0 = illimité.
|
||
</p>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="deviceLimitsMsg" style="display:none;padding:8px 12px;border-radius:6px;font-size:13px"></div>
|
||
</div>
|
||
<div class="modal-footer" style="display:flex;justify-content:flex-end;gap:10px">
|
||
<button type="button" class="secondary" onclick="closeDeviceLimitsModal()"
|
||
data-i18n="btn_cancel">Annuler</button>
|
||
<button type="button" id="btnSaveDeviceLimits" onclick="submitDeviceLimits()"
|
||
style="display:inline-flex;align-items:center;gap:6px">
|
||
<span>💾</span> <span data-i18n="modal_save_limits">Enregistrer les limitations</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Modal Changement de Type d'Appareil -->
|
||
<div id="modalDeviceType" class="modal-overlay">
|
||
<div class="modal-card" style="max-width:520px">
|
||
<div class="modal-header">
|
||
<h3 style="margin:0;display:flex;align-items:center;gap:8px" data-i18n="modal_change_dev_type_title">🏷️
|
||
Modifier le type d’appareil</h3>
|
||
<button type="button" class="secondary" onclick="closeDeviceTypeModal()"
|
||
style="padding:4px 10px;font-size:16px;border-radius:6px">✕</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<input type="hidden" id="deviceTypeModalMac" value="">
|
||
<div
|
||
style="background:var(--panel2);padding:10px 14px;border-radius:8px;border:1px solid var(--line);margin-bottom:14px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px">
|
||
<div>
|
||
<strong id="deviceTypeModalName" style="font-size:14px;display:block"></strong>
|
||
<code id="deviceTypeModalMacDisplay" style="font-size:11px;color:var(--muted)"></code>
|
||
</div>
|
||
<span id="deviceTypeModalStatus" class="pill" style="font-size:11px"></span>
|
||
</div>
|
||
<label class="label" style="margin-top:0;margin-bottom:10px;font-size:13px"
|
||
data-i18n="modal_choose_category">Choisissez une catégorie d’équipement :</label>
|
||
<div id="deviceTypeOptionsGrid"
|
||
style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px">
|
||
<!-- Options injectées par JS -->
|
||
</div>
|
||
<div id="deviceTypeModalMsg" class="muted" style="font-size:12px;margin-top:12px"></div>
|
||
</div>
|
||
<div class="modal-footer" style="display:flex;justify-content:flex-end;gap:10px">
|
||
<button type="button" class="secondary" onclick="closeDeviceTypeModal()"
|
||
data-i18n="btn_cancel">Annuler</button>
|
||
<button type="button" id="btnSaveDeviceType" onclick="saveDeviceType()"
|
||
data-i18n="btn_save">Enregistrer</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Modal Éditeur de Catégorie de Type d'Appareil -->
|
||
<div id="modalDeviceTypeEditor" class="modal-overlay">
|
||
<div class="modal-card" style="max-width:560px">
|
||
<div class="modal-header">
|
||
<h3 id="deviceTypeEditorTitle" style="margin:0;display:flex;align-items:center;gap:8px"
|
||
data-i18n="modal_cat_add_title">➕ Ajouter une catégorie d’appareil</h3>
|
||
<button type="button" class="secondary" onclick="closeDeviceTypeEditorModal()"
|
||
style="padding:4px 10px;font-size:16px;border-radius:6px">✕</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<input type="hidden" id="deviceTypeEditorOriginalId" value="">
|
||
|
||
<label class="label" for="deviceTypeEditorLabel" style="margin-top:0" data-i18n="modal_cat_name_label">Nom de
|
||
la catégorie *</label>
|
||
<input id="deviceTypeEditorLabel" type="text" maxlength="40"
|
||
placeholder="Ex: Console de jeux, Robot aspirateur..." data-i18n-placeholder="placeholder_dev_label"
|
||
oninput="autoSuggestTypeId()">
|
||
|
||
<label class="label" for="deviceTypeEditorId" data-i18n="modal_cat_id_label">Identifiant technique unique
|
||
*</label>
|
||
<input id="deviceTypeEditorId" type="text" maxlength="32" placeholder="Ex: console, robot, iot..."
|
||
data-i18n-placeholder="placeholder_dev_id" style="font-family:monospace">
|
||
<div class="muted" style="font-size:11px;margin-top:2px" data-i18n="modal_cat_id_help">Lettres minuscules,
|
||
chiffres, tirets ou soulignés uniquement.</div>
|
||
|
||
<label class="label" style="margin-top:14px" data-i18n="modal_cat_icon_label">Logo / Icône (Emoji ou SVG)
|
||
*</label>
|
||
<div style="display:flex;gap:10px;align-items:center">
|
||
<div id="deviceTypeIconPreview"
|
||
style="width:48px;height:48px;border-radius:10px;background:var(--panel2);border:1px solid var(--line);display:flex;align-items:center;justify-content:center;font-size:24px;flex-shrink:0">
|
||
📱
|
||
</div>
|
||
<div style="flex:1">
|
||
<input id="deviceTypeEditorIcon" type="text" placeholder="Emoji (📱, 💻...) ou code SVG"
|
||
data-i18n-placeholder="placeholder_dev_icon" oninput="updateDeviceTypeIconPreview()">
|
||
</div>
|
||
</div>
|
||
|
||
<div style="margin-top:8px">
|
||
<span class="muted" style="font-size:11px;display:block;margin-bottom:6px"
|
||
data-i18n="modal_cat_quick_sugg">Suggestions rapides :</span>
|
||
<div style="display:flex;flex-wrap:wrap;gap:6px">
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('📱')" title="Smartphone">📱</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('tablet_svg')" title="Tablette">📟</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('💻')" title="PC Portable">💻</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('🖥️')" title="Ordinateur fixe">🖥️</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('📺')" title="Smart TV">📺</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('🎮')" title="Console">🎮</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px" onclick="setQuickIcon('⌚')"
|
||
title="Montre">⌚</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('🖨️')" title="Imprimante">🖨️</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('📷')" title="Caméra">📷</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('🔊')" title="Enceinte">🔊</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('🤖')" title="Robot">🤖</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('🚗')" title="Véhicule">🚗</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('📟')" title="IoT">📟</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('🌐')" title="Réseau">🌐</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('🔒')" title="Sécurité">🔒</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('💡')" title="Éclairage">💡</button>
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:16px"
|
||
onclick="setQuickIcon('🎧')" title="Casque">🎧</button>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Explorateur de recherche en ligne d'icônes & emojis -->
|
||
<div
|
||
style="margin-top:12px;background:var(--panel2);border:1px solid var(--line);border-radius:10px;padding:12px">
|
||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
|
||
<strong style="font-size:13px;display:flex;align-items:center;gap:6px"
|
||
data-i18n="modal_search_icon_title">
|
||
🔍 Rechercher un emoji ou icône SVG
|
||
</strong>
|
||
<span id="iconSearchStatus" class="muted" style="font-size:11px">Iconify & Emojis</span>
|
||
</div>
|
||
|
||
<div style="display:flex;gap:6px;margin-bottom:8px">
|
||
<input id="iconSearchQuery" type="text"
|
||
placeholder="Rechercher (ex: laptop, wifi, console, camera, robot, apple...)"
|
||
data-i18n-placeholder="placeholder_icon_search" style="margin:0;font-size:13px;padding:8px 10px"
|
||
oninput="onIconSearchInput(this.value)"
|
||
onkeydown="if(event.key==='Enter'){event.preventDefault();doIconSearch();}">
|
||
<button type="button" class="secondary" onclick="doIconSearch()"
|
||
style="padding:0 12px;font-size:13px;white-space:nowrap" data-i18n="btn_search">Chercher</button>
|
||
</div>
|
||
|
||
<!-- Filtres (Tous / Emojis / SVG) + Action coller -->
|
||
<div style="display:flex;gap:6px;align-items:center;margin-bottom:8px;flex-wrap:wrap">
|
||
<button id="filterIconAll" type="button" class="secondary" onclick="setIconSearchFilter('all')"
|
||
style="padding:2px 8px;font-size:11px;border-radius:12px;background:var(--blue);color:var(--blue-text,#071326);font-weight:700"
|
||
data-i18n="filter_all">Tous</button>
|
||
<button id="filterIconEmoji" type="button" class="secondary" onclick="setIconSearchFilter('emoji')"
|
||
style="padding:2px 8px;font-size:11px;border-radius:12px">😀 Emojis</button>
|
||
<button id="filterIconSvg" type="button" class="secondary" onclick="setIconSearchFilter('svg')"
|
||
style="padding:2px 8px;font-size:11px;border-radius:12px">⚡ SVG (Iconify)</button>
|
||
<button type="button" class="secondary" onclick="pasteSvgFromClipboard()"
|
||
title="Coller du code SVG ou un emoji copié"
|
||
style="margin-left:auto;padding:2px 8px;font-size:11px;border-radius:6px;display:inline-flex;align-items:center;gap:4px"
|
||
data-i18n="btn_paste_svg">📋 Coller SVG</button>
|
||
</div>
|
||
|
||
<!-- Grille des résultats -->
|
||
<div id="iconSearchResultsGrid"
|
||
style="display:grid;grid-template-columns:repeat(auto-fill,minmax(46px,1fr));gap:6px;max-height:190px;overflow-y:auto;padding:6px;background:var(--bg);border-radius:8px;border:1px solid var(--line);min-height:54px;align-content:start">
|
||
<!-- Rempli par JavaScript -->
|
||
</div>
|
||
|
||
<!-- Liens directs vers des sites spécialisés pour chercher des SVG / Emojis -->
|
||
<div
|
||
style="margin-top:10px;padding-top:8px;border-top:1px dashed var(--line);display:flex;align-items:center;gap:6px;flex-wrap:wrap;font-size:11px">
|
||
<span class="muted" data-i18n="explore_on_sites">Explorer sur les sites :</span>
|
||
<a id="linkSearchIconify" href="https://icon-sets.iconify.design/" target="_blank"
|
||
rel="noopener noreferrer"
|
||
style="color:var(--blue);text-decoration:none;background:var(--panel);padding:2px 6px;border-radius:4px;border:1px solid var(--line);display:inline-flex;align-items:center;gap:3px">🌐
|
||
Iconify ↗</a>
|
||
<a id="linkSearchSvgRepo" href="https://www.svgrepo.com/" target="_blank" rel="noopener noreferrer"
|
||
style="color:var(--blue);text-decoration:none;background:var(--panel);padding:2px 6px;border-radius:4px;border:1px solid var(--line);display:inline-flex;align-items:center;gap:3px">🎨
|
||
SVG Repo ↗</a>
|
||
<a id="linkSearchTabler" href="https://tabler.io/icons" target="_blank" rel="noopener noreferrer"
|
||
style="color:var(--blue);text-decoration:none;background:var(--panel);padding:2px 6px;border-radius:4px;border:1px solid var(--line);display:inline-flex;align-items:center;gap:3px">📑
|
||
Tabler Icons ↗</a>
|
||
<a id="linkSearchEmojipedia" href="https://emojipedia.org/" target="_blank" rel="noopener noreferrer"
|
||
style="color:var(--blue);text-decoration:none;background:var(--panel);padding:2px 6px;border-radius:4px;border:1px solid var(--line);display:inline-flex;align-items:center;gap:3px">📖
|
||
Emojipedia ↗</a>
|
||
</div>
|
||
</div>
|
||
|
||
<label class="label" for="deviceTypeEditorDesc" style="margin-top:14px"
|
||
data-i18n="modal_cat_desc_label">Description / Exemples d’appareils</label>
|
||
<input id="deviceTypeEditorDesc" type="text" maxlength="80" placeholder="Ex: PlayStation, Xbox, Switch..."
|
||
data-i18n-placeholder="placeholder_dev_desc">
|
||
|
||
<div id="deviceTypeEditorMsg" class="muted" style="font-size:12px;margin-top:12px"></div>
|
||
</div>
|
||
<div class="modal-footer" style="display:flex;justify-content:flex-end;gap:10px">
|
||
<button type="button" class="secondary" onclick="closeDeviceTypeEditorModal()"
|
||
data-i18n="btn_cancel">Annuler</button>
|
||
<button type="button" id="btnSaveDeviceTypeEditor" onclick="saveDeviceTypeCategory()"
|
||
data-i18n="btn_save">Enregistrer</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="modalImportBackup" class="modal-overlay">
|
||
<div class="modal-card" style="max-width:540px">
|
||
<div class="modal-header">
|
||
<h2 style="margin:0;font-size:17px;display:flex;align-items:center;gap:8px">
|
||
<span>📤</span> <span data-i18n="modal_import_title">Restauration de la sauvegarde</span>
|
||
</h2>
|
||
<button type="button" class="secondary" style="padding:4px 10px;font-size:16px"
|
||
onclick="closeImportBackupModal()">✕</button>
|
||
</div>
|
||
<div class="modal-body" style="display:flex;flex-direction:column;gap:14px">
|
||
<div style="background:var(--panel2);border:1px solid var(--line);border-radius:10px;padding:12px">
|
||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
|
||
<span style="font-weight:700;color:var(--text);word-break:break-all"
|
||
id="importFileName">fichier.json</span>
|
||
<span class="pill pill-blue" id="importFileVersion" style="font-weight:700">V5.5</span>
|
||
</div>
|
||
<div class="muted" style="font-size:12px" id="importFileMeta" data-i18n="modal_import_created_date">Date de
|
||
création : —</div>
|
||
</div>
|
||
|
||
<div>
|
||
<strong style="font-size:13px;display:block;margin-bottom:8px" data-i18n="modal_import_detected">Éléments
|
||
détectés dans l’archive :</strong>
|
||
<div id="importSummaryPills" style="display:flex;gap:6px;flex-wrap:wrap">
|
||
<!-- Injecté par JS -->
|
||
</div>
|
||
</div>
|
||
|
||
<div style="background:rgba(56,189,248,0.06);border:1px solid var(--line);border-radius:10px;padding:12px">
|
||
<strong style="font-size:13px;display:block;margin-bottom:10px" data-i18n="modal_import_select">Sélectionnez
|
||
les données à restaurer :</strong>
|
||
<div style="display:grid;grid-template-columns:1fr;gap:9px;font-size:13px">
|
||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||
<input type="checkbox" id="chkRestoreVpn" checked style="width:auto;margin:0">
|
||
<span data-i18n-html="modal_import_item_vpn">🌐 <strong>Profils VPN & routages</strong> (WireGuard
|
||
& OpenVPN)</span>
|
||
</label>
|
||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||
<input type="checkbox" id="chkRestoreDevices" checked style="width:auto;margin:0">
|
||
<span data-i18n-html="modal_import_item_names">📱 <strong>Noms des équipements</strong> & types
|
||
attribués</span>
|
||
</label>
|
||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||
<input type="checkbox" id="chkRestoreBlocked" checked style="width:auto;margin:0">
|
||
<span>🚫 <strong data-i18n="modal_import_blocked">Liste des appareils bloqués</strong></span>
|
||
</label>
|
||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||
<input type="checkbox" id="chkRestoreCategories" checked style="width:auto;margin:0">
|
||
<span data-i18n-html="modal_import_item_types">🎨 <strong>Catégories d'appareils</strong> & logos
|
||
personnalisés</span>
|
||
</label>
|
||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||
<input type="checkbox" id="chkRestorePrefs" checked style="width:auto;margin:0">
|
||
<span data-i18n-html="modal_import_item_config">⚙️ <strong>Configuration & préférences</strong>
|
||
(Wi-Fi, réseau, thèmes, etc.)</span>
|
||
</label>
|
||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer;color:var(--muted)">
|
||
<input type="checkbox" id="chkRestoreAuth" style="width:auto;margin:0">
|
||
<span data-i18n-html="modal_import_item_admin">🔐 <strong>Compte administrateur & passkeys</strong>
|
||
(⚠️ écrasera le compte courant)</span>
|
||
</label>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="importModalMsg" style="display:none;font-size:13px;padding:8px 12px;border-radius:8px"></div>
|
||
</div>
|
||
<div class="modal-footer" style="display:flex;justify-content:flex-end;gap:10px">
|
||
<button type="button" class="secondary" onclick="closeImportBackupModal()"
|
||
data-i18n="btn_cancel">Annuler</button>
|
||
<button type="button" id="btnConfirmImportAction" onclick="submitImportBackup()"
|
||
data-i18n="modal_import_btn_confirm">Confirmer et restaurer</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Modal Fichiers du Drive / Stockage Distant -->
|
||
<div id="modalRemoteDriveFiles" class="modal-overlay">
|
||
<div class="modal-card" style="max-width:840px;width:95%">
|
||
<div class="modal-header">
|
||
<h2 style="margin:0;font-size:17px;display:flex;align-items:center;gap:8px">
|
||
<span id="remoteDriveModalIcon">☁️</span>
|
||
<span data-i18n="modal_remote_drive_title">Fichiers du stockage distant (Drive)</span>
|
||
</h2>
|
||
<button type="button" class="secondary" style="padding:4px 10px;font-size:16px" onclick="closeRemoteDriveModal()">✕</button>
|
||
</div>
|
||
<div class="modal-body" style="display:flex;flex-direction:column;gap:12px">
|
||
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px">
|
||
<div id="remoteDriveModalSub" class="muted" style="font-size:13px">
|
||
Chargement des fichiers distants…
|
||
</div>
|
||
<button type="button" class="secondary" onclick="loadRemoteDriveFiles()" style="padding:4px 10px;font-size:12px;display:inline-flex;align-items:center;gap:4px">
|
||
🔄 Actualiser le drive
|
||
</button>
|
||
</div>
|
||
<div id="remoteDriveActionMsg" style="display:none;padding:8px 12px;border-radius:8px;font-size:13px"></div>
|
||
<div class="table-wrap" style="max-height:400px;overflow-y:auto">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th data-i18n="th_file">FICHIER</th>
|
||
<th data-i18n="th_date">DATE</th>
|
||
<th data-i18n="th_size">TAILLE</th>
|
||
<th data-i18n="th_status">STATUT</th>
|
||
<th style="text-align:right" data-i18n="th_actions">ACTIONS</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody id="remoteDriveFilesTableBody">
|
||
<tr><td colspan="5" class="empty">Chargement…</td></tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="modal-footer" style="display:flex;justify-content:flex-end">
|
||
<button type="button" class="secondary" onclick="closeRemoteDriveModal()" data-i18n="btn_close">Fermer</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</main>
|
||
|
||
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js" defer></script>
|
||
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" async></script>
|
||
<script>
|
||
|
||
|
||
|
||
function $(id) { return document.getElementById(id); }
|
||
const API_URL = location.protocol === 'file:' ? 'http://127.0.0.1:8080' : '';
|
||
/* Version de l'application */
|
||
const APP_VERSION = "V5.5";
|
||
const ICON_REFRESH_ARROW = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" style="display:inline-block;vertical-align:middle"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.9 1 6.7 2.4L21 8"/><polyline points="21 3 21 8 16 8"/></svg>';
|
||
const ICON_GEAR = '⚙️';
|
||
const ICON_TABLET = '<svg width="1.15em" height="1.15em" viewBox="0 0 24 24" fill="none" style="display:inline-block;vertical-align:-0.18em;flex-shrink:0" aria-label="Tablette"><rect x="2.5" y="1.5" width="19" height="21" rx="2.5" fill="#1e293b" stroke="#64748b" stroke-width="1"/><rect x="4" y="3.2" width="16" height="15.6" rx="1.2" fill="#38bdf8"/><circle cx="12" cy="2.3" r="0.5" fill="#94a3b8"/><rect x="10" y="20" width="4" height="1.2" rx="0.6" fill="#94a3b8"/></svg>';
|
||
const ICON_SERVER = '<svg width="1.15em" height="1.15em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline-block;vertical-align:-0.18em;flex-shrink:0" aria-label="Serveur"><rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>';
|
||
const ICON_ROUTER = '<svg width="1.15em" height="1.15em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline-block;vertical-align:-0.18em;flex-shrink:0" aria-label="Routeur"><rect x="2" y="14" width="20" height="8" rx="2"/><line x1="6" y1="18" x2="6.01" y2="18"/><line x1="10" y1="18" x2="10.01" y2="18"/><line x1="14" y1="18" x2="14.01" y2="18"/><path d="M5 10a10 10 0 0 1 14 0"/><path d="M8.5 12a5 5 0 0 1 7 0"/></svg>';
|
||
const ICON_LAPTOP = '<svg width="1.15em" height="1.15em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline-block;vertical-align:-0.18em;flex-shrink:0" aria-label="PC Portable"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M2 20h20"/></svg>';
|
||
|
||
/* ============================================================
|
||
Système International d'Internationalisation (i18n)
|
||
Langues supportées : Français (fr), English US (en-us), English UK (en-gb)
|
||
============================================================ */
|
||
const LANGUAGES = {
|
||
'fr': { code: 'fr', name: 'Français', flag: '🇫🇷', short: 'FR', label: 'Français (France)', country: 'France' },
|
||
'en-us': { code: 'en-us', name: 'English (US)', flag: '🇺🇸', short: 'US', label: 'English (US)', country: 'United States' },
|
||
'en-gb': { code: 'en-gb', name: 'English (UK)', flag: '🇬🇧', short: 'UK', label: 'English (UK)', country: 'United Kingdom' }
|
||
};
|
||
|
||
let currentLanguage = localStorage.getItem('apLanguage') || 'fr';
|
||
if (!LANGUAGES[currentLanguage]) currentLanguage = 'fr';
|
||
|
||
// Dictionnaire i18n modulaire chargé depuis lang/*.js
|
||
const I18N = window.I18N || {};
|
||
|
||
function t(key, fallback = '') {
|
||
const langObj = I18N[currentLanguage] || I18N['fr'];
|
||
if (langObj && langObj[key] !== undefined) return langObj[key];
|
||
if (I18N['fr'] && I18N['fr'][key] !== undefined) return I18N['fr'][key];
|
||
return fallback !== null ? (fallback || key) : null;
|
||
}
|
||
|
||
const ERROR_TRANSLATIONS = {
|
||
// Délais d'attente / Timeouts
|
||
"Délai d'attente dépassé": { 'en-us': "Request timed out", 'en-gb': "Request timed out" },
|
||
"Délai d’attente dépassé": { 'en-us': "Request timed out", 'en-gb': "Request timed out" },
|
||
"Request timed out": { 'fr': "Délai d’attente dépassé" },
|
||
|
||
// Authentification et sessions
|
||
"Authentification requise": { 'en-us': "Authentication required", 'en-gb': "Authentication required" },
|
||
"Session expirée": { 'en-us': "Session expired", 'en-gb': "Session expired" },
|
||
"Nom d’utilisateur ou mot de passe incorrect": { 'en-us': "Incorrect username or password", 'en-gb': "Incorrect username or password" },
|
||
"Nom d'utilisateur ou mot de passe incorrect": { 'en-us': "Incorrect username or password", 'en-gb': "Incorrect username or password" },
|
||
"Mot de passe actuel incorrect": { 'en-us': "Incorrect current password", 'en-gb': "Incorrect current password" },
|
||
"Mot de passe incorrect": { 'en-us': "Incorrect password", 'en-gb': "Incorrect password" },
|
||
"Les nouveaux mots de passe ne correspondent pas": { 'en-us': "New passwords do not match", 'en-gb': "New passwords do not match" },
|
||
"Les mots de passe ne correspondent pas": { 'en-us': "Passwords do not match", 'en-gb': "Passwords do not match" },
|
||
"Le mot de passe doit contenir au moins 8 caractères": { 'en-us': "Password must be at least 8 characters long", 'en-gb': "Password must be at least 8 characters long" },
|
||
"Code 2FA incorrect": { 'en-us': "Incorrect 2FA code", 'en-gb': "Incorrect 2FA code" },
|
||
"Code de vérification invalide": { 'en-us': "Invalid verification code", 'en-gb': "Invalid verification code" },
|
||
"Code de secours déjà utilisé": { 'en-us': "Backup code already used", 'en-gb': "Backup code already used" },
|
||
"Utilisateur introuvable": { 'en-us': "User not found", 'en-gb': "User not found" },
|
||
"Action non autorisée": { 'en-us': "Unauthorized action", 'en-gb': "Unauthorized action" },
|
||
"Non autorisé": { 'en-us': "Unauthorized", 'en-gb': "Unauthorized" },
|
||
"Trop de tentatives": { 'en-us': "Too many attempts", 'en-gb': "Too many attempts" },
|
||
|
||
// Enregistrement / Quotas / Réseau
|
||
"Erreur lors de l’enregistrement": { 'en-us': "Error while saving", 'en-gb': "Error while saving" },
|
||
"Erreur lors de l'enregistrement": { 'en-us': "Error while saving", 'en-gb': "Error while saving" },
|
||
"Erreur lors de la réinitialisation": { 'en-us': "Error while resetting", 'en-gb': "Error while resetting" },
|
||
"Erreur lors de la suppression": { 'en-us': "Error while deleting", 'en-gb': "Error while deleting" },
|
||
"Erreur lors de l’assignation VPN": { 'en-us': "Error during VPN assignment", 'en-gb': "Error during VPN assignment" },
|
||
"Erreur lors de la modification du Kill-Switch": { 'en-us': "Error updating Kill-Switch", 'en-gb': "Error updating Kill-Switch" },
|
||
"Erreur réseau ou serveur inaccessible": { 'en-us': "Network error or unreachable server", 'en-gb': "Network error or unreachable server" },
|
||
"Impossible de contacter le serveur": { 'en-us': "Unable to reach server", 'en-gb': "Unable to reach server" },
|
||
"Échec de la connexion": { 'en-us': "Connection failed", 'en-gb': "Connection failed" },
|
||
"Failed to fetch": { 'fr': "Impossible de contacter le serveur", 'en-us': "Unable to reach server", 'en-gb': "Unable to reach server" },
|
||
"NetworkError when attempting to fetch resource.": { 'fr': "Erreur réseau lors de la communication avec le serveur.", 'en-us': "Network error while communicating with server.", 'en-gb': "Network error while communicating with server." },
|
||
"The user aborted a request.": { 'fr': "La requête a été interrompue.", 'en-us': "The request was aborted.", 'en-gb': "The request was aborted." },
|
||
"Adresse MAC invalide": { 'en-us': "Invalid MAC address", 'en-gb': "Invalid MAC address" },
|
||
|
||
// Wi-Fi / AP
|
||
"Impossible de démarrer l’AP": { 'en-us': "Unable to start Wi-Fi AP", 'en-gb': "Unable to start Wi-Fi AP" },
|
||
"Impossible d’arrêter l’AP": { 'en-us': "Unable to stop Wi-Fi AP", 'en-gb': "Unable to stop Wi-Fi AP" },
|
||
"Impossible de redémarrer l’AP": { 'en-us': "Unable to restart Wi-Fi AP", 'en-gb': "Unable to restart Wi-Fi AP" },
|
||
"SSID invalide": { 'en-us': "Invalid SSID", 'en-gb': "Invalid SSID" },
|
||
"Mot de passe Wi-Fi trop court": { 'en-us': "Wi-Fi password too short", 'en-gb': "Wi-Fi password too short" },
|
||
|
||
// Sauvegardes
|
||
"Aucune donnée de sauvegarde en attente.": { 'en-us': "No pending backup data.", 'en-gb': "No pending backup data." },
|
||
"Impossible de lire le fichier sélectionné.": { 'en-us': "Unable to read the selected file.", 'en-gb': "Unable to read the selected file." },
|
||
"Erreur d'analyse de la sauvegarde": { 'en-us': "Backup parsing error", 'en-gb': "Backup parsing error" },
|
||
"Erreur lors de la lecture du fichier JSON": { 'en-us': "Error reading JSON file", 'en-gb': "Error reading JSON file" },
|
||
|
||
// Passkeys
|
||
"Passkey introuvable": { 'en-us': "Passkey not found", 'en-gb': "Passkey not found" },
|
||
"Le nom de la clé de sécurité ne peut pas être vide.": { 'en-us': "Security key name cannot be empty.", 'en-gb': "Security key name cannot be empty." },
|
||
"Les Passkeys nécessitent un navigateur moderne et un contexte sécurisé (HTTPS ou localhost).": { 'en-us': "Passkeys require a modern browser and a secure context (HTTPS or localhost).", 'en-gb': "Passkeys require a modern browser and a secure context (HTTPS or localhost)." },
|
||
|
||
// Capture PCAP
|
||
"Aucun paquet à exporter": { 'en-us': "No packets to export", 'en-gb': "No packets to export" },
|
||
"Impossible de générer l’image de la topologie.": { 'en-us': "Unable to generate topology image.", 'en-gb': "Unable to generate topology image." },
|
||
"Impossible de supprimer la dernière catégorie d’appareil.": { 'en-us': "Cannot delete the last device category.", 'en-gb': "Cannot delete the last device category." },
|
||
// Administration & Auth supplémentaires
|
||
"Saisissez votre mot de passe administrateur actuel": { 'en-us': "Enter your current admin password", 'en-gb': "Enter your current admin password" },
|
||
"Erreur : les mots de passe ne correspondent pas": { 'en-us': "Error: passwords do not match", 'en-gb': "Error: passwords do not match" },
|
||
"Modification refusée": { 'en-us': "Modification rejected", 'en-gb': "Modification rejected" },
|
||
"Activation refusée": { 'en-us': "Activation rejected", 'en-gb': "Activation rejected" },
|
||
"Désactivation refusée": { 'en-us': "Deactivation rejected", 'en-gb': "Deactivation rejected" },
|
||
"Génération refusée": { 'en-us': "Generation rejected", 'en-gb': "Generation rejected" },
|
||
"Régénération refusée": { 'en-us': "Regeneration rejected", 'en-gb': "Regeneration rejected" },
|
||
"Statut 2FA indisponible": { 'en-us': "2FA status unavailable", 'en-gb': "2FA status unavailable" },
|
||
"Code refusé": { 'en-us': "Code rejected", 'en-gb': "Code rejected" },
|
||
"Configuration refusée": { 'en-us': "Configuration rejected", 'en-gb': "Configuration rejected" },
|
||
"Suppression refusée": { 'en-us': "Deletion rejected", 'en-gb': "Deletion rejected" },
|
||
"Impossible de déconnecter la session": { 'en-us': "Unable to disconnect session", 'en-gb': "Unable to disconnect session" },
|
||
"Impossible de renommer la machine": { 'en-us': "Unable to rename device", 'en-gb': "Unable to rename device" },
|
||
"Erreur d’enregistrement Passkey": { 'en-us': "Passkey registration error", 'en-gb': "Passkey registration error" },
|
||
"Erreur Passkey": { 'en-us': "Passkey error", 'en-gb': "Passkey error" },
|
||
"Vérification échouée": { 'en-us': "Verification failed", 'en-gb': "Verification failed" },
|
||
"Erreur options": { 'en-us': "Options error", 'en-gb': "Options error" },
|
||
"Erreur lors du renommage": { 'en-us': "Error while renaming", 'en-gb': "Error while renaming" },
|
||
|
||
// Reverse Proxy
|
||
"Erreur lors de la lecture des réglages proxy.": { 'en-us': "Error reading proxy settings.", 'en-gb': "Error reading proxy settings." },
|
||
"Impossible d’enregistrer les réglages proxy": { 'en-us': "Unable to save proxy settings", 'en-gb': "Unable to save proxy settings" },
|
||
|
||
// Notifications
|
||
"Erreur lors du test": { 'en-us': "Error during test", 'en-gb': "Error during test" },
|
||
"Erreur lors de l’envoi": { 'en-us': "Error sending notification", 'en-gb': "Error sending notification" },
|
||
|
||
// Sauvegardes
|
||
"Impossible d'analyser le fichier de sauvegarde": { 'en-us': "Unable to parse backup file", 'en-gb': "Unable to parse backup file" },
|
||
"Erreur lors de la restauration": { 'en-us': "Error restoring backup", 'en-gb': "Error restoring backup" },
|
||
"Erreur exportation": { 'en-us': "Export error", 'en-gb': "Export error" },
|
||
"Le fichier sélectionné ne semble pas être une sauvegarde valide": { 'en-us': "The selected file does not appear to be a valid backup", 'en-gb': "The selected file does not appear to be a valid backup" },
|
||
"Veuillez cocher au moins une catégorie": { 'en-us': "Please select at least one category", 'en-gb': "Please select at least one category" },
|
||
"Contenu du fichier manquant": { 'en-us': "Missing file content", 'en-gb': "Missing file content" },
|
||
"Erreur interne": { 'en-us': "Internal error", 'en-gb': "Internal error" },
|
||
"Fichier base de données introuvable": { 'en-us': "Database file not found", 'en-gb': "Database file not found" },
|
||
"IP publique introuvable via ce tunnel": { 'en-us': "Public IP not found through this tunnel", 'en-gb': "Public IP not found through this tunnel" },
|
||
"JSON invalide": { 'en-us': "Invalid JSON", 'en-gb': "Invalid JSON" },
|
||
"Le tunnel VPN est actuellement déconnecté": { 'en-us': "VPN tunnel is currently disconnected", 'en-gb': "VPN tunnel is currently disconnected" },
|
||
"Profil VPN introuvable": { 'en-us': "VPN profile not found", 'en-gb': "VPN profile not found" },
|
||
"Profil introuvable": { 'en-us': "Profile not found", 'en-gb': "Profile not found" },
|
||
"Route inconnue": { 'en-us': "Unknown route", 'en-gb': "Unknown route" },
|
||
"Tunnel VPN déconnecté": { 'en-us': "VPN tunnel disconnected", 'en-gb': "VPN tunnel disconnected" },
|
||
"Nom d'icône manquant": { 'en-us': "Missing icon name", 'en-gb': "Missing icon name" },
|
||
"Nom d’icône manquant": { 'en-us': "Missing icon name", 'en-gb': "Missing icon name" },
|
||
};
|
||
|
||
function tErr(err) {
|
||
if (!err) return '';
|
||
let msg = '';
|
||
if (typeof err === 'string') msg = err;
|
||
else if (err && err.message) msg = err.message;
|
||
else msg = String(err);
|
||
|
||
const lang = (typeof currentLanguage !== 'undefined' ? currentLanguage : 'fr').toLowerCase();
|
||
const isEn = lang.startsWith('en');
|
||
const errPrefix = isEn ? 'Error: ' : 'Erreur : ';
|
||
|
||
// Retirer préfixe éventuel déjà présent pour normaliser
|
||
msg = msg.replace(/^Erreur\s*:\s*/i, '').replace(/^Error\s*:\s*/i, '').trim();
|
||
|
||
// Gestion des timeouts dynamiques style "Délai d'attente dépassé (15s)" ou "Request timed out (15s)"
|
||
const timeoutMatch = msg.match(/(?:Délai d['’]attente dépassé|Request timed out)\s*\(([^)]+)\)/i);
|
||
if (timeoutMatch) {
|
||
const timeSec = timeoutMatch[1];
|
||
return isEn ? `Error: Request timed out (${timeSec})` : `Erreur : Délai d'attente dépassé (${timeSec})`;
|
||
}
|
||
|
||
// Traduction via dictionnaire si disponible
|
||
if (isEn) {
|
||
if (ERROR_TRANSLATIONS[msg]) {
|
||
const trans = ERROR_TRANSLATIONS[msg][lang] || ERROR_TRANSLATIONS[msg]['en-us'];
|
||
if (trans) return errPrefix + trans;
|
||
}
|
||
for (const k in ERROR_TRANSLATIONS) {
|
||
if (msg.includes(k)) {
|
||
const trans = ERROR_TRANSLATIONS[k][lang] || ERROR_TRANSLATIONS[k]['en-us'];
|
||
if (trans) {
|
||
msg = msg.replace(k, trans);
|
||
return errPrefix + msg;
|
||
}
|
||
}
|
||
}
|
||
} else {
|
||
if (ERROR_TRANSLATIONS[msg] && ERROR_TRANSLATIONS[msg]['fr']) {
|
||
return errPrefix + ERROR_TRANSLATIONS[msg]['fr'];
|
||
}
|
||
}
|
||
|
||
return errPrefix + msg;
|
||
}
|
||
const SUCCESS_TRANSLATIONS = {
|
||
// Wi-Fi / AP
|
||
"Réglages enregistrés": { 'en-us': "Settings saved successfully", 'en-gb': "Settings saved successfully" },
|
||
"Configuration enregistrée": { 'en-us': "Configuration saved successfully", 'en-gb': "Configuration saved successfully" },
|
||
"Démarrage de l’AP en cours…": { 'en-us': "Starting Wi-Fi AP…", 'en-gb': "Starting Wi-Fi AP…" },
|
||
"Arrêt de l’AP en cours…": { 'en-us': "Stopping Wi-Fi AP…", 'en-gb': "Stopping Wi-Fi AP…" },
|
||
"Redémarrage de l’AP en cours…": { 'en-us': "Restarting Wi-Fi AP…", 'en-gb': "Restarting Wi-Fi AP…" },
|
||
|
||
// Admin & 2FA
|
||
"Compte créé": { 'en-us': "Account created", 'en-gb': "Account created" },
|
||
"Identifiants modifiés avec succès !": { 'en-us': "Credentials updated successfully!", 'en-gb': "Credentials updated successfully!" },
|
||
"Double identification activée avec succès !": { 'en-us': "Two-factor authentication enabled successfully!", 'en-gb': "Two-factor authentication enabled successfully!" },
|
||
"Double identification désactivée": { 'en-us': "Two-factor authentication disabled", 'en-gb': "Two-factor authentication disabled" },
|
||
"Nouveaux codes générés avec succès !": { 'en-us': "New recovery codes generated successfully!", 'en-gb': "New recovery codes generated successfully!" },
|
||
"Nouveaux codes générés et téléchargés avec succès !": { 'en-us': "New recovery codes generated and downloaded successfully!", 'en-gb': "New recovery codes generated and downloaded successfully!" },
|
||
"Fichier des codes de récupération téléchargé !": { 'en-us': "Recovery codes file downloaded!", 'en-gb': "Recovery codes file downloaded!" },
|
||
"Codes copiés dans le presse-papier !": { 'en-us': "Codes copied to clipboard!", 'en-gb': "Codes copied to clipboard!" },
|
||
|
||
// Passkeys
|
||
"Passkey enregistrée avec succès !": { 'en-us': "Passkey registered successfully!", 'en-gb': "Passkey registered successfully!" },
|
||
"Passkey supprimée avec succès": { 'en-us': "Passkey deleted successfully", 'en-gb': "Passkey deleted successfully" },
|
||
"Clé de sécurité renommée avec succès": { 'en-us': "Security key renamed successfully", 'en-gb': "Security key renamed successfully" },
|
||
"Clé renommée avec succès !": { 'en-us': "Key renamed successfully!", 'en-gb': "Key renamed successfully!" },
|
||
"Authentification Passkey réussie !": { 'en-us': "Passkey authentication successful!", 'en-gb': "Passkey authentication successful!" },
|
||
|
||
// Sessions
|
||
"Session déconnectée avec succès": { 'en-us': "Session disconnected successfully", 'en-gb': "Session disconnected successfully" },
|
||
"Machine renommée avec succès": { 'en-us': "Device renamed successfully", 'en-gb': "Device renamed successfully" },
|
||
"Machine renommée avec succès !": { 'en-us': "Device renamed successfully!", 'en-gb': "Device renamed successfully!" },
|
||
|
||
// Proxy inversé
|
||
"Réglages du proxy inversé enregistrés avec succès !": { 'en-us': "Reverse proxy settings saved successfully!", 'en-gb': "Reverse proxy settings saved successfully!" },
|
||
"Réglages enregistrés !": { 'en-us': "Settings saved!", 'en-gb': "Settings saved!" },
|
||
|
||
// Notifications
|
||
"Réglages enregistrés avec succès !": { 'en-us': "Settings saved successfully!", 'en-gb': "Settings saved successfully!" },
|
||
"Test réussi !": { 'en-us': "Test succeeded!", 'en-gb': "Test succeeded!" },
|
||
"Certains tests ont échoué": { 'en-us': "Some tests failed", 'en-gb': "Some tests failed" },
|
||
"Rapport envoyé avec succès !": { 'en-us': "Report sent successfully!", 'en-gb': "Report sent successfully!" },
|
||
"Message de test Gotify envoyé avec succès": { 'en-us': "Gotify test message sent successfully", 'en-gb': "Gotify test message sent successfully" },
|
||
"Webhook Discord exécuté avec succès": { 'en-us': "Discord webhook executed successfully", 'en-gb': "Discord webhook executed successfully" },
|
||
"Push Pushbullet envoyé avec succès": { 'en-us': "Pushbullet push sent successfully", 'en-gb': "Pushbullet push sent successfully" },
|
||
"Notification Pushover délivrée avec succès": { 'en-us': "Pushover notification delivered successfully", 'en-gb': "Pushover notification delivered successfully" },
|
||
"Notification envoyée sur Slack avec succès": { 'en-us': "Notification sent to Slack successfully", 'en-gb': "Notification sent to Slack successfully" },
|
||
"Email envoyé avec succès": { 'en-us': "Email sent successfully", 'en-gb': "Email sent successfully" },
|
||
"Message Telegram envoyé avec succès": { 'en-us': "Telegram message sent successfully", 'en-gb': "Telegram message sent successfully" },
|
||
"Requête Webhook exécutée avec succès": { 'en-us': "Webhook request executed successfully", 'en-gb': "Webhook request executed successfully" },
|
||
"Message ntfy envoyé avec succès": { 'en-us': "ntfy message sent successfully", 'en-gb': "ntfy message sent successfully" },
|
||
|
||
// VPN
|
||
"Profil VPN enregistré avec succès": { 'en-us': "VPN profile saved successfully", 'en-gb': "VPN profile saved successfully" },
|
||
"Profil VPN supprimé avec succès": { 'en-us': "VPN profile deleted successfully", 'en-gb': "VPN profile deleted successfully" },
|
||
"IP publique VPN détectée": { 'en-us': "VPN public IP detected", 'en-gb': "VPN public IP detected" },
|
||
|
||
// Appareils / Quotas
|
||
"Limitations enregistrées avec succès": { 'en-us': "Limits saved successfully", 'en-gb': "Limits saved successfully" },
|
||
"Appareil renommé avec succès": { 'en-us': "Device renamed successfully", 'en-gb': "Device renamed successfully" },
|
||
"Type d’appareil modifié avec succès": { 'en-us': "Device type updated successfully", 'en-gb': "Device type updated successfully" },
|
||
"Catégorie d’appareil enregistrée avec succès": { 'en-us': "Device category saved successfully", 'en-gb': "Device category saved successfully" },
|
||
"Catégorie enregistrée avec succès !": { 'en-us': "Category saved successfully!", 'en-gb': "Category saved successfully!" },
|
||
"Catégorie supprimée avec succès": { 'en-us': "Category deleted successfully", 'en-gb': "Category deleted successfully" },
|
||
"Catégories réinitialisées avec succès": { 'en-us': "Categories reset successfully", 'en-gb': "Categories reset successfully" },
|
||
"Appareil supprimé de l’historique": { 'en-us': "Device removed from history", 'en-gb': "Device removed from history" },
|
||
"Historique des domaines réinitialisé": { 'en-us': "Domain history reset", 'en-gb': "Domain history reset" },
|
||
"Tous les journaux ont été supprimés": { 'en-us': "All logs have been cleared", 'en-gb': "All logs have been cleared" },
|
||
|
||
// Sauvegardes / Maintenance
|
||
"Sauvegarde restaurée avec succès !": { 'en-us': "Backup restored successfully!", 'en-gb': "Backup restored successfully!" },
|
||
"Sauvegarde restaurée avec succès": { 'en-us': "Backup restored successfully", 'en-gb': "Backup restored successfully" },
|
||
"Sauvegarde complète téléchargée": { 'en-us': "Full backup downloaded", 'en-gb': "Full backup downloaded" },
|
||
"Données réinitialisées": { 'en-us': "Data reset successfully", 'en-gb': "Data reset successfully" },
|
||
"Personnalisation enregistrée sur le serveur": { 'en-us': "Customization saved to server", 'en-gb': "Customization saved to server" },
|
||
"Réglages des notifications enregistrés avec succès": { 'en-us': "Notification settings saved successfully", 'en-gb': "Notification settings saved successfully" },
|
||
"Double identification activée. Conservez vos codes de récupération.": { 'en-us': "Two-factor authentication enabled. Keep your recovery codes safe.", 'en-gb': "Two-factor authentication enabled. Keep your recovery codes safe." },
|
||
"Identifiants modifiés": { 'en-us': "Credentials updated", 'en-gb': "Credentials updated" },
|
||
"Journaux supprimés": { 'en-us': "Logs deleted", 'en-gb': "Logs deleted" },
|
||
"Nouveaux codes générés": { 'en-us': "New recovery codes generated", 'en-gb': "New recovery codes generated" },
|
||
"Paquets de test DNS et ICMP générés": { 'en-us': "DNS and ICMP test packets generated", 'en-gb': "DNS and ICMP test packets generated" },
|
||
"Préférences enregistrées": { 'en-us': "Preferences saved", 'en-gb': "Preferences saved" },
|
||
"Secret généré. Ajoutez-le dans votre application TOTP puis confirmez avec le code affiché.": { 'en-us': "Secret generated. Add it to your TOTP app and confirm with the code.", 'en-gb': "Secret generated. Add it to your TOTP app and confirm with the code." },
|
||
"Toutes les données et le point d’accès ont été réinitialisés et supprimés": { 'en-us': "All data and access point have been reset and deleted", 'en-gb': "All data and access point have been reset and deleted" },
|
||
"Assignation VPN du client mise à jour avec succès": { 'en-us': "Client VPN assignment updated successfully", 'en-gb': "Client VPN assignment updated successfully" },
|
||
};
|
||
|
||
function tMsg(msg) {
|
||
if (!msg) return '';
|
||
let str = (typeof msg === 'string') ? msg : (msg && msg.message ? msg.message : String(msg));
|
||
const lang = (typeof currentLanguage !== 'undefined' ? currentLanguage : 'fr').toLowerCase();
|
||
const isEn = lang.startsWith('en');
|
||
if (!isEn) return str;
|
||
if (SUCCESS_TRANSLATIONS[str]) {
|
||
return SUCCESS_TRANSLATIONS[str][lang] || SUCCESS_TRANSLATIONS[str]['en-us'] || str;
|
||
}
|
||
for (const k in SUCCESS_TRANSLATIONS) {
|
||
if (str.includes(k)) {
|
||
const trans = SUCCESS_TRANSLATIONS[k][lang] || SUCCESS_TRANSLATIONS[k]['en-us'];
|
||
if (trans) return str.replace(k, trans);
|
||
}
|
||
}
|
||
return str;
|
||
}
|
||
|
||
|
||
function formatLastUpdated(dateOrStr) {
|
||
let timeStr = '—';
|
||
const loc = (typeof currentLanguage !== 'undefined' && currentLanguage.startsWith('en')) ? (currentLanguage === 'en-us' ? 'en-US' : 'en-GB') : 'fr-FR';
|
||
if (dateOrStr) {
|
||
if (typeof dateOrStr === 'string') timeStr = dateOrStr;
|
||
else if (dateOrStr instanceof Date) timeStr = dateOrStr.toLocaleTimeString(loc);
|
||
} else {
|
||
timeStr = new Date().toLocaleTimeString(loc);
|
||
}
|
||
return `${t('dash_updated', 'Dernière actualisation :')} ${timeStr}`;
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
function getLanguageFlagSvg(code, width = 22, height = 15) {
|
||
const c = String(code || '').toLowerCase();
|
||
const radius = Math.max(2, Math.round(height * 0.16));
|
||
const style = `display:inline-block;vertical-align:middle;border-radius:${radius}px;box-shadow:0 1px 2px rgba(0,0,0,0.35);flex-shrink:0;overflow:hidden;border:1px solid rgba(255,255,255,0.18)`;
|
||
|
||
if (c === 'fr') {
|
||
return `<svg viewBox="0 0 30 20" width="${width}" height="${height}" style="${style}" aria-label="France"><rect width="10" height="20" fill="#002654"/><rect x="10" width="10" height="20" fill="#ffffff"/><rect x="20" width="10" height="20" fill="#ce1126"/></svg>`;
|
||
}
|
||
if (c === 'en-us' || c === 'us') {
|
||
return `<svg viewBox="0 0 190 100" width="${width}" height="${height}" style="${style}" aria-label="United States"><rect width="190" height="100" fill="#b22234"/><path d="M0,7.7h190M0,23h190M0,38.5h190M0,53.8h190M0,69.2h190M0,84.6h190" stroke="#ffffff" stroke-width="7.7"/><rect width="76" height="53.8" fill="#3c3b6e"/><g fill="#ffffff"><circle cx="15" cy="11" r="3.5"/><circle cx="38" cy="11" r="3.5"/><circle cx="61" cy="11" r="3.5"/><circle cx="26.5" cy="22" r="3.5"/><circle cx="49.5" cy="22" r="3.5"/><circle cx="15" cy="33" r="3.5"/><circle cx="38" cy="33" r="3.5"/><circle cx="61" cy="33" r="3.5"/><circle cx="26.5" cy="44" r="3.5"/><circle cx="49.5" cy="44" r="3.5"/></g></svg>`;
|
||
}
|
||
if (c === 'en-gb' || c === 'gb' || c === 'uk') {
|
||
return `<svg viewBox="0 0 60 30" width="${width}" height="${height}" style="${style}" aria-label="United Kingdom"><path d="M0 0v30h60V0z" fill="#012169"/><path d="M0 0l60 30M60 0L0 30" stroke="#fff" stroke-width="6"/><path d="M0 0l60 30M60 0L0 30" stroke="#C8102E" stroke-width="4"/><path d="M30 0v30M0 15h60" stroke="#fff" stroke-width="10"/><path d="M30 0v30M0 15h60" stroke="#C8102E" stroke-width="6"/></svg>`;
|
||
}
|
||
return `<span style="font-size:${height}px;line-height:1">🌐</span>`;
|
||
}
|
||
|
||
const AUTH_COOKIE_NAME = 'apAuthToken';
|
||
const AUTH_COOKIE_TTL = 30 * 86400;
|
||
function readCookie(name) { const item = document.cookie.split('; ').find(row => row.startsWith(name + '=')); return item ? decodeURIComponent(item.split('=').slice(1).join('=')) : '' }
|
||
function saveAuthCookie(token) { document.cookie = AUTH_COOKIE_NAME + '=' + encodeURIComponent(token) + '; Max-Age=' + AUTH_COOKIE_TTL + '; Path=/; SameSite=Lax' }
|
||
function clearAuthCookie() { document.cookie = AUTH_COOKIE_NAME + '=; Max-Age=0; Path=/; SameSite=Lax' }
|
||
const savedAppStarted = (sessionStorage.getItem('apAppStarted') || localStorage.getItem('apAppStarted')) === '1';
|
||
const visitedInSession = sessionStorage.getItem('apVisited') === '1';
|
||
if (savedAppStarted || visitedInSession) {
|
||
const bText = $('loaderBadgeText'), bIcon = $('loaderBadgeIcon'), sText = $('loaderStatusText'), topIcon = $('loaderTopIcon');
|
||
if (bText) bText.textContent = t('loader_refreshing_badge', "Actualisation en cours");
|
||
if (bIcon) bIcon.innerHTML = ICON_REFRESH_ARROW;
|
||
if (sText) sText.textContent = t('loader_refreshing', "Actualisation en cours…");
|
||
if (topIcon) topIcon.innerHTML = '<svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="#38bdf8" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" style="display:block;animation:spin 2s linear infinite"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.9 1 6.7 2.4L21 8"/><polyline points="21 3 21 8 16 8"/></svg>';
|
||
}
|
||
|
||
let authToken = readCookie(AUTH_COOKIE_NAME) || localStorage.getItem('apAuthToken') || sessionStorage.getItem('apAuthToken') || '';
|
||
let authConfigured = false; let authSetupMode = false; let authTwoFactor = false; let clients = []; let status = {};
|
||
let clientsPage = 1; let topClientsPage = 1; let statsTablePage = 1; let logsPage = 1; let blockedPage = 1; let devicesPage = 1;
|
||
let devicesFilter = 'all'; let devicesSearchQuery = '';
|
||
let logsDataCache = []; let blockedDataCache = []; let devicesDataCache = []; let isDevicesLoading = false;
|
||
function applyLanguage(lang, persist = false) {
|
||
if (!LANGUAGES[lang]) lang = 'fr';
|
||
currentLanguage = lang;
|
||
localStorage.setItem('apLanguage', lang);
|
||
try {
|
||
document.documentElement.lang = (lang === 'fr' ? 'fr' : (lang === 'en-us' ? 'en-US' : 'en-GB'));
|
||
} catch (_) { }
|
||
|
||
const meta = LANGUAGES[lang];
|
||
if ($('headerLangFlag')) $('headerLangFlag').innerHTML = getLanguageFlagSvg(lang, 20, 14);
|
||
if ($('headerLangText')) $('headerLangText').textContent = meta.short;
|
||
if ($('headerLangBtn')) $('headerLangBtn').title = t('header_lang_tooltip', 'Paramètres de langue');
|
||
|
||
if ($('languageSelect')) $('languageSelect').value = lang;
|
||
if ($('settingsLangFlagBadge')) $('settingsLangFlagBadge').innerHTML = getLanguageFlagSvg(lang, 30, 20);
|
||
|
||
// Mettre à jour l'état actif des cartes visuelles de sélection de langue
|
||
['fr', 'en-us', 'en-gb'].forEach(k => {
|
||
const card = $('langCard_' + k);
|
||
const check = $('langCheck_' + k);
|
||
const isActive = (k === lang);
|
||
if (card) {
|
||
card.style.borderColor = isActive ? 'var(--blue)' : 'var(--line)';
|
||
card.style.background = isActive ? 'rgba(56,189,248,0.1)' : 'var(--panel2)';
|
||
card.style.boxShadow = isActive ? '0 0 0 1px var(--blue)' : 'none';
|
||
}
|
||
if (check) {
|
||
check.style.display = isActive ? 'inline' : 'none';
|
||
}
|
||
});
|
||
|
||
document.querySelectorAll('[data-i18n-html]').forEach(el => {
|
||
const k = el.getAttribute('data-i18n-html');
|
||
if (k) {
|
||
const val = t(k, null);
|
||
if (val !== null && val !== k) el.innerHTML = val;
|
||
}
|
||
});
|
||
|
||
document.querySelectorAll('[data-i18n]').forEach(el => {
|
||
const k = el.getAttribute('data-i18n');
|
||
if (k) {
|
||
const val = t(k, null);
|
||
if (val !== null && val !== k) el.textContent = val;
|
||
}
|
||
});
|
||
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
|
||
const k = el.getAttribute('data-i18n-placeholder');
|
||
if (k) {
|
||
const val = t(k, null);
|
||
if (val !== null && val !== k) el.setAttribute('placeholder', val);
|
||
}
|
||
});
|
||
document.querySelectorAll('[data-i18n-title]').forEach(el => {
|
||
const k = el.getAttribute('data-i18n-title');
|
||
if (k) {
|
||
const val = t(k, null);
|
||
if (val !== null && val !== k) el.setAttribute('title', val);
|
||
}
|
||
});
|
||
document.querySelectorAll('[data-i18n-aria-label]').forEach(el => {
|
||
const k = el.getAttribute('data-i18n-aria-label');
|
||
if (k) {
|
||
const val = t(k, null);
|
||
if (val !== null && val !== k) el.setAttribute('aria-label', val);
|
||
}
|
||
});
|
||
|
||
if ($('apControl')) {
|
||
const isStop = $('apControl').style.background && $('apControl').style.background.includes('red');
|
||
$('apControl').textContent = isStop ? t('btn_stop', 'Arrêter') : t('btn_start', 'Démarrer');
|
||
}
|
||
|
||
// Actualiser les unités et boutons préréglés de quotas
|
||
const isEn = lang.startsWith('en');
|
||
const unitGb = isEn ? 'GB' : 'Go';
|
||
const unitMb = isEn ? 'MB' : 'Mo';
|
||
const selectUnit = $('selectQuotaUnit');
|
||
if (selectUnit) {
|
||
Array.from(selectUnit.options).forEach(opt => {
|
||
if (opt.value === 'GB') opt.textContent = unitGb;
|
||
if (opt.value === 'MB') opt.textContent = unitMb;
|
||
});
|
||
}
|
||
[1, 5, 10, 20, 50].forEach(v => {
|
||
const el = document.querySelector(`[data-i18n="modal_quota_preset_${v}"]`);
|
||
if (el) el.textContent = `${v} ${unitGb}`;
|
||
});
|
||
|
||
try { if (typeof render === 'function') render(); } catch (_) { }
|
||
try { if (typeof renderDevicesTable === 'function') renderDevicesTable(); } catch (_) { }
|
||
try { if (typeof renderVpnClients === 'function' && typeof vpnClientsCache !== 'undefined' && typeof vpnProfilesCache !== 'undefined') renderVpnClients(vpnClientsCache, vpnProfilesCache); } catch (_) { }
|
||
try { if (typeof updateQuotaPreview === 'function') updateQuotaPreview(); } catch (_) { }
|
||
try {
|
||
if (typeof statsDataCache !== 'undefined' && statsDataCache) {
|
||
const isDay = (typeof currentStatsRange !== 'undefined' ? currentStatsRange : 'day') === 'day';
|
||
const itms = isDay ? (statsDataCache.hours || statsDataCache.days || []) : (statsDataCache[(typeof currentStatsRange !== 'undefined' ? currentStatsRange : 'day') + 's'] || []);
|
||
if (typeof renderStatsTable === 'function') renderStatsTable(itms, isDay);
|
||
if ($('statsTableSub')) $('statsTableSub').textContent = getStatsTableSub(typeof currentStatsRange !== 'undefined' ? currentStatsRange : 'day');
|
||
if ($('statsChartSubtitle')) $('statsChartSubtitle').textContent = getStatsChartSub(typeof currentStatsRange !== 'undefined' ? currentStatsRange : 'day');
|
||
}
|
||
} catch (_) { }
|
||
try { if (typeof renderStatsChart === 'function') renderStatsChart(typeof currentStatsRange !== 'undefined' ? currentStatsRange : 'day', true); } catch (_) { }
|
||
try { if (typeof renderTopClientsTable === 'function' && typeof updateTopClientsForRange === 'function' && typeof currentStatsRange !== 'undefined') updateTopClientsForRange(currentStatsRange); } catch (_) { }
|
||
try { if (typeof renderBlockedTable === 'function') renderBlockedTable(); } catch (_) { }
|
||
try { if (typeof renderLogsTable === 'function') renderLogsTable(); } catch (_) { }
|
||
try { if (typeof renderCaptureTable === 'function') renderCaptureTable(); } catch (_) { }
|
||
try { if (typeof renderTopology === 'function' && typeof topologyDataCache !== 'undefined' && topologyDataCache) renderTopology(topologyDataCache); } catch (_) { }
|
||
try { if (typeof renderTopologyStats === 'function' && typeof topologyDataCache !== 'undefined' && topologyDataCache) renderTopologyStats(topologyDataCache); } catch (_) { }
|
||
try { if (typeof renderVpnProfiles === 'function' && typeof vpnProfilesCache !== 'undefined') renderVpnProfiles(vpnProfilesCache); } catch (_) { }
|
||
try { if (typeof renderSessionsTable === 'function') renderSessionsTable(); } catch (_) { }
|
||
try { if (typeof loadPasskeysList === 'function' && window.passkeysById) loadPasskeysList(); } catch (_) { }
|
||
try { if (typeof render2faCurrentState === 'function') render2faCurrentState(); } catch (_) { }
|
||
try { if (typeof renderDeviceTypesTable === 'function') renderDeviceTypesTable(); } catch (_) { }
|
||
try { if (typeof updateAllPasswordToggles === 'function') updateAllPasswordToggles(); } catch (_) { }
|
||
try { if (typeof loadCaptureStatus === 'function') loadCaptureStatus(); } catch (_) { }
|
||
|
||
if ($('authView') && $('authView').classList.contains('active')) {
|
||
if ($('authTitle')) {
|
||
$('authTitle').textContent = authSetupMode ? t('auth_setup_title', 'Créer le compte administrateur') : t('auth_title', 'Connexion');
|
||
}
|
||
if ($('authIntro')) {
|
||
const appTitleEsc = escapeHtml(PROJECT_NAME || 'AP Manageur');
|
||
$('authIntro').innerHTML = authSetupMode
|
||
? `<span data-i18n="auth_setup_intro">${t('auth_setup_intro', 'Définissez le compte qui protégera le tableau de bord.')}</span>`
|
||
: `<span data-i18n="auth_intro_prefix">${t('auth_intro_prefix', 'Connectez-vous pour accéder à')}</span> <span class="app-title">${appTitleEsc}</span>.`;
|
||
}
|
||
if ($('authSubmit')) {
|
||
$('authSubmit').textContent = authSetupMode ? t('auth_setup_submit', 'Créer le compte') : t('auth_submit', 'Se connecter');
|
||
}
|
||
}
|
||
|
||
// La sauvegarde en base de données se fait exclusivement via le bouton 'Enregistrer la personnalisation'
|
||
}
|
||
|
||
function setLanguage(lang, persist = false) {
|
||
if ($('themeMessage')) $('themeMessage').textContent = '';
|
||
applyLanguage(lang, persist);
|
||
}
|
||
|
||
function openLanguageSettings() {
|
||
selectTab('settings');
|
||
selectSettingsTab('custom');
|
||
try {
|
||
const el = $('langCardsContainer');
|
||
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||
} catch (_) { }
|
||
}
|
||
window.openLanguageSettings = openLanguageSettings;
|
||
|
||
function cycleLanguage() {
|
||
const order = ['fr', 'en-us', 'en-gb'];
|
||
const idx = order.indexOf(currentLanguage);
|
||
const nextLang = order[(idx + 1) % order.length];
|
||
setLanguage(nextLang, false);
|
||
}
|
||
|
||
function onLanguageSelectChange(newLang) {
|
||
setLanguage(newLang, false);
|
||
}
|
||
// Application immédiate de la langue au chargement du script
|
||
try { applyLanguage(currentLanguage, false); } catch (_) { }
|
||
|
||
/* Catégories de types d'appareils globales et dynamiques */
|
||
let DEVICE_TYPE_LIST = [
|
||
{ id: 'phone', label: 'Smartphone', icon: '📱', raw_icon: '📱', desc: 'iPhone, Android, Galaxy...' },
|
||
{ id: 'tablet', label: 'Tablette', icon: ICON_TABLET, raw_icon: 'tablet_svg', desc: 'iPad, Galaxy Tab, Kindle...' },
|
||
{ id: 'laptop', label: 'PC Portable', icon: '💻', raw_icon: '💻', desc: 'MacBook, ThinkPad, Laptop...' },
|
||
{ id: 'desktop', label: 'Ordinateur fixe', icon: '🖥️', raw_icon: '🖥️', desc: 'PC Bureau, Mac Pro, Tour...' },
|
||
{ id: 'tv', label: 'Smart TV / Box', icon: '📺', raw_icon: '📺', desc: 'Apple TV, Chromecast, Box...' },
|
||
{ id: 'console', label: 'Console de jeux', icon: '🎮', raw_icon: '🎮', desc: 'PlayStation, Switch, Xbox...' },
|
||
{ id: 'iot', label: 'Objet connecté', icon: '📟', raw_icon: '📟', desc: 'IoT, Caméra, Domotique, RPi...' },
|
||
{ id: 'generic', label: 'Standard / Autre', icon: '💻', raw_icon: '💻', desc: 'Appareil générique / inconnu' }
|
||
];
|
||
|
||
function getDeviceTypeIcon(typeId) {
|
||
if (!typeId) typeId = 'generic';
|
||
const found = (DEVICE_TYPE_LIST || []).find(t => t.id === typeId);
|
||
if (found) {
|
||
if (found.raw_icon === 'tablet_svg' || found.icon === 'tablet_svg') return ICON_TABLET;
|
||
if (found.raw_icon === 'server_svg' || found.icon === 'server_svg') return ICON_SERVER;
|
||
if (found.raw_icon === 'router_svg' || found.icon === 'router_svg') return ICON_ROUTER;
|
||
if (found.raw_icon === 'laptop_svg' || found.icon === 'laptop_svg') return ICON_LAPTOP;
|
||
return found.icon || '💻';
|
||
}
|
||
if (typeId === 'tablet') return ICON_TABLET;
|
||
return '💻';
|
||
}
|
||
|
||
function getDeviceTypeLabel(typeId, plural = false) {
|
||
if (!typeId) typeId = 'generic';
|
||
const isEn = typeof currentLanguage === 'string' && currentLanguage.startsWith('en');
|
||
const enLabels = {
|
||
phone: plural ? 'Smartphones' : 'Smartphone',
|
||
tablet: plural ? 'Tablets' : 'Tablet',
|
||
laptop: plural ? 'Laptops' : 'Laptop',
|
||
desktop: plural ? 'Desktop PCs' : 'Desktop PC',
|
||
tv: plural ? 'Smart TVs' : 'Smart TV',
|
||
console: plural ? 'Gaming Consoles' : 'Gaming Console',
|
||
iot: plural ? 'Connected Devices' : 'Connected Device',
|
||
generic: plural ? 'Standard Devices' : 'Standard'
|
||
};
|
||
if (isEn && enLabels[typeId]) return enLabels[typeId];
|
||
const found = (DEVICE_TYPE_LIST || []).find(t => t.id === typeId);
|
||
if (found) {
|
||
if (plural) {
|
||
if (found.label.endsWith('s')) return found.label;
|
||
if (found.label === 'PC Portable') return 'PC Portables';
|
||
if (found.label === 'Ordinateur fixe') return 'Ordinateurs fixes';
|
||
if (found.label === 'Objet connecté') return 'Objets connectés';
|
||
return found.label + 's';
|
||
}
|
||
return found.label;
|
||
}
|
||
if (plural) return isEn ? 'Devices' : 'Appareils';
|
||
return isEn ? 'Standard' : 'Standard';
|
||
}
|
||
/* Nom du projet configurable */
|
||
let PROJECT_NAME = "Administration de l’AP Wi‑Fi";
|
||
let PROJECT_SHORT_NAME = "AP Manageur";
|
||
function applyProjectTitle(name = PROJECT_NAME, shortName = PROJECT_SHORT_NAME) {
|
||
PROJECT_NAME = name; PROJECT_SHORT_NAME = shortName; document.title = shortName + ' ' + APP_VERSION;
|
||
document.querySelectorAll('.app-title').forEach(el => el.textContent = name);
|
||
document.querySelectorAll('.app-short-title').forEach(el => el.textContent = shortName);
|
||
document.querySelectorAll('.app-version').forEach(el => el.textContent = APP_VERSION);
|
||
}
|
||
let captureRunning = false; let capturePackets = []; let capturePage = 1; let captureFilter = ''; let capturePollTimer = null; let captureStats = {};
|
||
|
||
function renderPagination(containerId, currentPage, totalItems, onPageChange, pageSize = 10) {
|
||
const container = $(containerId); if (!container) return;
|
||
if (!totalItems || totalItems <= pageSize) { container.innerHTML = ''; container.style.display = 'none'; return }
|
||
container.style.display = 'flex';
|
||
const totalPages = Math.ceil(totalItems / pageSize);
|
||
let html = '<div class="pagination-btns" style="margin:0 auto">';
|
||
html += `<button type="button" class="secondary" ${currentPage <= 1 ? 'disabled' : ''} onclick="${onPageChange}(${currentPage - 1})">${t('btn_prev', '← Précédent')}</button>`;
|
||
for (let p = 1; p <= totalPages; p++) {
|
||
if (totalPages <= 7 || p === 1 || p === totalPages || (p >= currentPage - 1 && p <= currentPage + 1)) {
|
||
const isActive = p === currentPage;
|
||
const activeAttr = isActive ? ' class="secondary active" style="background:var(--blue);color:var(--blue-text,#071326);font-weight:700"' : ' class="secondary"';
|
||
html += `<button type="button"${activeAttr} onclick="${onPageChange}(${p})">${p}</button>`;
|
||
} else if (p === currentPage - 2 || p === currentPage + 2) {
|
||
html += '<span style="padding:0 4px;color:var(--muted)">…</span>'
|
||
}
|
||
}
|
||
html += `<button type="button" class="secondary" ${currentPage >= totalPages ? 'disabled' : ''} onclick="${onPageChange}(${currentPage + 1})">${t('btn_next', 'Suivant →')}</button>`;
|
||
html += '</div>';
|
||
container.innerHTML = html;
|
||
}
|
||
|
||
async function apiFetch(path, options = {}) {
|
||
const devName = localStorage.getItem('apDeviceName');
|
||
options.headers = { ...(options.headers || {}), ...(authToken ? { 'X-Session-Token': authToken } : {}) };
|
||
if (typeof currentLanguage !== 'undefined') {
|
||
options.headers['X-Language'] = currentLanguage;
|
||
options.headers['Accept-Language'] = currentLanguage;
|
||
}
|
||
if (devName) options.headers['X-Device-Name'] = encodeURIComponent(devName);
|
||
let timer;
|
||
const timeoutMs = options.timeout || 15000;
|
||
const isEn = typeof currentLanguage !== 'undefined' && currentLanguage.startsWith('en');
|
||
const timeStr = `${Math.round(timeoutMs / 1000)}s`;
|
||
const timeoutMsg = isEn ? `Request timed out (${timeStr})` : `Délai d'attente dépassé (${timeStr})`;
|
||
|
||
if (!options.signal && typeof AbortController !== 'undefined') {
|
||
const controller = new AbortController();
|
||
timer = setTimeout(() => {
|
||
try {
|
||
controller.abort(new DOMException(timeoutMsg, 'TimeoutError'));
|
||
} catch (_) {
|
||
controller.abort();
|
||
}
|
||
}, timeoutMs);
|
||
options.signal = controller.signal;
|
||
}
|
||
try {
|
||
const response = await fetch(API_URL + path, options);
|
||
if (timer) clearTimeout(timer);
|
||
if (response.status === 401) {
|
||
authToken = ''; sessionStorage.removeItem('apAuthToken'); localStorage.removeItem('apAuthToken'); clearAuthCookie();
|
||
if (!$('authView') || !$('authView').classList.contains('active')) {
|
||
showAuth(false);
|
||
}
|
||
throw Error(t('err_auth_required', 'Session expirée'));
|
||
}
|
||
return response;
|
||
} catch (err) {
|
||
if (timer) clearTimeout(timer);
|
||
if (err && (err.name === 'AbortError' || (err.message && err.message.includes('without reason')))) {
|
||
const timeoutErr = new Error(timeoutMsg);
|
||
timeoutErr.name = 'TimeoutError';
|
||
throw timeoutErr;
|
||
}
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
function authHeaders(extra = {}) {
|
||
const h = { ...(extra || {}) };
|
||
if (typeof authToken !== 'undefined' && authToken) h['X-Session-Token'] = authToken;
|
||
if (typeof currentLanguage !== 'undefined') {
|
||
h['X-Language'] = currentLanguage;
|
||
h['Accept-Language'] = currentLanguage;
|
||
}
|
||
const devName = localStorage.getItem('apDeviceName');
|
||
if (devName) h['X-Device-Name'] = encodeURIComponent(devName);
|
||
return h;
|
||
}
|
||
|
||
function escapeHtml(s) {
|
||
if (s === null || s === undefined) return '';
|
||
return String(s).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
}
|
||
|
||
function showAuth(setup) {
|
||
authSetupMode = setup;
|
||
if ($('authView')) $('authView').classList.add('active');
|
||
if ($('app')) $('app').style.display = 'none';
|
||
if ($('authTitle')) {
|
||
$('authTitle').setAttribute('data-i18n', setup ? 'auth_setup_title' : 'auth_title');
|
||
$('authTitle').textContent = setup ? t('auth_setup_title', 'Créer le compte administrateur') : t('auth_title', 'Connexion');
|
||
}
|
||
if ($('authIntro')) {
|
||
const appTitleEsc = escapeHtml(PROJECT_NAME || 'AP Manageur');
|
||
$('authIntro').innerHTML = setup
|
||
? `<span data-i18n="auth_setup_intro">${t('auth_setup_intro', 'Définissez le compte qui protégera le tableau de bord.')}</span>`
|
||
: `<span data-i18n="auth_intro_prefix">${t('auth_intro_prefix', 'Connectez-vous pour accéder à')}</span> <span class="app-title">${appTitleEsc}</span>.`;
|
||
}
|
||
if ($('authSubmit')) {
|
||
$('authSubmit').setAttribute('data-i18n', setup ? 'auth_setup_submit' : 'auth_submit');
|
||
$('authSubmit').textContent = setup ? t('auth_setup_submit', 'Créer le compte') : t('auth_submit', 'Se connecter');
|
||
}
|
||
if ($('authPassword')) $('authPassword').value = ''; if ($('authOtp')) $('authOtp').value = '';
|
||
if ($('authOtpBox')) $('authOtpBox').style.display = (!setup && authTwoFactor) ? 'block' : 'none';
|
||
if ($('rememberUserBox')) $('rememberUserBox').style.display = setup ? 'none' : 'flex';
|
||
if ($('authPasskeyDivider')) $('authPasskeyDivider').style.display = setup ? 'none' : 'flex';
|
||
if ($('btnAuthPasskey')) $('btnAuthPasskey').style.display = setup ? 'none' : 'flex';
|
||
if ($('authPasskeyInfo')) $('authPasskeyInfo').style.display = setup ? 'none' : 'block';
|
||
if ($('authMessage')) $('authMessage').textContent = '';
|
||
if (!setup) { if ($('authUsername')) $('authUsername').value = localStorage.getItem('apRememberedUser') || ''; if ($('rememberUser')) $('rememberUser').checked = !!localStorage.getItem('apRememberedUser') }
|
||
else { if ($('authUsername')) $('authUsername').value = ''; if ($('rememberUser')) $('rememberUser').checked = false; }
|
||
hideLoaderScreen();
|
||
}
|
||
|
||
function showApp() {
|
||
try { loadPreferences(); } catch (_) { }
|
||
if (typeof loadDeviceTypes === 'function') loadDeviceTypes();
|
||
if ($('authView')) $('authView').classList.remove('active');
|
||
if ($('app')) $('app').style.display = 'block';
|
||
if ($('authSettingsUsername')) $('authSettingsUsername').value = localStorage.getItem('apRememberedUser') || ($('authUsername') ? $('authUsername').value : '') || '';
|
||
if (typeof loadAdminUser === 'function') loadAdminUser();
|
||
if (!currentTab) currentTab = 'dashboard';
|
||
if (typeof selectTab === 'function') {
|
||
try { selectTab(currentTab); } catch (_) { }
|
||
}
|
||
if ($('dashboardView') && !document.querySelector('.view.active')) {
|
||
$('dashboardView').classList.add('active');
|
||
}
|
||
}
|
||
|
||
async function logout() {
|
||
try { await apiFetch('/api/logout', { method: 'POST' }) } catch (_) { }
|
||
authToken = ''; sessionStorage.removeItem('apAuthToken'); localStorage.removeItem('apAuthToken'); clearAuthCookie(); showAuth(false);
|
||
}
|
||
|
||
let previousClientSignature = null; let qrSignature = null; let currentTab = 'dashboard'; let actionBusy = false;
|
||
let currentStatsRange = 'day'; let statsDataCache = null;
|
||
|
||
/* Topologie Réseau */
|
||
let currentStatsSubTab = sessionStorage.getItem('apStatsSubTab') || 'metrics';
|
||
let topologyDataCache = null;
|
||
let topologySearchQuery = '';
|
||
|
||
function selectStatsSubTab(subTab) {
|
||
currentStatsSubTab = subTab;
|
||
sessionStorage.setItem('apStatsSubTab', subTab);
|
||
const isMetrics = subTab === 'metrics';
|
||
const isTopology = subTab === 'topology';
|
||
const tm = $('tabStatsMetrics'), tt = $('tabStatsTopology');
|
||
if (tm) { tm.classList.toggle('active', isMetrics); tm.setAttribute('aria-selected', isMetrics); }
|
||
if (tt) { tt.classList.toggle('active', isTopology); tt.setAttribute('aria-selected', isTopology); }
|
||
const pm = $('panelStatsMetrics'), pt = $('panelStatsTopology');
|
||
if (pm) pm.style.display = isMetrics ? 'block' : 'none';
|
||
if (pt) pt.style.display = isTopology ? 'block' : 'none';
|
||
if (isMetrics) {
|
||
if (statsDataCache) {
|
||
const updateText = formatLastUpdated(statsDataCache.updated_at);
|
||
if ($('statsTrafficUpdated')) $('statsTrafficUpdated').textContent = updateText;
|
||
if ($('statsHistoryUpdated')) $('statsHistoryUpdated').textContent = updateText;
|
||
if ($('statsChartUpdated')) $('statsChartUpdated').textContent = updateText;
|
||
}
|
||
loadStats();
|
||
} else if (isTopology) {
|
||
if (topologyDataCache) {
|
||
renderTopology(topologyDataCache);
|
||
}
|
||
loadTopology();
|
||
}
|
||
}
|
||
|
||
function renderTopoClientVpn(c) {
|
||
if (!c.vpn_profile_name) {
|
||
return `<div class="topo-card-vpn" style="margin:6px 0;padding:3px 8px;background:var(--panel2);border-radius:6px;font-size:11px;color:var(--muted);display:flex;align-items:center;gap:5px"><span>🌐</span> ${t('topo_direct_wan', 'Direct WAN (Box)')}</div>`;
|
||
}
|
||
const isWg = c.vpn_profile_type === 'wireguard';
|
||
const logo = (typeof VPN_LOGOS !== 'undefined' && VPN_LOGOS[c.vpn_profile_type]) ? VPN_LOGOS[c.vpn_profile_type] : (isWg ? '🛡️' : '🔒');
|
||
if (!c.vpn_routed) {
|
||
return `<div class="topo-card-vpn" style="margin:6px 0;padding:3px 8px;background:rgba(255,107,107,.12);border:1px solid rgba(255,107,107,.25);border-radius:6px;font-size:11px;display:flex;align-items:center;gap:6px"><span style="display:inline-flex;align-items:center">${logo}</span><strong style="color:var(--red);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis" title="${escapeHtml(c.vpn_profile_name)}">${escapeHtml(c.vpn_profile_name)} ${t('vpn_status_disconnected_short', '(Coupé)')}</strong></div>`;
|
||
}
|
||
const flagHtml = (c.vpn_public_ip && typeof formatIpWithGeo === 'function') ? formatIpWithGeo(c.vpn_public_ip, c.vpn_public_ip_geo) : (c.vpn_public_ip ? `<code style="font-size:10px">${escapeHtml(c.vpn_public_ip)}</code>` : '');
|
||
return `<div class="topo-card-vpn" style="margin:6px 0;padding:4px 8px;background:rgba(50,213,131,.12);border:1px solid rgba(50,213,131,.25);border-radius:6px;font-size:11px;display:flex;align-items:center;justify-content:space-between;gap:6px;flex-wrap:wrap">
|
||
<div style="display:flex;align-items:center;gap:6px;min-width:0">
|
||
<span style="display:inline-flex;align-items:center">${logo}</span>
|
||
<strong style="color:var(--green);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis" title="${escapeHtml(c.vpn_profile_name)}">${escapeHtml(c.vpn_profile_name)}</strong>
|
||
</div>
|
||
${flagHtml ? `<div style="display:inline-flex;align-items:center;margin-left:auto">${flagHtml}</div>` : ''}
|
||
</div>`;
|
||
}
|
||
|
||
let isTopologyLoading = false;
|
||
async function loadTopology() {
|
||
if (isTopologyLoading) return;
|
||
isTopologyLoading = true;
|
||
try {
|
||
const res = await apiFetch('/api/network/topology', { cache: 'no-store', timeout: 10000 });
|
||
if (!res.ok) throw Error('HTTP ' + res.status);
|
||
topologyDataCache = await res.json();
|
||
renderTopology(topologyDataCache);
|
||
} catch (e) {
|
||
const isAbort = e.name === 'AbortError' || e.name === 'TimeoutError' || (e.message && e.message.toLowerCase().includes('abort'));
|
||
if (isAbort && topologyDataCache) return;
|
||
console.error('Erreur chargement topologie:', e);
|
||
} finally {
|
||
isTopologyLoading = false;
|
||
}
|
||
}
|
||
|
||
function renderTopology(data) {
|
||
if (!data) return;
|
||
// 1. Pilules d'en-tête
|
||
const wanOnline = data.internet && data.internet.status === 'online';
|
||
const wanBadge = $('topoStatusWan');
|
||
if (wanBadge) {
|
||
wanBadge.textContent = wanOnline ? t('topo_gateway_online', 'Passerelle : En ligne') : t('topo_gateway_standby', 'Passerelle : En veille');
|
||
wanBadge.className = 'pill ' + (wanOnline ? 'pill-green' : '');
|
||
}
|
||
const apBadge = $('topoStatusAp');
|
||
if (apBadge && data.ap) {
|
||
apBadge.textContent = `AP : ${data.ap.interface} (${data.ap.band} • Ch.${data.ap.channel})`;
|
||
}
|
||
const countBadge = $('topoClientsCount');
|
||
if (countBadge) {
|
||
countBadge.textContent = `${data.total_clients_count || 0} ` + t('connected_count_suffix', 'connecté(s)');
|
||
}
|
||
const trafBadge = $('topoTrafficRate');
|
||
if (trafBadge) {
|
||
trafBadge.textContent = `↓ ${data.total_download_str || '0 o/s'} • ↑ ${data.total_upload_str || '0 o/s'}`;
|
||
}
|
||
const topoUp = $('topoUpdated');
|
||
if (topoUp) {
|
||
topoUp.textContent = formatLastUpdated(data.updated_at);
|
||
}
|
||
|
||
// 2. Nœud WAN
|
||
if (data.internet) {
|
||
const wIp = $('topoWanIp');
|
||
if (wIp) wIp.textContent = `${data.internet.gateway_ip || '192.168.1.1'} (${data.internet.interface || 'WAN'})`;
|
||
}
|
||
|
||
// 2b. Nœuds Profils VPN Actifs
|
||
const topoLevel1 = $('topoLevel1');
|
||
const vpnContainer = $('topoVpnNodes');
|
||
const activeVpnList = (data.vpn_profiles || []).filter(p => p.connected);
|
||
const vpnLink = $('topoWanVerticalLink');
|
||
if (vpnLink) {
|
||
vpnLink.style.display = activeVpnList.length > 0 ? 'none' : 'flex';
|
||
}
|
||
if (topoLevel1) {
|
||
if (activeVpnList.length > 0) {
|
||
topoLevel1.className = 'topo-level1-grid';
|
||
} else {
|
||
topoLevel1.className = 'topo-level1-single';
|
||
}
|
||
}
|
||
const vpnBadge = $('topoStatusVpn');
|
||
if (vpnBadge) {
|
||
if (activeVpnList.length > 0) {
|
||
vpnBadge.style.display = 'inline-block';
|
||
vpnBadge.textContent = t('topo_vpn_active_badge', '🛡️ VPN : {n} actif(s)').replace('{n}', activeVpnList.length);
|
||
} else {
|
||
vpnBadge.style.display = 'none';
|
||
}
|
||
}
|
||
if (vpnContainer) {
|
||
if (!activeVpnList.length) {
|
||
vpnContainer.innerHTML = '';
|
||
vpnContainer.style.display = 'none';
|
||
} else {
|
||
vpnContainer.style.display = 'flex';
|
||
vpnContainer.innerHTML = activeVpnList.map(p => {
|
||
const isWg = p.type === 'wireguard';
|
||
const vpnLogo = isWg ? VPN_LOGOS.wireguard : VPN_LOGOS.openvpn;
|
||
const pNameEsc = escapeHtml(p.name);
|
||
const vpnBadgeHtml = typeof getVpnTypeBadgeHtml === 'function' ? getVpnTypeBadgeHtml(p.type, true) : `<span class="badge-${isWg ? 'vpn-wg' : 'vpn-ovpn'}">${isWg ? 'WireGuard' : 'OpenVPN'}</span>`;
|
||
const pubIpHtml = p.public_ip ? (typeof formatIpWithGeo === 'function' ? formatIpWithGeo(p.public_ip, p.public_ip_geo) : `<code>${escapeHtml(p.public_ip)}</code>`) : `<span class="muted" style="font-size:12px">${t('topo_tunnel_active', 'Tunnel actif')} (${escapeHtml(p.iface)})</span>`;
|
||
const iconBg = isWg ? 'rgba(136,23,26,.18)' : 'rgba(234,88,12,.18)';
|
||
const iconBorder = isWg ? 'rgba(220,38,38,.4)' : 'rgba(234,88,12,.4)';
|
||
const nodeBorder = isWg ? 'rgba(220,38,38,.55)' : 'rgba(234,88,12,.55)';
|
||
const nodeShadow = isWg ? '0 0 14px rgba(220,38,38,.25)' : '0 0 14px rgba(234,88,12,.25)';
|
||
|
||
const devRoutedText = t('topo_devices_routed_tunnel', '{count} appareil(s) routé(s) via ce tunnel').replace('{count}', `<strong style="color:${isWg ? '#fca5a5' : '#fdba74'}">${p.client_count || 0}</strong>`);
|
||
return `<div id="topoNodeVpn_${p.id}" class="topo-node topo-node-vpn" onclick="openTopologyModal('vpn','${p.id}')" style="cursor:pointer;border-color:${nodeBorder};box-shadow:${nodeShadow};width:100%;max-width:100%">
|
||
<div class="topo-node-icon" style="background:${iconBg};border:1px solid ${iconBorder};display:flex;align-items:center;justify-content:center;padding:6px">
|
||
<div style="transform:scale(1.25);display:flex;align-items:center;justify-content:center">${vpnLogo}</div>
|
||
</div>
|
||
<div class="topo-node-content" style="flex:1;min-width:0">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<strong style="color:var(--text);font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis" title="${pNameEsc}">VPN : ${pNameEsc}</strong>
|
||
${vpnBadgeHtml}
|
||
<span class="pill pill-green pill-no-dot" style="font-size:10px;padding:1px 6px">${t('status_connected', 'Connecté')}</span>
|
||
</div>
|
||
<div class="topo-node-sub" style="margin-top:4px;display:flex;align-items:center;gap:6px;flex-wrap:wrap">${pubIpHtml}</div>
|
||
<div class="muted" style="font-size:11px;margin-top:3px">${devRoutedText}</div>
|
||
</div>
|
||
<span class="dot" style="background:var(--green);box-shadow:0 0 10px rgba(50,213,131,.6)" title="${t('topo_tunnel_encrypted_ok', 'Tunnel chiffré opérationnel')}"></span>
|
||
</div>`;
|
||
}).join('');
|
||
}
|
||
}
|
||
|
||
// 3. Nœud AP
|
||
if (data.ap) {
|
||
const ssidEl = $('topoApSsid'); if (ssidEl) ssidEl.textContent = data.ap.ssid;
|
||
const apbEl = $('topoApBadge');
|
||
if (apbEl) {
|
||
apbEl.textContent = data.ap.active ? t('status_active', 'Actif') : t('status_inactive', 'Inactif');
|
||
apbEl.className = 'pill ' + (data.ap.active ? 'pill-green' : '');
|
||
}
|
||
const apIpEl = $('topoApIp');
|
||
const apIpDisp = (data.ap.ip === 'IP Pont LAN' || String(data.ap.ip).includes('Pont')) ? t('topo_ip_bridge_lan', 'IP Pont LAN') : data.ap.ip;
|
||
if (apIpEl) apIpEl.textContent = `${apIpDisp}/${data.ap.cidr || '24'} • ${t('topo_channel', 'Canal')} ${data.ap.channel} (${data.ap.band})`;
|
||
const apMetaEl = $('topoApMeta');
|
||
let apModeText = data.ap.mode || '';
|
||
if (data.ap.mode_key === 'bridge' || apModeText.includes('Bridge') || apModeText.includes('Pont')) {
|
||
apModeText = t('mode_bridge_label', 'Pont réseau (Bridge)');
|
||
} else if (data.ap.mode_key === 'nat' || apModeText.includes('Routeur') || apModeText.includes('NAT')) {
|
||
apModeText = t('mode_nat_label', 'Point d’accès (Routeur Wi-Fi)');
|
||
}
|
||
const actClients = t('topo_active_clients_count', '{n} client(s) actif(s)').replace('{n}', data.total_clients_count || 0);
|
||
if (apMetaEl) apMetaEl.textContent = `${data.ap.security} • ${apModeText} • ${actClients}`;
|
||
}
|
||
|
||
// 4. Grille des clients
|
||
const clientsGrid = $('topoClientsGrid');
|
||
const clients = data.clients || [];
|
||
if (clientsGrid) {
|
||
|
||
if (!clients.length) {
|
||
if (clientsGrid.dataset.macs !== 'empty') {
|
||
clientsGrid.dataset.macs = 'empty';
|
||
clientsGrid.innerHTML = `<div style="grid-column:1/-1;text-align:center;padding:36px 16px;background:var(--panel);border-radius:12px;border:1px dashed var(--line)">
|
||
<div style="font-size:32px;margin-bottom:8px">📡</div>
|
||
<strong style="font-size:15px;display:block">${t('topo_no_clients_title', "Aucun appareil connecté au point d'accès")}</strong>
|
||
<p class="muted" style="font-size:13px;max-width:440px;margin:6px auto 0">${t('topo_no_clients_desc', "Les équipements qui rejoignent le réseau Wi‑Fi s’afficheront automatiquement ici avec leur qualité de signal, IP et débits en temps réel.")}</p>
|
||
</div>`;
|
||
}
|
||
} else {
|
||
const currentMacsKey = clients.map(c => c.mac).sort().join(';');
|
||
if (clientsGrid.dataset.macs !== currentMacsKey) {
|
||
clientsGrid.dataset.macs = currentMacsKey;
|
||
clientsGrid.innerHTML = clients.map(c => {
|
||
const devType = c.device_type || 'generic';
|
||
const icon = getDeviceTypeIcon(devType);
|
||
const typeLabel = getDeviceTypeLabel(devType);
|
||
const nameEsc = String(c.name || t('client_unknown', 'Client inconnu')).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const ipEsc = String(c.ip || '—').replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const macEsc = String(c.mac || '—').replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const sigDbm = c.signal_dbm !== null && c.signal_dbm !== undefined ? c.signal_dbm : null;
|
||
|
||
let sigColor = '#ff6b6b';
|
||
let sigClass = 'active-red';
|
||
let barsCount = 1;
|
||
if (sigDbm !== null) {
|
||
if (sigDbm >= -50) { sigColor = 'var(--green)'; sigClass = 'active-green'; barsCount = 4; }
|
||
else if (sigDbm >= -60) { sigColor = '#68d391'; sigClass = 'active-green'; barsCount = 3; }
|
||
else if (sigDbm >= -70) { sigColor = '#f6ad55'; sigClass = 'active-yellow'; barsCount = 2; }
|
||
else { sigColor = 'var(--red)'; sigClass = 'active-red'; barsCount = 1; }
|
||
}
|
||
|
||
const barsHtml = [1, 2, 3, 4].map(b => `<span class="topo-signal-bar ${b <= barsCount ? sigClass : ''}" style="height:${b * 3}px"></span>`).join('');
|
||
|
||
const vpnBadgeTopo = renderTopoClientVpn(c);
|
||
|
||
const isVpnRouted = !!c.vpn_routed;
|
||
const linkColor = isVpnRouted ? 'var(--red)' : sigColor;
|
||
const cardBorder = isVpnRouted ? 'border-color:rgba(255,107,107,.45);box-shadow:0 0 10px rgba(255,107,107,.15);' : '';
|
||
|
||
return `<div class="topo-client-card" data-mac="${macEsc}" data-name="${nameEsc}" data-ip="${ipEsc}" data-link-color="${linkColor}" data-vpn-routed="${isVpnRouted}" style="${cardBorder}" onclick="openTopologyModal('client','${macEsc}')">
|
||
<div class="topo-client-header">
|
||
<div style="display:flex;align-items:center;gap:8px;min-width:0">
|
||
<div class="topo-client-type">${icon}</div>
|
||
<div style="min-width:0">
|
||
<div class="topo-client-name" title="${nameEsc}">${nameEsc}</div>
|
||
<div class="muted" style="font-size:11px">${typeLabel}</div>
|
||
</div>
|
||
</div>
|
||
<div style="display:flex;align-items:center;gap:6px">
|
||
<div class="topo-signal-bars">${barsHtml}</div>
|
||
<span class="topo-card-sig" style="font-size:11px;font-weight:700;color:${sigColor}">${sigDbm !== null ? sigDbm + ' dBm' : '—'}</span>
|
||
</div>
|
||
</div>
|
||
<div class="topo-client-body">
|
||
<div><span class="muted" style="font-size:10px">IP</span><br><code class="topo-card-ip" style="font-size:11px">${ipEsc}</code></div>
|
||
<div><span class="muted" style="font-size:10px">MAC</span><br><code style="font-size:10px">${macEsc}</code></div>
|
||
</div>
|
||
${vpnBadgeTopo}
|
||
<div class="topo-client-speeds">
|
||
<span class="topo-card-down" style="color:var(--blue)">↓ ${c.download_speed_str || '0 o/s'}</span>
|
||
<span class="topo-card-up" style="color:var(--green)">↑ ${c.upload_speed_str || '0 o/s'}</span>
|
||
</div>
|
||
<div class="topo-actions">
|
||
<button type="button" class="secondary" onclick="event.stopPropagation();openTopologyModal('client','${macEsc}')">${t('btn_details', '🔍 Détails')}</button>
|
||
<button type="button" class="secondary" style="color:var(--red)" onclick="event.stopPropagation();blockClient('${macEsc}',true)">${t('btn_block_action', '🚫 Bloquer')}</button>
|
||
</div>
|
||
</div>`;
|
||
}).join('');
|
||
} else {
|
||
// Même liste de clients : mise à jour en place SANS recréer le DOM
|
||
clients.forEach(c => {
|
||
const card = clientsGrid.querySelector(`.topo-client-card[data-mac="${c.mac}"]`);
|
||
if (!card) return;
|
||
const sigDbm = c.signal_dbm !== null && c.signal_dbm !== undefined ? c.signal_dbm : null;
|
||
let sigColor = '#ff6b6b';
|
||
let sigClass = 'active-red';
|
||
let barsCount = 1;
|
||
if (sigDbm !== null) {
|
||
if (sigDbm >= -50) { sigColor = 'var(--green)'; sigClass = 'active-green'; barsCount = 4; }
|
||
else if (sigDbm >= -60) { sigColor = '#68d391'; sigClass = 'active-green'; barsCount = 3; }
|
||
else if (sigDbm >= -70) { sigColor = '#f6ad55'; sigClass = 'active-yellow'; barsCount = 2; }
|
||
else { sigColor = 'var(--red)'; sigClass = 'active-red'; barsCount = 1; }
|
||
}
|
||
const isVpnRouted = !!c.vpn_routed;
|
||
const linkColor = isVpnRouted ? 'var(--red)' : sigColor;
|
||
card.dataset.linkColor = linkColor;
|
||
card.dataset.vpnRouted = isVpnRouted;
|
||
card.style.borderColor = isVpnRouted ? 'rgba(255,107,107,.45)' : '';
|
||
card.style.boxShadow = isVpnRouted ? '0 0 10px rgba(255,107,107,.15)' : '';
|
||
const sigEl = card.querySelector('.topo-card-sig');
|
||
if (sigEl) { sigEl.textContent = sigDbm !== null ? sigDbm + ' dBm' : '—'; sigEl.style.color = sigColor; }
|
||
const barsContainer = card.querySelector('.topo-signal-bars');
|
||
if (barsContainer) {
|
||
barsContainer.innerHTML = [1, 2, 3, 4].map(b => `<span class="topo-signal-bar ${b <= barsCount ? sigClass : ''}" style="height:${b * 3}px"></span>`).join('');
|
||
}
|
||
const downEl = card.querySelector('.topo-card-down');
|
||
if (downEl) downEl.textContent = '↓ ' + (c.download_speed_str || '0 o/s');
|
||
const upEl = card.querySelector('.topo-card-up');
|
||
if (upEl) upEl.textContent = '↑ ' + (c.upload_speed_str || '0 o/s');
|
||
const ipEl = card.querySelector('.topo-card-ip');
|
||
if (ipEl && c.ip) ipEl.textContent = c.ip;
|
||
const vpnEl = card.querySelector('.topo-card-vpn');
|
||
if (vpnEl) {
|
||
const vpnBadgeFresh = renderTopoClientVpn(c);
|
||
vpnEl.outerHTML = vpnBadgeFresh;
|
||
}
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
// 5. Synthèse Signal & Appareils
|
||
renderTopologyStats(data);
|
||
|
||
// 6. Dessin des lignes SVG
|
||
requestAnimationFrame(drawTopologySvgLines);
|
||
|
||
// 7. Réappliquer le filtre si présent
|
||
if (topologySearchQuery) {
|
||
filterTopologyNodes(topologySearchQuery);
|
||
}
|
||
|
||
// 8. Actualiser la modale de détails si ouverte
|
||
if (activeTopologyModal && $('topoDetailModal') && $('topoDetailModal').classList.contains('active')) {
|
||
updateTopologyModalContent(activeTopologyModal.type, activeTopologyModal.clientMac);
|
||
}
|
||
}
|
||
|
||
function renderTopologyStats(data) {
|
||
const clients = data.clients || [];
|
||
const total = clients.length;
|
||
|
||
// Signal
|
||
const sigBox = $('topoSignalStats');
|
||
if (sigBox) {
|
||
if (!total) {
|
||
sigBox.innerHTML = '<div class="muted" style="font-size:13px" data-i18n="topo_no_clients_desc">Aucun client connecté</div>';
|
||
} else {
|
||
let exc = 0, bon = 0, moy = 0, fai = 0;
|
||
clients.forEach(c => {
|
||
const s = c.signal_dbm;
|
||
if (s !== null && s !== undefined) {
|
||
if (s >= -50) exc++;
|
||
else if (s >= -60) bon++;
|
||
else if (s >= -70) moy++;
|
||
else fai++;
|
||
} else fai++;
|
||
});
|
||
sigBox.innerHTML = `
|
||
<div>
|
||
<div style="display:flex;justify-content:space-between;font-size:12px;margin-bottom:3px">
|
||
<span style="color:var(--green)">● ${t('signal_excellent', 'Excellent')}</span><strong>${exc} (${Math.round(exc / total * 100)}%)</strong>
|
||
</div>
|
||
<div class="topo-progress-track"><div class="topo-progress-fill" style="width:${Math.round(exc / total * 100)}%;background:var(--green)"></div></div>
|
||
</div>
|
||
<div>
|
||
<div style="display:flex;justify-content:space-between;font-size:12px;margin-bottom:3px">
|
||
<span style="color:#68d391">● ${t('signal_good', 'Bon')}</span><strong>${bon} (${Math.round(bon / total * 100)}%)</strong>
|
||
</div>
|
||
<div class="topo-progress-track"><div class="topo-progress-fill" style="width:${Math.round(bon / total * 100)}%;background:#68d391"></div></div>
|
||
</div>
|
||
<div>
|
||
<div style="display:flex;justify-content:space-between;font-size:12px;margin-bottom:3px">
|
||
<span style="color:#f6ad55">● ${t('signal_fair', 'Moyen')}</span><strong>${moy} (${Math.round(moy / total * 100)}%)</strong>
|
||
</div>
|
||
<div class="topo-progress-track"><div class="topo-progress-fill" style="width:${Math.round(moy / total * 100)}%;background:#f6ad55"></div></div>
|
||
</div>
|
||
<div>
|
||
<div style="display:flex;justify-content:space-between;font-size:12px;margin-bottom:3px">
|
||
<span style="color:var(--red)">● ${t('signal_weak', 'Faible')}</span><strong>${fai} (${Math.round(fai / total * 100)}%)</strong>
|
||
</div>
|
||
<div class="topo-progress-track"><div class="topo-progress-fill" style="width:${Math.round(fai / total * 100)}%;background:var(--red)"></div></div>
|
||
</div>`;
|
||
}
|
||
}
|
||
|
||
// Devices
|
||
const devBox = $('topoDeviceStats');
|
||
if (devBox) {
|
||
if (!total) {
|
||
devBox.innerHTML = '<div class="muted" style="font-size:13px" data-i18n="topo_no_clients_desc">Aucun client connecté</div>';
|
||
} else {
|
||
const counts = {};
|
||
clients.forEach(c => {
|
||
const t = c.device_type || 'generic';
|
||
counts[t] = (counts[t] || 0) + 1;
|
||
});
|
||
devBox.innerHTML = Object.entries(counts).map(([type, cnt]) => {
|
||
const label = getDeviceTypeLabel(type, true);
|
||
const pct = Math.round(cnt / total * 100);
|
||
return `<div>
|
||
<div style="display:flex;justify-content:space-between;font-size:12px;margin-bottom:3px">
|
||
<span>${label}</span><strong>${cnt} (${pct}%)</strong>
|
||
</div>
|
||
<div class="topo-progress-track"><div class="topo-progress-fill" style="width:${pct}%;background:var(--blue)"></div></div>
|
||
</div>`;
|
||
}).join('');
|
||
}
|
||
}
|
||
|
||
// Live speeds & blocked
|
||
if ($('topoLiveDown')) $('topoLiveDown').textContent = data.total_download_str || '0 o/s';
|
||
if ($('topoLiveUp')) $('topoLiveUp').textContent = data.total_upload_str || '0 o/s';
|
||
if ($('topoBlockedCount')) $('topoBlockedCount').textContent = data.blocked_count || 0;
|
||
}
|
||
|
||
function drawTopologySvgLines() {
|
||
const svg = $('topoSvgLines');
|
||
const apNode = $('topoNodeAp');
|
||
const clientsContainer = $('topoClientsGrid');
|
||
if (!svg || !apNode || !clientsContainer) return;
|
||
|
||
const cards = Array.from(clientsContainer.querySelectorAll('.topo-client-card')).filter(c => c.style.display !== 'none');
|
||
|
||
const mapCard = svg.parentElement;
|
||
const mapRect = mapCard.getBoundingClientRect();
|
||
const apRect = apNode.getBoundingClientRect();
|
||
|
||
const apX = Math.round(apRect.left + apRect.width / 2 - mapRect.left);
|
||
const apY = Math.round(apRect.bottom - mapRect.top);
|
||
|
||
// Nœuds centraux sur l'AP (persistant dans le DOM pour ne jamais réinitialiser les animations)
|
||
let apDot = svg.querySelector('.topo-ap-center-dot');
|
||
let apRing = svg.querySelector('.topo-ap-center-ring');
|
||
if (!apDot) {
|
||
apDot = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
|
||
apDot.setAttribute('class', 'topo-ap-center-dot');
|
||
apDot.setAttribute('r', '5');
|
||
apDot.setAttribute('fill', 'var(--blue)');
|
||
svg.appendChild(apDot);
|
||
}
|
||
apDot.setAttribute('cx', apX);
|
||
apDot.setAttribute('cy', apY);
|
||
|
||
if (!apRing) {
|
||
apRing = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
|
||
apRing.setAttribute('class', 'topo-ap-center-ring topo-end-dot');
|
||
apRing.setAttribute('r', '8');
|
||
apRing.setAttribute('fill', 'none');
|
||
apRing.setAttribute('stroke', 'var(--blue)');
|
||
apRing.setAttribute('stroke-width', '1.5');
|
||
svg.appendChild(apRing);
|
||
}
|
||
apRing.setAttribute('cx', apX);
|
||
apRing.setAttribute('cy', apY);
|
||
|
||
// Liaisons vers les Nœuds Profils VPN actifs (à gauche, en rouge) et Passerelle WAN (à droite, en bleu)
|
||
const vpnNodes = Array.from(document.querySelectorAll('.topo-node-vpn'));
|
||
const currentActiveVpnIds = new Set();
|
||
const apTopX = Math.round(apRect.left + apRect.width / 2 - mapRect.left);
|
||
const apTopY = Math.round(apRect.top - mapRect.top);
|
||
|
||
// 1. Connexions vers les VPN actifs (gauche)
|
||
const sortedVpns = vpnNodes.map(vNode => {
|
||
const vpnId = vNode.id.replace('topoNodeVpn_', '');
|
||
const vRect = vNode.getBoundingClientRect();
|
||
return {
|
||
node: vNode,
|
||
id: vpnId,
|
||
rect: vRect,
|
||
x: Math.round(vRect.left + vRect.width / 2 - mapRect.left),
|
||
yBottom: Math.round(vRect.bottom - mapRect.top),
|
||
yTop: Math.round(vRect.top - mapRect.top)
|
||
};
|
||
}).filter(v => !!v.id).sort((a, b) => b.yBottom - a.yBottom);
|
||
|
||
sortedVpns.forEach((vObj, idx) => {
|
||
currentActiveVpnIds.add(vObj.id);
|
||
const vColor = 'var(--red)';
|
||
let dVpn = '';
|
||
|
||
if (idx === 0) {
|
||
const apTopVpnX = Math.round(apTopX - 35);
|
||
const midVpnY = Math.round(apTopY + (vObj.yBottom - apTopY) * 0.5);
|
||
dVpn = `M ${apTopVpnX} ${apTopY} C ${apTopVpnX} ${midVpnY}, ${vObj.x} ${midVpnY}, ${vObj.x} ${vObj.yBottom}`;
|
||
} else {
|
||
const prev = sortedVpns[idx - 1];
|
||
dVpn = `M ${prev.x} ${prev.yTop} L ${vObj.x} ${vObj.yBottom}`;
|
||
}
|
||
|
||
let vGlow = svg.querySelector(`path.topo-line-glow[data-vpn-id="${vObj.id}"]`);
|
||
if (!vGlow) {
|
||
vGlow = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||
vGlow.setAttribute('class', 'topo-line-glow');
|
||
vGlow.setAttribute('data-vpn-id', vObj.id);
|
||
vGlow.setAttribute('fill', 'none');
|
||
vGlow.setAttribute('stroke', vColor);
|
||
vGlow.setAttribute('stroke-width', '5');
|
||
vGlow.setAttribute('opacity', '0.35');
|
||
svg.insertBefore(vGlow, apDot);
|
||
}
|
||
if (vGlow.getAttribute('d') !== dVpn) vGlow.setAttribute('d', dVpn);
|
||
|
||
let vFlow = svg.querySelector(`path.topo-line-flow[data-vpn-id="${vObj.id}"]`);
|
||
if (!vFlow) {
|
||
vFlow = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||
vFlow.setAttribute('class', 'topo-line-flow');
|
||
vFlow.setAttribute('data-vpn-id', vObj.id);
|
||
vFlow.setAttribute('fill', 'none');
|
||
vFlow.setAttribute('stroke', vColor);
|
||
vFlow.setAttribute('stroke-width', '2.8');
|
||
vFlow.setAttribute('opacity', '0.95');
|
||
svg.insertBefore(vFlow, apDot);
|
||
}
|
||
if (vFlow.getAttribute('d') !== dVpn) vFlow.setAttribute('d', dVpn);
|
||
|
||
let vDot = svg.querySelector(`circle.topo-end-dot[data-vpn-id="${vObj.id}"]`);
|
||
if (!vDot) {
|
||
vDot = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
|
||
vDot.setAttribute('class', 'topo-end-dot');
|
||
vDot.setAttribute('data-vpn-id', vObj.id);
|
||
vDot.setAttribute('r', '4');
|
||
vDot.setAttribute('fill', vColor);
|
||
svg.appendChild(vDot);
|
||
}
|
||
vDot.setAttribute('cx', vObj.x);
|
||
vDot.setAttribute('cy', vObj.yBottom);
|
||
});
|
||
|
||
svg.querySelectorAll('[data-vpn-id]').forEach(el => {
|
||
if (!currentActiveVpnIds.has(el.getAttribute('data-vpn-id'))) {
|
||
el.remove();
|
||
}
|
||
});
|
||
|
||
// 2. Connexion vers la Passerelle WAN à droite (quand des VPN sont actifs)
|
||
const wanNode = $('topoNodeWan');
|
||
if (vpnNodes.length > 0 && wanNode) {
|
||
const wanRect = wanNode.getBoundingClientRect();
|
||
const wX = Math.round(wanRect.left + wanRect.width / 2 - mapRect.left);
|
||
const wY = Math.round(wanRect.bottom - mapRect.top);
|
||
const apTopWanX = Math.round(apTopX + 35);
|
||
const midWanY = Math.round(apTopY + (wY - apTopY) * 0.5);
|
||
const dWan = `M ${apTopWanX} ${apTopY} C ${apTopWanX} ${midWanY}, ${wX} ${midWanY}, ${wX} ${wY}`;
|
||
|
||
let wGlow = svg.querySelector('path.topo-line-glow[data-wan-link="1"]');
|
||
if (!wGlow) {
|
||
wGlow = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||
wGlow.setAttribute('class', 'topo-line-glow');
|
||
wGlow.setAttribute('data-wan-link', '1');
|
||
wGlow.setAttribute('fill', 'none');
|
||
wGlow.setAttribute('stroke', 'var(--blue)');
|
||
wGlow.setAttribute('stroke-width', '5');
|
||
wGlow.setAttribute('opacity', '0.35');
|
||
svg.insertBefore(wGlow, apDot);
|
||
}
|
||
if (wGlow.getAttribute('d') !== dWan) wGlow.setAttribute('d', dWan);
|
||
|
||
let wFlow = svg.querySelector('path.topo-line-flow[data-wan-link="1"]');
|
||
if (!wFlow) {
|
||
wFlow = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||
wFlow.setAttribute('class', 'topo-line-flow');
|
||
wFlow.setAttribute('data-wan-link', '1');
|
||
wFlow.setAttribute('fill', 'none');
|
||
wFlow.setAttribute('stroke', 'var(--blue)');
|
||
wFlow.setAttribute('stroke-width', '2.8');
|
||
wFlow.setAttribute('opacity', '0.95');
|
||
svg.insertBefore(wFlow, apDot);
|
||
}
|
||
if (wFlow.getAttribute('d') !== dWan) wFlow.setAttribute('d', dWan);
|
||
|
||
let wDot = svg.querySelector('circle.topo-end-dot[data-wan-link="1"]');
|
||
if (!wDot) {
|
||
wDot = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
|
||
wDot.setAttribute('class', 'topo-end-dot');
|
||
wDot.setAttribute('data-wan-link', '1');
|
||
wDot.setAttribute('r', '4');
|
||
wDot.setAttribute('fill', 'var(--blue)');
|
||
svg.appendChild(wDot);
|
||
}
|
||
wDot.setAttribute('cx', wX);
|
||
wDot.setAttribute('cy', wY);
|
||
} else {
|
||
svg.querySelectorAll('[data-wan-link]').forEach(el => el.remove());
|
||
}
|
||
|
||
const currentActiveMacs = new Set();
|
||
|
||
cards.forEach(card => {
|
||
const mac = card.dataset.mac;
|
||
if (!mac) return;
|
||
currentActiveMacs.add(mac);
|
||
|
||
const cRect = card.getBoundingClientRect();
|
||
const cX = Math.round(cRect.left + cRect.width / 2 - mapRect.left);
|
||
const cY = Math.round(cRect.top - mapRect.top);
|
||
const midY = Math.round(apY + (cY - apY) * 0.45);
|
||
const isVpn = card.dataset.vpnRouted === 'true';
|
||
const color = isVpn ? 'var(--red)' : (card.dataset.linkColor || 'var(--blue)');
|
||
const d = `M ${apX} ${apY} C ${apX} ${midY}, ${cX} ${midY}, ${cX} ${cY}`;
|
||
|
||
// 1. Halo lumineux persistant
|
||
let glow = svg.querySelector(`path.topo-line-glow[data-mac="${mac}"]`);
|
||
if (!glow) {
|
||
glow = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||
glow.setAttribute('class', 'topo-line-glow');
|
||
glow.setAttribute('data-mac', mac);
|
||
glow.setAttribute('fill', 'none');
|
||
svg.insertBefore(glow, apDot);
|
||
}
|
||
if (glow.getAttribute('d') !== d) glow.setAttribute('d', d);
|
||
if (glow.getAttribute('stroke') !== color) glow.setAttribute('stroke', color);
|
||
glow.setAttribute('stroke-width', isVpn ? '4.5' : '3');
|
||
glow.setAttribute('opacity', isVpn ? '0.38' : '0.25');
|
||
|
||
// 2. Ligne animée en flux continu (CONSERVÉE dans le DOM pour que l'animation ne redémarre jamais de zéro)
|
||
let flow = svg.querySelector(`path.topo-line-flow[data-mac="${mac}"]`);
|
||
if (!flow) {
|
||
flow = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||
flow.setAttribute('class', 'topo-line-flow');
|
||
flow.setAttribute('data-mac', mac);
|
||
flow.setAttribute('fill', 'none');
|
||
svg.insertBefore(flow, apDot);
|
||
}
|
||
if (flow.getAttribute('d') !== d) flow.setAttribute('d', d);
|
||
if (flow.getAttribute('stroke') !== color) flow.setAttribute('stroke', color);
|
||
flow.setAttribute('stroke-width', isVpn ? '2.8' : '2.2');
|
||
flow.setAttribute('opacity', isVpn ? '0.95' : '0.85');
|
||
|
||
// 3. Point d'arrivée pulsant
|
||
let dot = svg.querySelector(`circle.topo-end-dot[data-mac="${mac}"]`);
|
||
if (!dot) {
|
||
dot = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
|
||
dot.setAttribute('class', 'topo-end-dot');
|
||
dot.setAttribute('data-mac', mac);
|
||
svg.appendChild(dot);
|
||
}
|
||
dot.setAttribute('cx', cX);
|
||
dot.setAttribute('cy', cY);
|
||
dot.setAttribute('r', isVpn ? '4.5' : '3.5');
|
||
dot.setAttribute('fill', color);
|
||
});
|
||
|
||
// Supprimer les chemins des appareils déconnectés
|
||
svg.querySelectorAll('[data-mac]').forEach(el => {
|
||
if (!currentActiveMacs.has(el.getAttribute('data-mac'))) {
|
||
el.remove();
|
||
}
|
||
});
|
||
}
|
||
|
||
function filterTopologyNodes(query) {
|
||
topologySearchQuery = (query || '').toLowerCase().trim();
|
||
const cards = document.querySelectorAll('.topo-client-card');
|
||
cards.forEach(card => {
|
||
const name = (card.dataset.name || '').toLowerCase();
|
||
const ip = (card.dataset.ip || '').toLowerCase();
|
||
const mac = (card.dataset.mac || '').toLowerCase();
|
||
const match = !topologySearchQuery || name.includes(topologySearchQuery) || ip.includes(topologySearchQuery) || mac.includes(topologySearchQuery);
|
||
card.style.display = match ? 'flex' : 'none';
|
||
});
|
||
drawTopologySvgLines();
|
||
}
|
||
|
||
let activeTopologyModal = null;
|
||
|
||
function openTopologyModal(type, clientMac) {
|
||
activeTopologyModal = { type, clientMac };
|
||
updateTopologyModalContent(type, clientMac);
|
||
const modal = $('topoDetailModal');
|
||
if (modal) modal.classList.add('active');
|
||
}
|
||
|
||
function closeTopologyModal() {
|
||
activeTopologyModal = null;
|
||
const modal = $('topoDetailModal');
|
||
if (modal) modal.classList.remove('active');
|
||
}
|
||
|
||
/* Menu et Export de la topologie en Image (PNG / JPG) */
|
||
function toggleTopoExportMenu(e) {
|
||
if (e) e.stopPropagation();
|
||
const m = $('topoExportMenu');
|
||
if (m) m.style.display = (m.style.display === 'block') ? 'none' : 'block';
|
||
}
|
||
|
||
function closeTopoExportMenu() {
|
||
const m = $('topoExportMenu');
|
||
if (m) m.style.display = 'none';
|
||
}
|
||
|
||
document.addEventListener('click', e => {
|
||
if (!e.target.closest('#topoExportBtn') && !e.target.closest('#topoExportMenu')) {
|
||
closeTopoExportMenu();
|
||
}
|
||
});
|
||
|
||
async function exportTopologyImage(format = 'png') {
|
||
closeTopoExportMenu();
|
||
const isJpg = format.toLowerCase() === 'jpg' || format.toLowerCase() === 'jpeg';
|
||
const ext = isJpg ? 'jpg' : 'png';
|
||
const mimeType = isJpg ? 'image/jpeg' : 'image/png';
|
||
const filename = 'topologie_reseau_' + (new Date().toISOString().slice(0, 19).replace(/[:T]/g, '_')) + '.' + ext;
|
||
|
||
let canvas = null;
|
||
|
||
// 1. Moteur Canvas dédié haute résolution (Recommandé : vectoriel net 2x, liaison WAN & Wi-Fi parfaites, 100% autonome et hors-ligne)
|
||
if (topologyDataCache) {
|
||
try {
|
||
canvas = renderTopologyToCanvas(topologyDataCache);
|
||
} catch (err) {
|
||
console.warn('renderTopologyToCanvas a échoué:', err);
|
||
}
|
||
}
|
||
|
||
// 2. Repli si html2canvas disponible
|
||
if (!canvas && window.html2canvas) {
|
||
try {
|
||
const mapCard = document.querySelector('.topo-map-card');
|
||
if (mapCard) {
|
||
const currentTheme = document.documentElement.dataset.theme || 'dark';
|
||
const isMacosDark = currentTheme === 'macos' && (document.documentElement.dataset.macosMode === 'dark' || (typeof themeMedia !== 'undefined' && !themeMedia.matches));
|
||
let html2canvasBg = '#071326';
|
||
if (currentTheme === 'hacker') html2canvasBg = '#000000';
|
||
else if (currentTheme === 'futuristic') html2canvasBg = '#050814';
|
||
else if (currentTheme === 'winxp') html2canvasBg = '#ece9d8';
|
||
else if (currentTheme === 'light') html2canvasBg = '#f2f5fa';
|
||
else if (currentTheme === 'macos') html2canvasBg = isMacosDark ? '#1c1c1e' : '#f5f5f7';
|
||
else html2canvasBg = '#071326';
|
||
|
||
canvas = await html2canvas(mapCard, {
|
||
scale: 2,
|
||
useCORS: true,
|
||
backgroundColor: html2canvasBg,
|
||
logging: false
|
||
});
|
||
}
|
||
} catch (err) {
|
||
console.warn('html2canvas a échoué:', err);
|
||
}
|
||
}
|
||
|
||
// 3. Si aucun canvas et cache non chargé, charger les données puis rendre
|
||
if (!canvas && !topologyDataCache) {
|
||
try {
|
||
await loadTopology();
|
||
if (topologyDataCache) {
|
||
canvas = renderTopologyToCanvas(topologyDataCache);
|
||
}
|
||
} catch (err) {
|
||
console.warn('loadTopology avant export a échoué:', err);
|
||
}
|
||
}
|
||
|
||
if (!canvas) {
|
||
alert('Impossible de générer l’image de la topologie.');
|
||
return;
|
||
}
|
||
|
||
const dataUrl = canvas.toDataURL(mimeType, isJpg ? 0.92 : undefined);
|
||
const link = document.createElement('a');
|
||
link.download = filename;
|
||
link.href = dataUrl;
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
document.body.removeChild(link);
|
||
}
|
||
|
||
function renderTopologyToCanvas(data) {
|
||
if (!data) return null;
|
||
|
||
let theme = document.documentElement.dataset.theme || 'dark';
|
||
if (theme === 'auto') {
|
||
theme = (typeof themeMedia !== 'undefined' && themeMedia.matches) ? 'light' : 'dark';
|
||
}
|
||
|
||
let bg, cardBg, nodeBg, textColor, mutedColor, lineColor, blue, green, red, pillBgGreen;
|
||
let fontFamily = 'system-ui, -apple-system, sans-serif';
|
||
let fontMono = 'ui-monospace, monospace';
|
||
|
||
if (theme === 'winxp') {
|
||
bg = '#225ad9';
|
||
cardBg = '#ece9d8';
|
||
nodeBg = '#ffffff';
|
||
textColor = '#000000';
|
||
mutedColor = '#49546a';
|
||
lineColor = '#7f9db9';
|
||
blue = '#0055ea';
|
||
green = '#2e8b22';
|
||
red = '#cc1111';
|
||
pillBgGreen = 'rgba(46, 139, 34, 0.16)';
|
||
fontFamily = 'Tahoma, "Segoe UI", system-ui, sans-serif';
|
||
fontMono = '"Lucida Console", monospace';
|
||
} else if (theme === 'hacker') {
|
||
bg = '#000000';
|
||
cardBg = '#050d05';
|
||
nodeBg = '#091709';
|
||
textColor = '#00ff41';
|
||
mutedColor = '#00aa2b';
|
||
lineColor = 'rgba(0, 255, 65, 0.45)';
|
||
blue = '#00ff41';
|
||
green = '#00ff41';
|
||
red = '#ff2244';
|
||
pillBgGreen = 'rgba(0, 255, 65, 0.2)';
|
||
fontFamily = '"Courier New", "Fira Code", monospace';
|
||
fontMono = '"Courier New", "Fira Code", monospace';
|
||
} else if (theme === 'futuristic') {
|
||
bg = '#050814';
|
||
cardBg = '#0b1124';
|
||
nodeBg = '#101935';
|
||
textColor = '#e6f6ff';
|
||
mutedColor = '#7890b8';
|
||
lineColor = 'rgba(0, 240, 255, 0.35)';
|
||
blue = '#00f0ff';
|
||
green = '#05ffa1';
|
||
red = '#ff2a6d';
|
||
pillBgGreen = 'rgba(5, 255, 161, 0.2)';
|
||
fontFamily = 'system-ui, -apple-system, sans-serif';
|
||
fontMono = 'ui-monospace, monospace';
|
||
} else if (theme === 'macos') {
|
||
const isMacosDark = document.documentElement.dataset.macosMode === 'dark' || (typeof themeMedia !== 'undefined' && !themeMedia.matches);
|
||
if (isMacosDark) {
|
||
bg = '#1c1c1e';
|
||
cardBg = '#28282a';
|
||
nodeBg = '#323236';
|
||
textColor = '#f5f5f7';
|
||
mutedColor = '#98989d';
|
||
lineColor = 'rgba(255, 255, 255, 0.14)';
|
||
blue = '#0a84ff';
|
||
green = '#32d74b';
|
||
red = '#ff453a';
|
||
pillBgGreen = 'rgba(50, 215, 75, 0.2)';
|
||
} else {
|
||
bg = '#f5f5f7';
|
||
cardBg = '#ffffff';
|
||
nodeBg = '#f0f2f5';
|
||
textColor = '#1d1d1f';
|
||
mutedColor = '#86868b';
|
||
lineColor = '#e1e4e8';
|
||
blue = '#0071e3';
|
||
green = '#34c759';
|
||
red = '#ff3b30';
|
||
pillBgGreen = 'rgba(52, 199, 89, 0.18)';
|
||
}
|
||
fontFamily = '-apple-system, BlinkMacSystemFont, "SF Pro Text", "Helvetica Neue", sans-serif';
|
||
fontMono = '"SF Mono", Menlo, monospace';
|
||
} else if (theme === 'light') {
|
||
bg = '#f2f5fa';
|
||
cardBg = '#ffffff';
|
||
nodeBg = '#e9eef7';
|
||
textColor = '#15203a';
|
||
mutedColor = '#5b6b8c';
|
||
lineColor = '#d2dcec';
|
||
blue = '#1e6ef0';
|
||
green = '#13a06a';
|
||
red = '#e53935';
|
||
pillBgGreen = 'rgba(19, 160, 106, 0.16)';
|
||
fontFamily = 'system-ui, -apple-system, sans-serif';
|
||
fontMono = 'ui-monospace, monospace';
|
||
} else {
|
||
// 'dark'
|
||
bg = '#071326';
|
||
cardBg = '#0d1d36';
|
||
nodeBg = '#132746';
|
||
textColor = '#eef4ff';
|
||
mutedColor = '#9aa8c5';
|
||
lineColor = '#223c68';
|
||
blue = '#5ca7ff';
|
||
green = '#32d583';
|
||
red = '#ff6b6b';
|
||
pillBgGreen = 'rgba(50, 213, 131, 0.2)';
|
||
fontFamily = 'system-ui, -apple-system, sans-serif';
|
||
fontMono = 'ui-monospace, monospace';
|
||
}
|
||
|
||
const clients = data.clients || [];
|
||
const numClients = clients.length;
|
||
const cols = numClients >= 3 ? 3 : (numClients === 2 ? 2 : 1);
|
||
const rows = numClients > 0 ? Math.ceil(numClients / cols) : 1;
|
||
const cardW = Math.floor((1100 - 80 - (cols - 1) * 20) / cols);
|
||
const cardH = 155;
|
||
const yStart = 425;
|
||
const width = 1100;
|
||
const height = Math.max(700, yStart + rows * (cardH + 20) + 70);
|
||
|
||
const canvas = document.createElement('canvas');
|
||
canvas.width = width * 2;
|
||
canvas.height = height * 2;
|
||
const ctx = canvas.getContext('2d');
|
||
ctx.scale(2, 2);
|
||
|
||
function roundRect(x, y, w, h, r) {
|
||
ctx.beginPath();
|
||
ctx.moveTo(x + r, y);
|
||
ctx.arcTo(x + w, y, x + w, y + h, r);
|
||
ctx.arcTo(x + w, y + h, x, y + h, r);
|
||
ctx.arcTo(x, y + h, x, y, r);
|
||
ctx.arcTo(x, y, x + w, y, r);
|
||
ctx.closePath();
|
||
}
|
||
|
||
// 1. Fond principal
|
||
ctx.fillStyle = bg;
|
||
ctx.fillRect(0, 0, width, height);
|
||
|
||
// 2. Cadre carte
|
||
roundRect(20, 20, width - 40, height - 40, 16);
|
||
ctx.fillStyle = cardBg;
|
||
ctx.fill();
|
||
ctx.strokeStyle = lineColor;
|
||
ctx.lineWidth = 1;
|
||
ctx.stroke();
|
||
|
||
// 3. Titre & En-tête
|
||
ctx.fillStyle = blue;
|
||
ctx.font = 'bold 22px ' + fontFamily;
|
||
ctx.fillText('TOPOLOGIE DU RÉSEAU WI‑FI', 44, 58);
|
||
|
||
ctx.fillStyle = mutedColor;
|
||
ctx.font = '13px ' + fontFamily;
|
||
const dateStr = new Date().toLocaleString('fr-FR');
|
||
ctx.fillText(`AP Manageur ${APP_VERSION} • SSID: ${(data.ap && data.ap.ssid) || 'AP Wi-Fi'} • ${data.total_clients_count || 0} appareil(s) connecté(s) • ${dateStr}`, 44, 80);
|
||
|
||
// 4. Nœud WAN & Nœud VPN
|
||
const activeVpns = (data.vpn_profiles || []).filter(p => p.connected);
|
||
const wanY = 115, wanH = 60, apY = 240;
|
||
|
||
if (activeVpns.length > 0) {
|
||
const primaryVpn = activeVpns[0];
|
||
const vpnProto = primaryVpn.type === 'wireguard' ? 'WireGuard' : 'OpenVPN';
|
||
const vpnProtoShort = primaryVpn.type === 'wireguard' ? 'WG' : 'OVPN';
|
||
const countryTag = (primaryVpn.public_ip_geo && primaryVpn.public_ip_geo.code) ? `[${primaryVpn.public_ip_geo.code}] ` : '';
|
||
// Nœud VPN à gauche
|
||
const vpnX = width / 2 - 340, vpnW = 310;
|
||
roundRect(vpnX, wanY, vpnW, wanH, 12);
|
||
ctx.fillStyle = nodeBg; ctx.fill(); ctx.strokeStyle = red; ctx.lineWidth = 1.5; ctx.stroke();
|
||
ctx.font = '22px ' + fontFamily; ctx.fillText(primaryVpn.type === 'wireguard' ? '🐉' : '🔒', vpnX + 16, wanY + 40);
|
||
ctx.fillStyle = red; ctx.font = 'bold 15px ' + fontFamily;
|
||
let vpnTitle = `[${vpnProtoShort}] ${primaryVpn.name}`;
|
||
if (vpnTitle.length > 22) vpnTitle = vpnTitle.slice(0, 21) + '…';
|
||
ctx.fillText(vpnTitle, vpnX + 54, wanY + 28);
|
||
ctx.fillStyle = mutedColor; ctx.font = '12px ' + fontMono;
|
||
ctx.fillText(primaryVpn.public_ip ? `IP : ${countryTag}${primaryVpn.public_ip}` : `Iface : ${primaryVpn.iface}`, vpnX + 54, wanY + 48);
|
||
ctx.beginPath(); ctx.arc(vpnX + vpnW - 20, wanY + 30, 5, 0, Math.PI * 2); ctx.fillStyle = green; ctx.fill();
|
||
|
||
// Passerelle WAN à droite
|
||
const wanX = width / 2 + 30, wanW = 310;
|
||
roundRect(wanX, wanY, wanW, wanH, 12);
|
||
ctx.fillStyle = nodeBg; ctx.fill(); ctx.strokeStyle = lineColor; ctx.lineWidth = 1; ctx.stroke();
|
||
ctx.font = '24px ' + fontFamily; ctx.fillText('🌐', wanX + 16, wanY + 40);
|
||
ctx.fillStyle = textColor; ctx.font = 'bold 15px ' + fontFamily; ctx.fillText('Passerelle Internet', wanX + 54, wanY + 28);
|
||
ctx.fillStyle = mutedColor; ctx.font = '13px ' + fontMono;
|
||
ctx.fillText(`${(data.internet && data.internet.gateway_ip) || '192.168.1.1'} (${(data.internet && data.internet.interface) || 'WAN'})`, wanX + 54, wanY + 48);
|
||
ctx.beginPath(); ctx.arc(wanX + wanW - 20, wanY + 30, 5, 0, Math.PI * 2); ctx.fillStyle = green; ctx.fill();
|
||
|
||
// Liaison VPN -> AP à gauche
|
||
const wanBottomY = wanY + wanH;
|
||
ctx.strokeStyle = red; ctx.lineWidth = 3.5;
|
||
ctx.beginPath(); ctx.moveTo(vpnX + vpnW / 2, wanBottomY); ctx.lineTo(width / 2 - 50, apY); ctx.stroke();
|
||
|
||
// Liaison WAN -> AP (Filaire) à droite
|
||
ctx.strokeStyle = blue; ctx.lineWidth = 3;
|
||
ctx.beginPath(); ctx.moveTo(wanX + wanW / 2, wanBottomY); ctx.lineTo(width / 2 + 50, apY); ctx.stroke();
|
||
|
||
// Badge central Liaison VPN (gauche)
|
||
roundRect(vpnX + vpnW / 2 - 60, wanBottomY + 20, 120, 20, 10);
|
||
ctx.fillStyle = cardBg; ctx.fill(); ctx.strokeStyle = red; ctx.lineWidth = 1; ctx.stroke();
|
||
ctx.fillStyle = red; ctx.font = 'bold 10px ' + fontFamily; ctx.textAlign = 'center';
|
||
ctx.fillText(`🛡️ ${vpnProto}`, vpnX + vpnW / 2, wanBottomY + 34); ctx.textAlign = 'left';
|
||
|
||
// Badge central Liaison WAN (droite)
|
||
roundRect(wanX + wanW / 2 - 55, wanBottomY + 20, 110, 20, 10);
|
||
ctx.fillStyle = cardBg; ctx.fill(); ctx.strokeStyle = blue; ctx.lineWidth = 1; ctx.stroke();
|
||
ctx.fillStyle = blue; ctx.font = 'bold 10px ' + fontFamily; ctx.textAlign = 'center';
|
||
ctx.fillText('⚡ WAN Direct', wanX + wanW / 2, wanBottomY + 34); ctx.textAlign = 'left';
|
||
|
||
} else {
|
||
// Nœud WAN seul (Pas de VPN actif)
|
||
const wanX = width / 2 - 160, wanW = 320;
|
||
roundRect(wanX, wanY, wanW, wanH, 12);
|
||
ctx.fillStyle = nodeBg; ctx.fill(); ctx.strokeStyle = lineColor; ctx.lineWidth = 1; ctx.stroke();
|
||
ctx.font = '24px ' + fontFamily; ctx.fillText('🌐', wanX + 16, wanY + 40);
|
||
ctx.fillStyle = textColor; ctx.font = 'bold 15px ' + fontFamily; ctx.fillText('Passerelle Internet', wanX + 54, wanY + 28);
|
||
ctx.fillStyle = mutedColor; ctx.font = '13px ' + fontMono;
|
||
ctx.fillText(`${(data.internet && data.internet.gateway_ip) || '192.168.1.1'} (${(data.internet && data.internet.interface) || 'WAN'})`, wanX + 54, wanY + 48);
|
||
ctx.beginPath(); ctx.arc(wanX + wanW - 24, wanY + 30, 5, 0, Math.PI * 2); ctx.fillStyle = green; ctx.fill();
|
||
|
||
const wanBottomY = wanY + wanH; const linkCenterX = width / 2; const wanLinkGap = 65;
|
||
ctx.strokeStyle = blue; ctx.lineWidth = 3.5;
|
||
ctx.beginPath(); ctx.moveTo(linkCenterX, wanBottomY); ctx.lineTo(linkCenterX, apY); ctx.stroke();
|
||
const badgeW = 150, badgeH = 22; const badgeY = wanBottomY + Math.round((wanLinkGap - badgeH) / 2);
|
||
roundRect(linkCenterX - badgeW / 2, badgeY, badgeW, badgeH, 11);
|
||
ctx.fillStyle = cardBg; ctx.fill(); ctx.strokeStyle = blue; ctx.lineWidth = 1.5; ctx.stroke();
|
||
ctx.fillStyle = blue; ctx.font = 'bold 11px ' + fontFamily; ctx.textAlign = 'center';
|
||
ctx.fillText('⚡ Liaison Filaire / WAN', linkCenterX, badgeY + 15); ctx.textAlign = 'left';
|
||
}
|
||
|
||
// 6. Nœud AP (Point d'accès / Bridge)
|
||
// Exactement les mêmes couleurs et bordures que la Passerelle Internet (nodeBg & lineColor)
|
||
const apX = width / 2 - 180, apW = 360, apH = 75;
|
||
roundRect(apX, apY, apW, apH, 14);
|
||
ctx.fillStyle = nodeBg;
|
||
ctx.fill();
|
||
ctx.strokeStyle = lineColor;
|
||
ctx.lineWidth = 1;
|
||
ctx.stroke();
|
||
|
||
ctx.font = '28px ' + fontFamily;
|
||
ctx.fillText('📡', apX + 18, apY + 48);
|
||
|
||
ctx.fillStyle = textColor;
|
||
ctx.font = 'bold 16px ' + fontFamily;
|
||
const apSsid = (data.ap && data.ap.ssid) || 'AP Wi-Fi';
|
||
ctx.fillText(apSsid, apX + 60, apY + 30);
|
||
|
||
// Badge actif
|
||
const ssidWidth = ctx.measureText(apSsid).width;
|
||
roundRect(apX + 60 + ssidWidth + 10, apY + 16, 50, 18, 9);
|
||
ctx.fillStyle = pillBgGreen;
|
||
ctx.fill();
|
||
ctx.fillStyle = green;
|
||
ctx.font = 'bold 11px ' + fontFamily;
|
||
ctx.fillText('Actif', apX + 60 + ssidWidth + 22, apY + 29);
|
||
|
||
ctx.fillStyle = mutedColor;
|
||
ctx.font = '13px ' + fontMono;
|
||
const apIpStr = (data.ap && data.ap.ip) ? `${data.ap.ip}/${data.ap.cidr || '24'} • Canal ${data.ap.channel} (${data.ap.band})` : '10.42.0.1/24 • Canal 6';
|
||
ctx.fillText(apIpStr, apX + 60, apY + 50);
|
||
ctx.font = '11px ' + fontFamily;
|
||
const apMetaStr = `${(data.ap && data.ap.security) || 'WPA2'} • ${(data.ap && data.ap.mode) || 'NAT'} • ↓ ${data.total_download_str || '0 o/s'} • ↑ ${data.total_upload_str || '0 o/s'}`;
|
||
ctx.fillText(apMetaStr, apX + 60, apY + 66);
|
||
|
||
// 7. Liaisons & Cartes Clients
|
||
const apCenterX = width / 2;
|
||
const apBottomY = apY + apH;
|
||
|
||
// Connecteur émetteur Wi-Fi sous l'AP
|
||
ctx.beginPath();
|
||
ctx.arc(apCenterX, apBottomY, 4.5, 0, Math.PI * 2);
|
||
ctx.fillStyle = blue;
|
||
ctx.fill();
|
||
ctx.beginPath();
|
||
ctx.arc(apCenterX, apBottomY, 7.5, 0, Math.PI * 2);
|
||
ctx.strokeStyle = blue;
|
||
ctx.lineWidth = 1.5;
|
||
ctx.stroke();
|
||
|
||
if (!numClients) {
|
||
const emptyX = 40, emptyY = yStart, emptyW = width - 80, emptyH = 120;
|
||
roundRect(emptyX, emptyY, emptyW, emptyH, 12);
|
||
ctx.fillStyle = nodeBg;
|
||
ctx.fill();
|
||
ctx.strokeStyle = lineColor;
|
||
ctx.stroke();
|
||
ctx.fillStyle = textColor;
|
||
ctx.font = 'bold 15px ' + fontFamily;
|
||
ctx.textAlign = 'center';
|
||
ctx.fillText("Aucun appareil connecté au point d'accès actuellement", width / 2, emptyY + 55);
|
||
ctx.fillStyle = mutedColor;
|
||
ctx.font = '13px ' + fontFamily;
|
||
ctx.fillText("Les équipements Wi-Fi rejoignant le réseau apparaîtront ici automatiquement.", width / 2, emptyY + 80);
|
||
ctx.textAlign = 'left';
|
||
} else {
|
||
clients.forEach((c, idx) => {
|
||
const col = idx % cols;
|
||
const row = Math.floor(idx / cols);
|
||
const cX = 40 + col * (cardW + 20);
|
||
const cY = yStart + row * (cardH + 20);
|
||
const cCenterX = cX + cardW / 2;
|
||
|
||
const sig = c.signal_dbm;
|
||
let sigColor = red;
|
||
if (sig !== null && sig !== undefined) {
|
||
if (sig >= -50) sigColor = green;
|
||
else if (sig >= -60) sigColor = (theme === 'hacker' ? '#00ff41' : (theme === 'winxp' ? '#2e8b22' : '#68d391'));
|
||
else if (sig >= -70) sigColor = (theme === 'hacker' ? '#00aa2b' : '#f6ad55');
|
||
}
|
||
|
||
const isVpn = !!c.vpn_routed;
|
||
const linkColor = isVpn ? red : sigColor;
|
||
|
||
// Courbe de liaison (Rouge si l'équipement est routé sur le VPN)
|
||
ctx.beginPath();
|
||
ctx.moveTo(apCenterX, apBottomY);
|
||
const midCurveY = apBottomY + (cY - apBottomY) * 0.45;
|
||
ctx.bezierCurveTo(apCenterX, midCurveY, cCenterX, midCurveY, cCenterX, cY);
|
||
ctx.strokeStyle = linkColor;
|
||
ctx.lineWidth = isVpn ? 3.2 : 2.0;
|
||
ctx.stroke();
|
||
|
||
// Carte client
|
||
roundRect(cX, cY, cardW, cardH, 12);
|
||
ctx.fillStyle = nodeBg;
|
||
ctx.fill();
|
||
ctx.strokeStyle = isVpn ? red : lineColor;
|
||
ctx.lineWidth = isVpn ? 1.8 : 1.0;
|
||
ctx.stroke();
|
||
|
||
const icon = getDeviceTypeIcon(c.device_type);
|
||
if (typeof icon === 'string' && icon.startsWith('<svg')) {
|
||
ctx.save();
|
||
ctx.fillStyle = nodeBg;
|
||
ctx.strokeStyle = lineColor;
|
||
ctx.lineWidth = 1;
|
||
roundRect(cX + 14, cY + 16, 20, 23, 3);
|
||
ctx.fill();
|
||
ctx.stroke();
|
||
ctx.fillStyle = blue;
|
||
roundRect(cX + 16, cY + 18, 16, 16, 2);
|
||
ctx.fill();
|
||
ctx.fillStyle = mutedColor;
|
||
ctx.fillRect(cX + 21, cY + 36, 6, 1.5);
|
||
ctx.restore();
|
||
} else {
|
||
ctx.font = '22px ' + fontFamily;
|
||
ctx.fillText(icon, cX + 14, cY + 36);
|
||
}
|
||
|
||
ctx.fillStyle = textColor;
|
||
ctx.font = 'bold 14px ' + fontFamily;
|
||
const maxTitleW = cardW - 130;
|
||
let devName = c.name || 'Client inconnu';
|
||
while (ctx.measureText(devName).width > maxTitleW && devName.length > 5) {
|
||
devName = devName.slice(0, -1);
|
||
}
|
||
if (devName !== c.name) devName += '…';
|
||
ctx.fillText(devName, cX + 46, cY + 32);
|
||
|
||
// Badge Signal
|
||
ctx.fillStyle = sigColor;
|
||
ctx.font = 'bold 11px ' + fontMono;
|
||
const sigText = (sig !== null && sig !== undefined) ? `${sig} dBm` : '—';
|
||
ctx.textAlign = 'right';
|
||
ctx.fillText(sigText, cX + cardW - 14, cY + 32);
|
||
ctx.textAlign = 'left';
|
||
|
||
// Séparateur
|
||
ctx.strokeStyle = lineColor;
|
||
ctx.lineWidth = 0.5;
|
||
ctx.beginPath();
|
||
ctx.moveTo(cX + 14, cY + 48);
|
||
ctx.lineTo(cX + cardW - 14, cY + 48);
|
||
ctx.stroke();
|
||
|
||
// IP & MAC
|
||
ctx.fillStyle = mutedColor;
|
||
ctx.font = '10px ' + fontFamily;
|
||
ctx.fillText('IP:', cX + 14, cY + 68);
|
||
ctx.fillStyle = textColor;
|
||
ctx.font = '12px ' + fontMono;
|
||
ctx.fillText(c.ip || 'Non attribuée', cX + 34, cY + 68);
|
||
|
||
ctx.fillStyle = mutedColor;
|
||
ctx.font = '10px ' + fontFamily;
|
||
ctx.fillText('MAC:', cX + 14, cY + 88);
|
||
ctx.fillStyle = textColor;
|
||
ctx.font = '11px ' + fontMono;
|
||
ctx.fillText(c.mac || '—', cX + 46, cY + 88);
|
||
|
||
// Routage Internet / VPN
|
||
if (c.vpn_profile_name) {
|
||
ctx.fillStyle = c.vpn_routed ? green : red;
|
||
ctx.font = 'bold 11px ' + fontFamily;
|
||
const cProto = c.vpn_profile_type === 'wireguard' ? 'WG' : (c.vpn_profile_type === 'openvpn' ? 'OVPN' : 'VPN');
|
||
const cCountry = (c.vpn_public_ip_geo && c.vpn_public_ip_geo.code) ? `[${c.vpn_public_ip_geo.code}] ` : '';
|
||
const vpnTxt = (c.vpn_routed ? '🛡️ ' : '⚠️ ') + `[${cProto}] ` + c.vpn_profile_name + (c.vpn_public_ip ? ` (${cCountry}${c.vpn_public_ip})` : '') + (c.vpn_routed ? ' 🔒' : '');
|
||
ctx.fillText(vpnTxt, cX + 14, cY + 112);
|
||
} else {
|
||
ctx.fillStyle = mutedColor;
|
||
ctx.font = '11px ' + fontFamily;
|
||
ctx.fillText('🌐 Direct WAN (Box)', cX + 14, cY + 112);
|
||
}
|
||
|
||
// Vitesses
|
||
ctx.fillStyle = blue;
|
||
ctx.font = 'bold 12px ' + fontMono;
|
||
ctx.fillText(`↓ ${c.download_speed_str || '0 o/s'}`, cX + 14, cY + 136);
|
||
ctx.fillStyle = green;
|
||
ctx.fillText(`↑ ${c.upload_speed_str || '0 o/s'}`, cX + cardW / 2 + 10, cY + 136);
|
||
});
|
||
}
|
||
|
||
// 8. Pied de page
|
||
ctx.fillStyle = mutedColor;
|
||
ctx.font = '11px ' + fontFamily;
|
||
ctx.textAlign = 'center';
|
||
ctx.fillText('Généré par AP Manageur • Interface d’administration Wi‑Fi', width / 2, height - 28);
|
||
ctx.textAlign = 'left';
|
||
|
||
return canvas;
|
||
}
|
||
|
||
|
||
function updateTopologyModalContent(type, clientMac) {
|
||
const modal = $('topoDetailModal');
|
||
const title = $('topoModalTitle');
|
||
const body = $('topoModalBody');
|
||
const footer = $('topoModalFooter');
|
||
if (!modal || !title || !body) return;
|
||
|
||
const data = topologyDataCache || {};
|
||
|
||
if (type === 'wan') {
|
||
title.innerHTML = '<span>🌐</span> ' + t('topo_modal_wan_title', 'Passerelle Internet (WAN)') + ' <span class="pill pill-green pill-no-dot" style="font-size:11px;margin-left:auto">' + t('topo_modal_live_badge', 'En direct') + '</span>';
|
||
const wan = data.internet || {};
|
||
body.innerHTML = `
|
||
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px">
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_gw_ip', 'ADRESSE IP PASSERELLE')}</span><div style="font-weight:700;font-size:16px;margin-top:4px"><code>${wan.gateway_ip || '192.168.1.1'}</code></div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_out_iface', 'INTERFACE SORTANTE')}</span><div style="font-weight:700;font-size:16px;margin-top:4px">${wan.interface || 'eth0'}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_wan_status', 'STATUT WAN')}</span><div style="font-weight:700;font-size:16px;margin-top:4px;color:var(--green)">● ${t('status_connected', 'Connecté')}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_dns_servers', 'SERVEURS DNS')}</span><div style="font-weight:700;font-size:14px;margin-top:4px"><code>${(wan.dns || ['1.1.1.1', '8.8.8.8']).join(', ')}</code></div></div>
|
||
</div>
|
||
<p class="muted" style="font-size:13px;margin-top:8px">${t('topo_modal_wan_desc', 'La passerelle assure la connectivité vers Internet pour tous les appareils connectés au point d’accès Wi‑Fi via routage et translation d’adresses NAT.')}</p>`;
|
||
footer.innerHTML = `<button type="button" class="secondary" onclick="closeTopologyModal()">${t('btn_close', 'Fermer')}</button>`;
|
||
} else if (type === 'ap') {
|
||
title.innerHTML = '<span>📡</span> ' + t('topo_modal_ap_title', 'Point d’Accès Wi‑Fi (AP Manageur)') + ' <span class="pill pill-green pill-no-dot" style="font-size:11px;margin-left:auto">' + t('topo_modal_live_badge', 'En direct') + '</span>';
|
||
const ap = data.ap || {};
|
||
const apIpVal = (ap.ip === 'IP Pont LAN' || String(ap.ip).includes('Pont')) ? t('topo_ip_bridge_lan', 'IP Pont LAN') : (ap.ip || '10.42.0.1');
|
||
let apModeVal = ap.mode || 'NAT';
|
||
if (ap.mode_key === 'bridge' || apModeVal.includes('Bridge') || apModeVal.includes('Pont')) {
|
||
apModeVal = t('mode_bridge_label', 'Pont réseau (Bridge)');
|
||
} else if (ap.mode_key === 'nat' || apModeVal.includes('Routeur') || apModeVal.includes('NAT')) {
|
||
apModeVal = t('mode_nat_label', 'Point d’accès (Routeur Wi-Fi)');
|
||
}
|
||
body.innerHTML = `
|
||
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:10px">
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_ssid', 'NOM DU SSID')}</span><div style="font-weight:700;font-size:16px;margin-top:4px">${ap.ssid || 'AP Wi-Fi'}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_local_ip', 'IP LOCALE AP')}</span><div style="font-weight:700;font-size:16px;margin-top:4px"><code>${apIpVal}/${ap.cidr || '24'}</code></div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_wifi_iface', 'INTERFACE SANS FIL')}</span><div style="font-weight:700;font-size:16px;margin-top:4px">${ap.interface || 'wlan0'}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_radio_channel', 'RADIO & CANAL')}</span><div style="font-weight:700;font-size:16px;margin-top:4px">${t('topo_channel', 'Canal')} ${ap.channel || 6} (${ap.band || '2.4 GHz'})</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_net_mode', 'MODE RÉSEAU')}</span><div style="font-weight:700;font-size:16px;margin-top:4px">${apModeVal}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_security', 'SÉCURITÉ')}</span><div style="font-weight:700;font-size:16px;margin-top:4px">${ap.security || 'WPA2'}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_connected_devs', 'APPAREILS CONNECTÉS')}</span><div style="font-weight:700;font-size:16px;margin-top:4px">${data.total_clients_count || 0} / ${ap.max_clients || 30}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_live_speed', 'DÉBIT EN DIRECT')}</span><div style="font-weight:700;font-size:14px;margin-top:4px;color:var(--blue)">↓ ${data.total_download_str || '0 o/s'} • <span style="color:var(--green)">↑ ${data.total_upload_str || '0 o/s'}</span></div></div>
|
||
</div>`;
|
||
footer.innerHTML = `<button type="button" class="secondary" onclick="closeTopologyModal()">${t('btn_close', 'Fermer')}</button>`;
|
||
} else if (type === 'client') {
|
||
const clients = data.clients || [];
|
||
const client = clients.find(c => c.mac === clientMac);
|
||
if (!client) {
|
||
title.innerHTML = '<span>📱</span> ' + t('topo_disconnected_device_title', 'Équipement déconnecté');
|
||
body.innerHTML = `
|
||
<div class="card" style="padding:18px;text-align:center">
|
||
<div style="font-size:32px;margin-bottom:8px">⚠️</div>
|
||
<strong>${t('topo_disconnected_device_msg', "Cet appareil n'est plus actuellement connecté au réseau Wi-Fi")}</strong>
|
||
<p class="muted" style="font-size:13px;margin-top:6px">${t('topo_modal_mac_addr', 'ADRESSE MAC')} : <code>${clientMac || '—'}</code></p>
|
||
</div>`;
|
||
footer.innerHTML = `<button type="button" class="secondary" onclick="closeTopologyModal()">${t('btn_close', 'Fermer')}</button>`;
|
||
return;
|
||
}
|
||
const icon = getDeviceTypeIcon(client.device_type);
|
||
const nameEsc = String(client.name || t('client_unknown', 'Client inconnu')).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const ipEsc = String(client.ip || '—').replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const macEsc = String(client.mac || '—').replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const sigDbm = client.signal_dbm !== null && client.signal_dbm !== undefined ? client.signal_dbm : null;
|
||
let sigColor = 'var(--red)';
|
||
if (sigDbm !== null) {
|
||
if (sigDbm >= -50) sigColor = 'var(--green)';
|
||
else if (sigDbm >= -60) sigColor = '#68d391';
|
||
else if (sigDbm >= -70) sigColor = '#f6ad55';
|
||
}
|
||
const clientVpnDesc = client.vpn_profile_name ? (client.vpn_routed ? `<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap"><span style="display:inline-flex;align-items:center">${typeof VPN_LOGOS !== 'undefined' && VPN_LOGOS[client.vpn_profile_type] ? VPN_LOGOS[client.vpn_profile_type] : '🛡️'}</span> <strong>${escapeHtml(client.vpn_profile_name)}</strong> ${client.vpn_public_ip ? (typeof formatIpWithGeo === 'function' ? formatIpWithGeo(client.vpn_public_ip, client.vpn_public_ip_geo) : `<code>${escapeHtml(client.vpn_public_ip)}</code>`) : ''}</div>` : `⚠️ ${escapeHtml(client.vpn_profile_name)} ${t('vpn_status_disconnected_short', '(Coupé)')}`) : ('🌐 ' + t('topo_direct_wan', 'Direct WAN (Box)'));
|
||
title.innerHTML = `<span>${icon}</span> ${t('topo_modal_dev_details', 'Détails de l’équipement : {name}').replace('{name}', nameEsc)} <span class="pill pill-green pill-no-dot" style="font-size:11px;margin-left:auto">${t('topo_modal_live_badge', 'En direct')}</span>`;
|
||
body.innerHTML = `
|
||
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:10px">
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_dev_name', 'NOM DE L’APPAREIL')}</span><div style="font-weight:700;font-size:15px;margin-top:4px">${nameEsc}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_ip_addr', 'ADRESSE IP')}</span><div style="font-weight:700;font-size:15px;margin-top:4px"><code>${ipEsc}</code></div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_mac_addr', 'ADRESSE MAC')}</span><div style="font-weight:700;font-size:13px;margin-top:4px"><code>${macEsc}</code></div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_sig_quality', 'QUALITÉ DU SIGNAL')}</span><div style="font-weight:700;font-size:15px;margin-top:4px;color:${sigColor}">${sigDbm !== null ? sigDbm + ' dBm' : '—'}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_inst_speed', 'DÉBIT INSTANTANÉ')}</span><div style="font-weight:700;font-size:14px;margin-top:4px;color:var(--blue)">↓ ${client.download_speed_str || '0 o/s'} • <span style="color:var(--green)">↑ ${client.upload_speed_str || '0 o/s'}</span></div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_hw_type', 'TYPE MATÉRIEL')}</span><div style="font-weight:700;font-size:15px;margin-top:4px">${getDeviceTypeLabel(client.device_type)}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_routing_vpn', 'ROUTAGE INTERNET / VPN')}</span><div style="font-weight:700;font-size:15px;margin-top:4px;color:${client.vpn_routed ? 'var(--green)' : 'var(--text)'}">${clientVpnDesc}</div></div>
|
||
</div>`;
|
||
footer.innerHTML = `
|
||
<button type="button" class="secondary" style="color:var(--red);margin-right:auto" onclick="closeTopologyModal();blockClient('${macEsc}',true)">${t('btn_block_this_device', '🚫 Bloquer cet appareil')}</button>
|
||
<button type="button" class="secondary" onclick="closeTopologyModal()">${t('btn_close', 'Fermer')}</button>`;
|
||
} else if (type === 'vpn') {
|
||
const vpnList = data.vpn_profiles || [];
|
||
const vpn = vpnList.find(p => String(p.id) === String(clientMac)) || vpnList[0];
|
||
if (!vpn) {
|
||
title.innerHTML = '<span>🛡️</span> ' + t('topo_modal_vpn_title', 'Tunnel VPN : {name}').replace('{name}', '');
|
||
body.innerHTML = `<div class="card" style="padding:18px;text-align:center"><div style="font-size:32px;margin-bottom:8px">⚠️</div><strong>${t('vpn_profile_not_connected', "Ce profil VPN n'est plus connecté")}</strong></div>`;
|
||
footer.innerHTML = `<button type="button" class="secondary" onclick="closeTopologyModal()">${t('btn_close', 'Fermer')}</button>`;
|
||
return;
|
||
}
|
||
const vtype = vpn.type === 'wireguard' ? 'WireGuard' : 'OpenVPN';
|
||
const vpnLogoSvg = (typeof VPN_LOGOS !== 'undefined' && VPN_LOGOS[vpn.type]) ? VPN_LOGOS[vpn.type] : '🛡️';
|
||
title.innerHTML = `<span style="display:inline-flex;align-items:center">${vpnLogoSvg}</span> ${t('topo_modal_vpn_title', 'Tunnel VPN : {name}').replace('{name}', escapeHtml(vpn.name))} <span class="pill pill-green pill-no-dot" style="font-size:11px;margin-left:auto">${t('status_active', 'Actif')}</span>`;
|
||
body.innerHTML = `
|
||
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:10px">
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_prof_name', 'NOM DU PROFIL')}</span><div style="font-weight:700;font-size:16px;margin-top:4px">${escapeHtml(vpn.name)}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_vpn_proto', 'PROTOCOLE VPN')}</span><div style="font-weight:700;font-size:16px;margin-top:4px">${typeof getVpnTypeBadgeHtml === 'function' ? getVpnTypeBadgeHtml(vpn.type, true) : vtype}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_sys_iface', 'INTERFACE SYSTÈME')}</span><div style="font-weight:700;font-size:16px;margin-top:4px"><code>${escapeHtml(vpn.iface)}</code></div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_public_ip', 'IP PUBLIQUE DU TUNNEL')}</span><div style="font-weight:700;font-size:16px;margin-top:4px;color:var(--green)">${vpn.public_ip ? (typeof formatIpWithGeo === 'function' ? formatIpWithGeo(vpn.public_ip, vpn.public_ip_geo) : `<code>${escapeHtml(vpn.public_ip)}</code>`) : '<code>Détection en cours...</code>'}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_pbr_table', 'TABLE PBR NOYAU')}</span><div style="font-weight:700;font-size:16px;margin-top:4px">Table ${vpn.table_id || '101'}</div></div>
|
||
<div class="card" style="padding:12px"><span class="muted" style="font-size:11px">${t('topo_modal_routed_devs', 'APPAREILS ROUTÉS')}</span><div style="font-weight:700;font-size:16px;margin-top:4px;color:var(--red)">${t('topo_devices_routed_tunnel', '{count} appareil(s)').replace(' routé(s) via ce tunnel', '').replace('{count}', vpn.client_count || 0)}</div></div>
|
||
</div>
|
||
<p class="muted" style="font-size:13px;margin-top:12px">${t('topo_modal_vpn_desc', 'Tout le trafic Internet des équipements associés à ce profil est chiffré et acheminé exclusivement à travers ce tunnel VPN.')}</p>`;
|
||
footer.innerHTML = `
|
||
<button type="button" class="secondary" style="color:var(--blue);margin-right:auto" onclick="closeTopologyModal();selectTab('advanced');selectAdvSubTab('vpn')">${t('btn_manage_vpn_routing', '⚙️ Gérer le routage VPN')}</button>
|
||
<button type="button" class="secondary" onclick="closeTopologyModal()">${t('btn_close', 'Fermer')}</button>`;
|
||
}
|
||
}
|
||
let statsChartInstance = null; let previousChartDataKey = null; let previousChartAxis = null;
|
||
|
||
(function loadChartJs() {
|
||
try {
|
||
const s = document.createElement('script');
|
||
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js';
|
||
s.async = true;
|
||
s.onload = () => { if (currentTab === 'stats' && statsDataCache) renderStatsChart(currentStatsRange, true) };
|
||
document.head.appendChild(s);
|
||
} catch (_) { }
|
||
})();
|
||
|
||
// $ est défini globalement en haut du script
|
||
let themePref = localStorage.getItem('apTheme') || 'dark'; const themeMedia = window.matchMedia('(prefers-color-scheme: light)');
|
||
function applyTheme() {
|
||
document.documentElement.dataset.theme = themePref === 'auto' ? (themeMedia.matches ? 'light' : 'dark') : themePref;
|
||
if (themePref === 'macos') {
|
||
document.documentElement.dataset.macosMode = themeMedia.matches ? 'light' : 'dark';
|
||
} else {
|
||
delete document.documentElement.dataset.macosMode;
|
||
}
|
||
const s = document.getElementById('themeSelect'); if (s) s.value = themePref;
|
||
if (typeof renderStatsChart === 'function' && statsDataCache) renderStatsChart(currentStatsRange, true);
|
||
}
|
||
themeMedia.addEventListener('change', () => { if (themePref === 'auto' || themePref === 'macos') applyTheme() }); applyTheme();
|
||
|
||
async function loadPreferences() {
|
||
try {
|
||
const r = await fetch(API_URL + '/api/preferences', { cache: 'no-store' });
|
||
if (r.ok) {
|
||
const d = await r.json();
|
||
if (d && ['dark', 'light', 'auto', 'winxp', 'futuristic', 'macos', 'hacker'].includes(d.theme)) {
|
||
themePref = d.theme;
|
||
try { localStorage.setItem('apTheme', themePref); } catch (_) { }
|
||
applyTheme();
|
||
}
|
||
if (d && d.language && ['fr', 'en-us', 'en-gb'].includes(d.language)) {
|
||
setLanguage(d.language, false);
|
||
}
|
||
if (d && d.app_name && $('appNameInput')) $('appNameInput').value = d.app_name;
|
||
if (d && d.app_short_name && $('appShortNameInput')) $('appShortNameInput').value = d.app_short_name;
|
||
applyProjectTitle(d.app_name || PROJECT_NAME, d.app_short_name || PROJECT_SHORT_NAME);
|
||
}
|
||
} catch (_) { }
|
||
}
|
||
try { loadPreferences(); } catch (_) { }
|
||
|
||
function setActionBusy(busy) {
|
||
actionBusy = busy;
|
||
document.querySelectorAll('button').forEach(button => { button.disabled = busy; button.style.opacity = busy ? '0.55' : ''; button.style.cursor = busy ? 'wait' : '' });
|
||
}
|
||
async function runAction(action) {
|
||
if (actionBusy) return; setActionBusy(true);
|
||
try { return await action() } finally { setActionBusy(false) }
|
||
}
|
||
|
||
function uptime(s) {
|
||
if (!s) return '—';
|
||
let d = Math.floor(s / 86400), h = Math.floor(s % 86400 / 3600), m = Math.floor(s % 3600 / 60), sec = s % 60;
|
||
return (d ? d + 'j ' : '') + (h ? String(h).padStart(2, '0') + 'h ' : '') + String(m).padStart(2, '0') + 'm ' + String(sec).padStart(2, '0') + 's';
|
||
}
|
||
function esc(s) { return String(s).replace(/([\\;,:])/g, '\\$1') }
|
||
function signalQuality(dbm, client) {
|
||
if (dbm === null || dbm === undefined || Number.isNaN(Number(dbm))) return '<span class="signal">—</span>';
|
||
const val = Math.round(Number(dbm));
|
||
const isEst = !!(client && client.signal_estimated);
|
||
const rate = client && client.link_rate_mbps ? Number(client.link_rate_mbps) : null;
|
||
const suffix = isEst
|
||
? (rate ? ` <small style="opacity:.78;font-weight:500">(${Math.round(rate)} Mbps)</small>` : ` <small style="opacity:.78;font-weight:500">(~)</small>`)
|
||
: ` <small style="opacity:.78;font-weight:500">(${val} dBm)</small>`;
|
||
const tip = isEst
|
||
? (rate ? `Estimé via lien Wi-Fi ${rate} MBit/s (pilote Raspberry Pi brcmfmac)` : `Qualité estimée via les statistiques de paquets (pilote Raspberry Pi brcmfmac)`)
|
||
: `${val} dBm`;
|
||
if (val >= -50) return `<span class="signal signal-excellent" title="${tip}">${t('signal_excellent', 'Excellent')}${suffix}</span>`;
|
||
if (val >= -60) return `<span class="signal signal-bon" title="${tip}">${t('signal_good', 'Bon')}${suffix}</span>`;
|
||
if (val >= -70) return `<span class="signal signal-moyen" title="${tip}">${t('signal_fair', 'Moyen')}${suffix}</span>`;
|
||
return `<span class="signal signal-faible" title="${tip}">${t('signal_weak', 'Faible')}${suffix}</span>`;
|
||
}
|
||
|
||
function cleanQrBox(box) {
|
||
if (!box) return;
|
||
const canvas = box.querySelector('canvas');
|
||
const img = box.querySelector('img');
|
||
if (!canvas && !img) return;
|
||
if (img && img.src && img.src.startsWith('data:image')) {
|
||
img.style.display = 'block'; img.style.width = '100%'; img.style.height = '100%';
|
||
if (canvas) canvas.remove();
|
||
return;
|
||
}
|
||
if (canvas) {
|
||
try {
|
||
const dataUrl = canvas.toDataURL('image/png');
|
||
if (dataUrl && dataUrl.length > 50) {
|
||
if (img) {
|
||
img.src = dataUrl; img.style.display = 'block'; img.style.width = '100%'; img.style.height = '100%';
|
||
canvas.remove(); return;
|
||
}
|
||
}
|
||
} catch (_) { }
|
||
canvas.style.display = 'block'; canvas.style.width = '100%'; canvas.style.height = '100%';
|
||
if (img) img.remove();
|
||
return;
|
||
}
|
||
if (img) { img.style.display = 'block'; img.style.width = '100%'; img.style.height = '100%' }
|
||
}
|
||
|
||
let currentSettingsTab = 'wifi';
|
||
let currentNotifSubTab = sessionStorage.getItem('apNotifSubTab') || 'services';
|
||
function selectNotifSubTab(subTab) {
|
||
currentNotifSubTab = subTab;
|
||
sessionStorage.setItem('apNotifSubTab', subTab);
|
||
const isServices = subTab === 'services';
|
||
const isAlerts = subTab === 'alerts';
|
||
const ts = $('tabNotifServices'), ta = $('tabNotifAlerts');
|
||
if (ts) { ts.classList.toggle('active', isServices); ts.setAttribute('aria-selected', isServices); }
|
||
if (ta) { ta.classList.toggle('active', isAlerts); ta.setAttribute('aria-selected', isAlerts); }
|
||
const ps = $('panelNotifServices'), pa = $('panelNotifAlerts');
|
||
if (ps) ps.style.display = isServices ? 'block' : 'none';
|
||
if (pa) pa.style.display = isAlerts ? 'block' : 'none';
|
||
}
|
||
|
||
function selectSettingsTab(tabKey) {
|
||
if (tabKey === '2fa') tabKey = 'admin';
|
||
currentSettingsTab = tabKey;
|
||
const tabs = ['wifi', 'admin', 'vpn', 'proxy', 'notif', 'custom', 'backup', 'danger'];
|
||
tabs.forEach(k => {
|
||
const btnId = 'tabSettings' + k.charAt(0).toUpperCase() + k.slice(1);
|
||
const panelId = 'panelSettings' + k.charAt(0).toUpperCase() + k.slice(1);
|
||
const btn = $(btnId); const panel = $(panelId);
|
||
if (btn) {
|
||
btn.classList.toggle('active', k === tabKey);
|
||
btn.setAttribute('aria-selected', k === tabKey ? 'true' : 'false');
|
||
}
|
||
if (panel) {
|
||
panel.style.display = (k === tabKey) ? 'block' : 'none';
|
||
panel.classList.toggle('active', k === tabKey);
|
||
}
|
||
});
|
||
if (tabKey === 'admin') { if (typeof loadAdminUser === 'function') loadAdminUser(); if (typeof loadSessions === 'function') loadSessions(); if (typeof loadPasskeysList === 'function') loadPasskeysList(); }
|
||
if (tabKey === 'vpn') {
|
||
if (typeof loadVpnProfiles === 'function') loadVpnProfiles();
|
||
if (typeof loadVpnClients === 'function') loadVpnClients();
|
||
startVpnTabRefresh();
|
||
}
|
||
if (tabKey === 'proxy') {
|
||
if (typeof loadReverseProxySettings === 'function') loadReverseProxySettings();
|
||
}
|
||
if (tabKey === 'notif') {
|
||
if (typeof selectNotifSubTab === 'function') selectNotifSubTab(currentNotifSubTab || 'services');
|
||
if (typeof loadNotificationSettings === 'function') loadNotificationSettings();
|
||
}
|
||
if (tabKey === 'custom') {
|
||
if (typeof loadDeviceTypes === 'function') loadDeviceTypes();
|
||
}
|
||
if (tabKey === 'backup') {
|
||
if (typeof loadBackupsTab === 'function') loadBackupsTab();
|
||
}
|
||
}
|
||
|
||
let vpnTabRefreshTimer = null;
|
||
function startVpnTabRefresh() {
|
||
if (vpnTabRefreshTimer) clearInterval(vpnTabRefreshTimer);
|
||
vpnTabRefreshTimer = setInterval(() => {
|
||
if (authToken && currentTab === 'settings' && currentSettingsTab === 'vpn') {
|
||
if (typeof loadVpnProfiles === 'function') loadVpnProfiles();
|
||
if (typeof loadVpnClients === 'function') loadVpnClients();
|
||
} else {
|
||
clearInterval(vpnTabRefreshTimer);
|
||
vpnTabRefreshTimer = null;
|
||
}
|
||
}, 3000);
|
||
}
|
||
|
||
function qr() {
|
||
if (!status.ssid || !status.password) return;
|
||
let box = $('qrcode'); let signature = status.ssid + '\u0000' + status.password;
|
||
if (signature === qrSignature) return;
|
||
$('qrPassword').value = status.password; box.replaceChildren();
|
||
new QRCode(box, { text: `WIFI:T:WPA;S:${esc(status.ssid)};P:${esc(status.password)};;`, width: 190, height: 190 });
|
||
cleanQrBox(box);
|
||
setTimeout(() => cleanQrBox(box), 50);
|
||
setTimeout(() => cleanQrBox(box), 200);
|
||
qrSignature = signature;
|
||
}
|
||
|
||
async function controlAp(action) {
|
||
return runAction(async () => {
|
||
try {
|
||
const response = await apiFetch('/api/ap/control', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) });
|
||
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Action refusée');
|
||
await new Promise(resolve => setTimeout(resolve, 1000)); await load();
|
||
} catch (e) { alert(tErr(e.message)) }
|
||
});
|
||
}
|
||
|
||
function updateApButtons() {
|
||
const active = !!status.active, configured = !!status.configured;
|
||
if ($('dashboardView')) $('dashboardView').classList.toggle('active', currentTab === 'dashboard');
|
||
if ($('statsView')) $('statsView').classList.toggle('active', configured && currentTab === 'stats');
|
||
if ($('devicesView')) $('devicesView').classList.toggle('active', configured && currentTab === 'devices');
|
||
if ($('advancedView')) $('advancedView').classList.toggle('active', configured && currentTab === 'advanced');
|
||
if ($('settingsView')) $('settingsView').classList.toggle('active', configured && currentTab === 'settings');
|
||
if ($('logsView')) $('logsView').classList.toggle('active', configured && currentTab === 'logs');
|
||
if ($('blockedView')) $('blockedView').classList.toggle('active', configured && currentTab === 'blocked');
|
||
if ($('nav')) $('nav').style.display = configured ? 'flex' : 'none';
|
||
if ($('dashboardTab')) $('dashboardTab').style.display = configured ? '' : 'none';
|
||
if ($('statsTab')) $('statsTab').style.display = configured ? '' : 'none';
|
||
if ($('devicesTab')) $('devicesTab').style.display = configured ? '' : 'none';
|
||
if ($('advancedTab')) $('advancedTab').style.display = configured ? '' : 'none';
|
||
if ($('settingsTab')) $('settingsTab').style.display = configured ? '' : 'none';
|
||
if ($('logsTab')) $('logsTab').style.display = configured ? '' : 'none';
|
||
if ($('blockedTab')) $('blockedTab').style.display = configured ? '' : 'none';
|
||
if ($('apControl')) $('apControl').style.display = configured ? '' : 'none';
|
||
if ($('apRestart')) $('apRestart').style.display = configured && active ? '' : 'none';
|
||
if ($('refresh')) $('refresh').style.display = configured ? '' : 'none';
|
||
if (configured && $('apControl')) {
|
||
$('apControl').textContent = active ? t('btn_stop', 'Arrêter') : t('btn_start', 'Démarrer');
|
||
$('apControl').style.background = active ? 'var(--red)' : 'var(--blue)';
|
||
$('apControl').style.color = active ? 'white' : 'var(--blue-text, #071326)';
|
||
}
|
||
}
|
||
|
||
async function toggleBlock(mac, blocked) {
|
||
return runAction(async () => {
|
||
try {
|
||
const response = await apiFetch('/api/clients/block', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ mac, blocked }) });
|
||
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Opération refusée');
|
||
await load();
|
||
} catch (e) { alert(tErr(e.message)) }
|
||
});
|
||
}
|
||
|
||
function render() {
|
||
updateApButtons();
|
||
$('clientCount').textContent = status.max_clients > 0 ? `${clients.length} / ${status.max_clients}` : clients.length;
|
||
$('ssid').textContent = status.ssid || 'SSID inconnu';
|
||
$('uptime').textContent = status.active ? uptime(status.uptime_seconds) : '—';
|
||
$('settingsSsid').value = status.ssid || '';
|
||
$('settingsPassword').value = status.password || '';
|
||
$('settingsSecurity').value = status.security || 'wpa2';
|
||
if ($('settingsMaxClients')) $('settingsMaxClients').value = status.max_clients !== undefined ? status.max_clients : 0;
|
||
const isBridge = status.mode === 'bridge';
|
||
if ($('networkModeBadge')) {
|
||
$('networkModeBadge').textContent = isBridge ? t('badge_mode_bridge', 'Pont (DHCP Box)') : t('badge_mode_ap', 'AP (Routeur/NAT)');
|
||
$('networkModeBadge').className = 'pill ' + (isBridge ? 'pill-blue' : 'pill-green');
|
||
$('networkModeBadge').style.background = '';
|
||
$('networkModeBadge').style.color = '';
|
||
}
|
||
if ($('settingsModeAp') && $('settingsModeBridge')) {
|
||
if (isBridge) $('settingsModeBridge').checked = true; else $('settingsModeAp').checked = true;
|
||
if ($('settingsBridgeBlock')) $('settingsBridgeBlock').style.display = isBridge ? 'block' : 'none';
|
||
}
|
||
const ethList = status.ethernet_interfaces || [];
|
||
const populateEth = (selId, cur) => {
|
||
const el = $(selId); if (!el) return; const val = el.value || cur;
|
||
el.innerHTML = ethList.length ? ethList.map(e => `<option value="${e}">${e}</option>`).join('') : '<option value="">Auto-détection</option>';
|
||
if (val && ethList.includes(val)) el.value = val; else if (cur && ethList.includes(cur)) el.value = cur;
|
||
};
|
||
populateEth('setupBridgeEth', status.bridge_eth); populateEth('settingsBridgeEth', status.bridge_eth);
|
||
$('settingsAutoconnect').checked = !!status.autoconnect;
|
||
$('updated').textContent = formatLastUpdated();
|
||
$('state').innerHTML = status.active ? '<i class="dot"></i> ' + t('status_active', 'Actif') : '<i class="dot" style="background:var(--red)"></i> ' + t('status_inactive', 'Inactif');
|
||
|
||
const totalPages = Math.max(1, Math.ceil(clients.length / 10));
|
||
if (clientsPage > totalPages) clientsPage = totalPages; if (clientsPage < 1) clientsPage = 1;
|
||
const pagedClients = clients.slice((clientsPage - 1) * 10, clientsPage * 10);
|
||
|
||
$('clients').innerHTML = pagedClients.length ? pagedClients.map(c => {
|
||
const speedHtml = c.blocked
|
||
? `<span class="signal-faible">● ${t('status_blocked', 'Bloqué')}</span>`
|
||
: `<span style="font-family:monospace;font-size:13px;white-space:nowrap"><span style="color:var(--blue);font-weight:700" title="Débit descendant">↓ ${c.download_speed_str || formatSpeed(c.download_speed)}</span><span style="color:var(--muted);margin:0 5px">|</span><span style="color:var(--green);font-weight:700" title="Débit montant">↑ ${c.upload_speed_str || formatSpeed(c.upload_speed)}</span></span>`;
|
||
const vpnHtml = c.vpn_routed
|
||
? `<span class="pill pill-green" style="font-size:11px;font-weight:600;display:inline-flex;align-items:center;gap:4px" title="Trafic chiffré via ${escapeHtml(c.vpn_profile_name)}">🛡️ ${escapeHtml(c.vpn_profile_name)}${c.vpn_public_ip ? ` <span style="font-family:monospace;font-size:10px;opacity:.9">(${escapeHtml(c.vpn_public_ip)})</span>` : ''}</span>`
|
||
: (c.vpn_profile_name
|
||
? (c.kill_switch
|
||
? `<span class="pill" style="background:rgba(255,107,107,.15);color:var(--red);font-size:11px;font-weight:600">🛡️ ${t('vpn_killswitch_chk', 'Kill-Switch')}</span>`
|
||
: `<span class="pill" style="background:rgba(246,173,85,.15);color:#f6ad55;font-size:11px">⚠️ Direct</span>`)
|
||
: `<span class="muted" style="font-size:12px;display:inline-flex;align-items:center;gap:4px">🌐 ${t('topo_direct_wan', 'Direct WAN (Box)')}</span>`);
|
||
const ipLabel = c.ip || t('not_assigned', 'Non attribuée');
|
||
const nameLabel = String(c.name || t('name_unknown', 'Nom non communiqué')).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const blockBtnLabel = c.blocked ? t('btn_unblock', 'Débloquer') : t('btn_block', 'Bloquer');
|
||
const quotaBtnLabel = '⚖️ ' + t('th_quota', 'Quota');
|
||
return `<tr><td><div class="client"><div class="avatar">${String(c.name || '?')[0].toUpperCase()}</div><strong>${nameLabel}</strong></div></td><td>${ipLabel}</td><td>${c.mac || '—'}</td><td>${vpnHtml}</td><td>${signalQuality(c.signal_dbm, c)}</td><td>${speedHtml}</td><td><div style="display:inline-flex;gap:4px;align-items:center"><button class="secondary" type="button" style="padding:4px 8px;font-size:11px" onclick="openDeviceLimitsModal('${c.mac}')" title="${t('modal_limits_title', 'Gérer le quota et la limitation de débit')}">${quotaBtnLabel}</button><button class="secondary" type="button" onclick="toggleBlock('${c.mac}',${!c.blocked})">${blockBtnLabel}</button></div></td></tr>`;
|
||
}).join('') : `<tr><td colspan="7" class="empty">${t('no_clients', 'Aucun client connecté')}</td></tr>`;
|
||
|
||
renderPagination('clientsPagination', clientsPage, clients.length, 'changeClientsPage', 10);
|
||
qr();
|
||
}
|
||
|
||
window.changeClientsPage = (p) => { clientsPage = p; render(); };
|
||
|
||
let isLoadInProgress = false;
|
||
let loadFailureCount = 0;
|
||
|
||
async function load() {
|
||
if (isLoadInProgress) return;
|
||
isLoadInProgress = true;
|
||
try {
|
||
let [a, b] = await Promise.all([apiFetch('/api/status', { cache: 'no-store', timeout: 10000 }), apiFetch('/api/clients', { cache: 'no-store', timeout: 10000 })]);
|
||
if (!a.ok || !b.ok) {
|
||
const response = !a.ok ? a : b; let detail = 'HTTP ' + response.status;
|
||
try { const body = await response.json(); detail = body.error || detail; } catch (_) {}
|
||
throw Error(detail);
|
||
}
|
||
const nextStatus = await a.json(); const nextClients = await b.json();
|
||
const signature = nextClients.map(client => client.mac).sort().join('|');
|
||
const changed = previousClientSignature !== null && signature !== previousClientSignature;
|
||
status = nextStatus; clients = nextClients; previousClientSignature = signature;
|
||
loadFailureCount = 0;
|
||
render(); if (changed) { loadLogs(); } if (currentTab === 'devices') { loadDevices(); }
|
||
} catch (e) {
|
||
console.warn('Chargement API :', e);
|
||
const isAbort = e.name === 'AbortError' || e.name === 'TimeoutError' || (e.message && e.message.toLowerCase().includes('abort'));
|
||
if (isAbort && status && status.configured !== undefined) {
|
||
return;
|
||
}
|
||
loadFailureCount++;
|
||
if (loadFailureCount >= 3 || !status || status.configured === undefined) {
|
||
if ($('state')) $('state').textContent = 'API indisponible : ' + e.message;
|
||
}
|
||
} finally {
|
||
isLoadInProgress = false;
|
||
}
|
||
}
|
||
|
||
function renderLogsTable() {
|
||
const tbody = $('logs'); if (!tbody) return;
|
||
if (!logsDataCache || !logsDataCache.length) { tbody.innerHTML = '<tr><td colspan="5" class="empty">' + t('no_logs', 'Aucun journal disponible') + '</td></tr>'; renderPagination('logsPagination', 1, 0, 'changeLogsPage', 10); return }
|
||
const totalPages = Math.max(1, Math.ceil(logsDataCache.length / 10));
|
||
if (logsPage > totalPages) logsPage = totalPages; if (logsPage < 1) logsPage = 1;
|
||
const paged = logsDataCache.slice((logsPage - 1) * 10, logsPage * 10);
|
||
const labels = {
|
||
'connexion': t('log_connexion', '● Connexion Wi-Fi'),
|
||
'déconnexion': t('log_deconnexion', '○ Déconnexion Wi-Fi'),
|
||
'vpn_route': t('log_vpn_route', '🛡️ Routage VPN'),
|
||
'vpn_connect': t('log_vpn_connect', '🌐 Connexion VPN'),
|
||
'vpn_disconnect': t('log_vpn_disconnect', '🔌 Déconnexion VPN'),
|
||
'connexion_admin': t('log_connexion_admin', '● Connexion Admin'),
|
||
'connexion_code_recuperation': t('log_connexion_code_recuperation', '🔑 Connexion Code Secours'),
|
||
'echec_connexion': t('log_echec_connexion', '❌ Échec Connexion'),
|
||
'deconnexion_admin': t('log_deconnexion_admin', '○ Déconnexion Admin'),
|
||
'creation_compte_admin': t('log_creation_compte_admin', '👤 Création Compte'),
|
||
'modification_identifiants': t('log_modification_identifiants', '🔑 Modif. Identifiants'),
|
||
'generation_secret_2fa': t('log_generation_secret_2fa', '⚙️ Secret 2FA généré'),
|
||
'activation_2fa': t('log_activation_2fa', '🛡️ Activation 2FA'),
|
||
'desactivation_2fa': t('log_desactivation_2fa', '🔓 Désactivation 2FA'),
|
||
'regeneration_codes_secours': t('log_regeneration_codes_secours', '🔄 Nouveaux Codes Secours'),
|
||
'modification_preferences': t('log_modification_preferences', '🎨 Modif. Préférences'),
|
||
'suppression_journaux': t('log_suppression_journaux', '🗑️ Suppr. Journaux'),
|
||
'reinitialisation_donnees': t('log_reinitialisation_donnees', '⚠️ Réinitialisation Data'),
|
||
'limites_appareil_modifiees': t('log_limites_appareil_modifiees', '⚖️ Quota & Débit modifiés'),
|
||
'rejet_limite': t('log_rejet_limite', '⚠️ Limite atteinte (rejet)'),
|
||
'création': t('log_creation', '+ Création AP'),
|
||
'enregistrement_modifie': t('log_config_modified', '✓ Config AP modifiée'),
|
||
'blocage': t('log_blocage', '⛔ Blocage'),
|
||
'déblocage': t('log_deblocage', '✓ Déblocage'),
|
||
'démarrage': t('log_demarrage', '▶ Démarrage AP'),
|
||
'arrêt': t('log_arret', '■ Arrêt AP'),
|
||
'redémarrage': t('log_redemarrage', '↻ Redémarrage AP'),
|
||
'planification_sauvegarde_modifiee': t('log_planif_sauvegarde', '📅 Planification sauvegarde'),
|
||
'creation_sauvegarde_serveur': t('log_creation_sauvegarde', '💾 Sauvegarde créée'),
|
||
'sauvegarde_automatique': t('log_sauvegarde_auto', '⏰ Sauvegarde automatique'),
|
||
'suppression_sauvegarde': t('log_suppr_sauvegarde', '🗑️ Sauvegarde supprimée'),
|
||
'import_configuration_complete': t('log_restauration_sauvegarde', '📥 Sauvegarde restaurée'),
|
||
'configuration_stockage_distant': t('log_stockage_distant', '☁️ Stockage distant configuré'),
|
||
'televersement_distant_manuel': t('log_televersement_distant', '☁️ Téléversement distant'),
|
||
'recuperation_sauvegarde_distante': t('log_recup_distant', '☁️ Import depuis le drive'),
|
||
'suppression_sauvegarde_distante': t('log_suppr_distant', '🗑️ Suppr. sur le drive'),
|
||
'export_sauvegarde_complete': t('log_export_sauvegarde', '💾 Export sauvegarde'),
|
||
'export_base_sqlite': t('log_export_sqlite', '💾 Export SQLite'),
|
||
'export_configuration_json': t('log_export_json', '💾 Export JSON')
|
||
};
|
||
tbody.innerHTML = paged.map(log => {
|
||
const ev = String(log.event || '').toLowerCase();
|
||
let eventHtml;
|
||
if (ev === 'connexion' || ev === 'connexion_wifi' || ev === 'connexion wifi') {
|
||
eventHtml = '<span style="color:var(--green);font-weight:600">' + t('log_connexion', '● Connexion Wi-Fi') + '</span>';
|
||
} else if (ev === 'déconnexion' || ev === 'deconnexion' || ev === 'déconnexion_wifi' || ev === 'deconnexion_wifi' || ev === 'déconnexion wifi') {
|
||
eventHtml = '<span style="color:var(--red);font-weight:600">' + t('log_deconnexion', '○ Déconnexion Wi-Fi') + '</span>';
|
||
} else {
|
||
const label = labels[log.event] || log.event;
|
||
if (ev.includes('admin') || ev.includes('2fa') || ev === 'création' || ev === 'démarrage' || ev.includes('sauvegarde') || ev.includes('distant') || ev.includes('export')) {
|
||
eventHtml = `<span style="color:var(--blue);font-weight:600">${label}</span>`;
|
||
} else if (ev.includes('vpn') || ev === 'vpn_route' || ev === 'vpn_connect') {
|
||
eventHtml = `<span style="color:var(--green);font-weight:600">${label}</span>`;
|
||
} else if (ev === 'vpn_disconnect') {
|
||
eventHtml = `<span style="color:var(--yellow);font-weight:600">${label}</span>`;
|
||
} else if (ev.includes('echec') || ev.includes('blocage') || ev === 'arrêt' || ev.includes('rejet') || ev.includes('reinitialisation')) {
|
||
eventHtml = `<span style="color:var(--red);font-weight:600">${label}</span>`;
|
||
} else {
|
||
eventHtml = `<span style="font-weight:500">${label}</span>`;
|
||
}
|
||
}
|
||
const macCategoryMap = {
|
||
'AUTH': t('category_auth', 'Authentification'),
|
||
'CONFIG': t('category_config', 'Configuration'),
|
||
'SYSTEM': t('category_system', 'Système'),
|
||
'BACKUP': t('category_backup', 'Sauvegarde'),
|
||
'SETTINGS': t('category_settings', 'Paramètres'),
|
||
'VPN': 'VPN',
|
||
'AP': t('category_ap', 'Point d’accès')
|
||
};
|
||
const macText = macCategoryMap[log.mac] || (log.mac || '—');
|
||
const vpnBadgeLog = log.vpn_profile_name ?
|
||
(log.vpn_routed ? `<span class="pill pill-green pill-no-dot" style="font-size:10px;margin-left:6px;padding:2px 6px;vertical-align:middle" title="Routé via VPN">🛡️ ${escapeHtml(log.vpn_profile_name)}</span>` : `<span class="pill pill-no-dot" style="font-size:10px;margin-left:6px;padding:2px 6px;background:rgba(255,107,107,.15);color:var(--red);vertical-align:middle" title="Profil VPN coupé">⚠️ ${escapeHtml(log.vpn_profile_name)}</span>`) : '';
|
||
return `<tr><td>${log.time}</td><td>${eventHtml}</td><td>${escapeHtml(log.name || 'Nom non communiqué')}${vpnBadgeLog}</td><td>${log.ip || '—'}</td><td>${macText}</td></tr>`;
|
||
}).join('');
|
||
renderPagination('logsPagination', logsPage, logsDataCache.length, 'changeLogsPage', 10);
|
||
}
|
||
window.changeLogsPage = (p) => { logsPage = p; renderLogsTable() };
|
||
|
||
let isLogsLoading = false;
|
||
async function loadLogs() {
|
||
if (isLogsLoading) return;
|
||
isLogsLoading = true;
|
||
try { const response = await apiFetch('/api/logs', { cache: 'no-store', timeout: 10000 }); logsDataCache = await response.json(); renderLogsTable(); if ($('logsUpdated')) $('logsUpdated').textContent = formatLastUpdated(); }
|
||
catch (e) {
|
||
const isAbort = e.name === 'AbortError' || e.name === 'TimeoutError' || (e.message && e.message.toLowerCase().includes('abort'));
|
||
if (isAbort && logsDataCache && logsDataCache.length > 0) return;
|
||
$('logs').innerHTML = '<tr><td colspan="5" class="empty">API indisponible</td></tr>'; renderPagination('logsPagination', 1, 0, 'changeLogsPage', 10);
|
||
} finally {
|
||
isLogsLoading = false;
|
||
}
|
||
}
|
||
|
||
function renderBlockedTable() {
|
||
const tbody = $('blockedClients'); if (!tbody) return;
|
||
if (!blockedDataCache || !blockedDataCache.length) { tbody.innerHTML = '<tr><td colspan="4" class="empty">' + t('no_blocked_clients', 'Aucun appareil bloqué') + '</td></tr>'; renderPagination('blockedPagination', 1, 0, 'changeBlockedPage', 10); return }
|
||
const totalPages = Math.max(1, Math.ceil(blockedDataCache.length / 10));
|
||
if (blockedPage > totalPages) blockedPage = totalPages; if (blockedPage < 1) blockedPage = 1;
|
||
const paged = blockedDataCache.slice((blockedPage - 1) * 10, blockedPage * 10);
|
||
tbody.innerHTML = paged.map(c => `<tr><td><div class="client"><div class="avatar">${String(c.name || '?')[0].toUpperCase()}</div><strong>${String(c.name || t('unknown_client', 'Nom non communiqué')).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';')}</strong></div></td><td>${c.mac}</td><td>${c.blocked_at}</td><td><button class="secondary" type="button" onclick="toggleBlock('${c.mac}',false);setTimeout(loadBlocked,300)">${t('unblock', 'Débloquer')}</button></td></tr>`).join('');
|
||
renderPagination('blockedPagination', blockedPage, blockedDataCache.length, 'changeBlockedPage', 10);
|
||
}
|
||
window.changeBlockedPage = (p) => { blockedPage = p; renderBlockedTable() };
|
||
|
||
let isBlockedLoading = false;
|
||
async function loadBlocked() {
|
||
if (isBlockedLoading) return;
|
||
isBlockedLoading = true;
|
||
try { const response = await apiFetch('/api/clients/blocked', { cache: 'no-store', timeout: 10000 }); if (!response.ok) throw Error('API indisponible'); blockedDataCache = await response.json(); renderBlockedTable(); if ($('blockedUpdated')) $('blockedUpdated').textContent = formatLastUpdated(); }
|
||
catch (e) {
|
||
const isAbort = e.name === 'AbortError' || e.name === 'TimeoutError' || (e.message && e.message.toLowerCase().includes('abort'));
|
||
if (isAbort && blockedDataCache && blockedDataCache.length > 0) return;
|
||
$('blockedClients').innerHTML = '<tr><td colspan="4" class="empty">API indisponible</td></tr>'; renderPagination('blockedPagination', 1, 0, 'changeBlockedPage', 10);
|
||
} finally {
|
||
isBlockedLoading = false;
|
||
}
|
||
}
|
||
|
||
/* --- Gestion de l'onglet Appareils (Historique BDD et statut en direct) --- */
|
||
async function loadDevices() {
|
||
if (isDevicesLoading) return;
|
||
isDevicesLoading = true;
|
||
try {
|
||
const res = await apiFetch('/api/devices', { cache: 'no-store', timeout: 10000 });
|
||
if (!res.ok) throw new Error('API indisponible');
|
||
const data = await res.json();
|
||
devicesDataCache = data.devices || [];
|
||
|
||
const totalCount = data.total ?? devicesDataCache.length;
|
||
const connectedCount = data.connected_count ?? devicesDataCache.filter(d => d.connected).length;
|
||
const offlineCount = data.offline_count ?? devicesDataCache.filter(d => !d.connected).length;
|
||
const blockedCount = data.blocked_count ?? devicesDataCache.filter(d => d.blocked).length;
|
||
|
||
if ($('metricDevicesTotal')) $('metricDevicesTotal').textContent = totalCount;
|
||
if ($('metricDevicesConnected')) $('metricDevicesConnected').textContent = connectedCount;
|
||
if ($('metricDevicesOffline')) $('metricDevicesOffline').textContent = offlineCount;
|
||
if ($('metricDevicesBlocked')) $('metricDevicesBlocked').textContent = blockedCount;
|
||
|
||
if ($('filterCountAll')) $('filterCountAll').textContent = totalCount;
|
||
if ($('filterCountConn')) $('filterCountConn').textContent = connectedCount;
|
||
if ($('filterCountOff')) $('filterCountOff').textContent = offlineCount;
|
||
if ($('filterCountBlock')) $('filterCountBlock').textContent = blockedCount;
|
||
|
||
renderDevicesTable();
|
||
if ($('devicesUpdated')) $('devicesUpdated').textContent = formatLastUpdated();
|
||
} catch (e) {
|
||
const isAbort = e.name === 'AbortError' || e.name === 'TimeoutError' || (e.message && e.message.toLowerCase().includes('abort'));
|
||
if (isAbort && devicesDataCache && devicesDataCache.length > 0) return;
|
||
const tbody = $('devicesTableBody');
|
||
if (tbody) tbody.innerHTML = '<tr><td colspan="7" class="empty">API indisponible : ' + escapeHtml(e.message) + '</td></tr>';
|
||
renderPagination('devicesPagination', 1, 0, 'changeDevicesPage', 10);
|
||
} finally {
|
||
isDevicesLoading = false;
|
||
}
|
||
}
|
||
|
||
function renderDevicesTable() {
|
||
const tbody = $('devicesTableBody');
|
||
if (!tbody) return;
|
||
|
||
let filtered = devicesDataCache.filter(d => {
|
||
if (devicesFilter === 'connected' && !d.connected) return false;
|
||
if (devicesFilter === 'offline' && d.connected) return false;
|
||
if (devicesFilter === 'blocked' && !d.blocked) return false;
|
||
if (devicesSearchQuery) {
|
||
const q = devicesSearchQuery;
|
||
const m = (d.name || '').toLowerCase().includes(q) ||
|
||
(d.mac || '').toLowerCase().includes(q) ||
|
||
(d.ip || '').toLowerCase().includes(q);
|
||
if (!m) return false;
|
||
}
|
||
return true;
|
||
});
|
||
|
||
const paged = filtered.slice((devicesPage - 1) * 10, devicesPage * 10);
|
||
tbody.innerHTML = paged.map(d => {
|
||
const icon = getDeviceTypeIcon(d.device_type);
|
||
const devTypeLabel = getDeviceTypeLabel(d.device_type);
|
||
|
||
let statusPill = '';
|
||
if (d.blocked) {
|
||
statusPill = `<span style="color:var(--red);font-weight:600;display:inline-flex;align-items:center;gap:6px">🔴 ${t('status_blocked', 'Bloqué')}</span>`;
|
||
} else if (d.connected) {
|
||
statusPill = `<span style="color:var(--green);font-weight:600;display:inline-flex;align-items:center;gap:6px">🟢 ${t('status_connected', 'Connecté')}</span>`;
|
||
} else {
|
||
statusPill = `<span style="color:var(--muted);font-weight:500;display:inline-flex;align-items:center;gap:6px">⚪ ${t('status_offline', 'Hors ligne')}</span>`;
|
||
}
|
||
|
||
const vpnBadge = d.vpn_profile_name ? `<span class="pill" style="background:rgba(56,189,248,0.12);color:var(--blue);font-size:10px;margin-left:4px">🛡️ ${escapeHtml(d.vpn_profile_name)}</span>` : '';
|
||
const ipDisplay = d.ip && d.ip !== 'Non attribuée' ? `<code>${escapeHtml(d.ip)}</code>` : `<span class="muted">${t('not_assigned', 'Non attribuée')}</span>`;
|
||
|
||
let limitsHtml = '';
|
||
const lim = d.limits;
|
||
if (lim && (lim.quota_enabled || lim.bandwidth_enabled)) {
|
||
const parts = [];
|
||
if (lim.quota_enabled && lim.quota_bytes > 0) {
|
||
if (lim.quota_exceeded) {
|
||
parts.push(`
|
||
<div style="display:flex;flex-direction:column;gap:3px">
|
||
<span class="pill" style="background:rgba(239,68,68,0.15);color:var(--red);font-size:10px;font-weight:bold;padding:2px 6px">🚫 ${t('modal_quota_exceeded', 'Quota dépassé')} (${escapeHtml(lim.usage_bytes_str || '')} / ${escapeHtml(lim.quota_bytes_str || '')})</span>
|
||
<div style="background:rgba(239,68,68,0.2);height:4px;border-radius:2px;overflow:hidden;width:100%"><div style="background:var(--red);width:100%;height:100%"></div></div>
|
||
</div>
|
||
`);
|
||
} else {
|
||
const pct = Math.min(100, Math.max(0, lim.usage_percent || 0));
|
||
const barColor = pct >= 85 ? '#f59e0b' : 'var(--blue)';
|
||
parts.push(`
|
||
<div style="display:flex;flex-direction:column;gap:3px;min-width:110px">
|
||
<div style="display:flex;justify-content:space-between;font-size:11px;font-weight:500">
|
||
<span>📊 ${escapeHtml(lim.usage_bytes_str || '')} / ${escapeHtml(lim.quota_bytes_str || '')}</span>
|
||
<span class="muted" style="font-size:10px">${pct}%</span>
|
||
</div>
|
||
<div style="background:var(--line);height:4px;border-radius:2px;overflow:hidden;width:100%"><div style="background:${barColor};width:${pct}%;height:100%"></div></div>
|
||
</div>
|
||
`);
|
||
}
|
||
}
|
||
if (lim.bandwidth_enabled && (lim.rate_down_kbps > 0 || lim.rate_up_kbps > 0)) {
|
||
parts.push(`<div class="muted" style="font-size:11px;margin-top:2px">⚡ ${t('th_speed', 'Débit')} : ↓ ${escapeHtml(lim.rate_down_str || '')} • ↑ ${escapeHtml(lim.rate_up_str || '')}</div>`);
|
||
}
|
||
limitsHtml = parts.join('');
|
||
}
|
||
if (!limitsHtml) {
|
||
limitsHtml = `<span class="muted" style="font-size:12px">${t('unlimited', 'Illimité')}</span>`;
|
||
}
|
||
|
||
const nameHtml = escapeHtml(d.name || t('client_unknown', 'Client inconnu'));
|
||
const macHtml = escapeHtml(d.mac || '—');
|
||
let lastSeenHtml = '—';
|
||
if (d.connected) {
|
||
lastSeenHtml = `<span style="color:var(--green);font-weight:600">${t('currently_online', 'Actuellement en ligne')}</span>`;
|
||
} else if (d.last_seen && d.last_seen !== '—' && d.last_seen !== 'Inconnue' && d.last_seen !== 'Unknown' && d.last_seen !== 'Actuellement en ligne' && d.last_seen !== 'Currently online') {
|
||
lastSeenHtml = escapeHtml(d.last_seen);
|
||
} else {
|
||
lastSeenHtml = `<span class="muted">${t('unknown_f', 'Inconnue')}</span>`;
|
||
}
|
||
const firstSeenHtml = escapeHtml(d.first_seen || '—');
|
||
|
||
return `<tr>
|
||
<td>
|
||
<div class="client">
|
||
<div class="avatar" style="font-size:16px;cursor:pointer;position:relative" title="${t('modal_device_type_click', 'Cliquer pour changer le type d’appareil')}" onclick="openDeviceTypeModal('${escapeHtml(d.mac)}')">
|
||
${icon}
|
||
<span style="position:absolute;bottom:-3px;right:-3px;font-size:9px;background:var(--panel);border:1px solid var(--line);border-radius:50%;width:14px;height:14px;display:flex;align-items:center;justify-content:center;line-height:1">✏️</span>
|
||
</div>
|
||
<div>
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<strong>${nameHtml}</strong>
|
||
${vpnBadge}
|
||
</div>
|
||
<div class="muted" style="font-size:11px;margin-top:2px">
|
||
<span style="cursor:pointer;color:var(--blue);text-decoration:underline dashed;text-underline-offset:2px" onclick="openDeviceTypeModal('${escapeHtml(d.mac)}')" title="${t('modal_device_type_title', 'Modifier le type d’appareil')}">${escapeHtml(devTypeLabel)}</span> • ${d.connected ? t('status_online_live', 'En direct') : t('stored_in_db', 'Mémorisé en BDD')}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</td>
|
||
<td><code>${macHtml}</code></td>
|
||
<td>${ipDisplay}</td>
|
||
<td>${statusPill}</td>
|
||
<td>${limitsHtml}</td>
|
||
<td><span style="font-size:13px">${lastSeenHtml}</span></td>
|
||
<td><span class="muted" style="font-size:12px">${firstSeenHtml}</span></td>
|
||
<td style="text-align:right">
|
||
<div style="display:inline-flex;gap:4px;align-items:center;justify-content:flex-end">
|
||
<button class="secondary" type="button" style="padding:4px 9px;font-size:12px;display:inline-flex;align-items:center;gap:3px" onclick="openDeviceLimitsModal('${escapeHtml(d.mac)}')" title="${t('modal_limits_title_attr', 'Définir un quota et limiter la bande passante')}">⚖️ <span style="font-size:10px">${t('th_quota', 'Quota')}</span></button>
|
||
<button class="secondary" type="button" style="padding:4px 9px;font-size:12px" onclick="openDeviceTypeModal('${escapeHtml(d.mac)}')" title="${t('modal_device_type_attr', 'Modifier le type d’appareil (Smartphone, Tablette, PC, TV...)')}">🏷️</button>
|
||
<button class="secondary" type="button" style="padding:4px 9px;font-size:12px" onclick="renameDevice('${escapeHtml(d.mac)}')" title="${t('rename_device_attr', 'Renommer cet appareil')}">✏️</button>
|
||
<button class="secondary" type="button" style="padding:4px 9px;font-size:12px;${d.blocked ? 'color:var(--green)' : 'color:var(--red)'}" onclick="toggleBlockDevice('${escapeHtml(d.mac)}', ${!d.blocked})" title="${d.blocked ? t('unblock', 'Débloquer') : t('block', 'Bloquer')}">${d.blocked ? '✅' : '🔴'}</button>
|
||
${!d.connected ? `<button class="secondary" type="button" style="padding:4px 9px;font-size:12px;color:var(--muted)" onclick="deleteDeviceHistory('${escapeHtml(d.mac)}')" title="${t('delete_history_attr', "Supprimer de l'historique BDD")}">🗑️</button>` : ''}
|
||
</div>
|
||
</td>
|
||
</tr>`;
|
||
}).join('');
|
||
|
||
renderPagination('devicesPagination', devicesPage, filtered.length, 'changeDevicesPage', 10);
|
||
}
|
||
|
||
window.changeDevicesPage = (p) => { devicesPage = p; renderDevicesTable(); };
|
||
|
||
window.onDevicesSearch = (q) => {
|
||
devicesSearchQuery = (q || '').trim().toLowerCase();
|
||
devicesPage = 1;
|
||
renderDevicesTable();
|
||
};
|
||
|
||
window.setDevicesFilter = (f) => {
|
||
devicesFilter = f;
|
||
devicesPage = 1;
|
||
['all', 'connected', 'offline', 'blocked'].forEach(type => {
|
||
const btn = $('btnFilterDev' + type.charAt(0).toUpperCase() + type.slice(1));
|
||
if (btn) btn.classList.toggle('active', f === type);
|
||
});
|
||
renderDevicesTable();
|
||
};
|
||
|
||
async function renameDevice(mac) {
|
||
const dev = devicesDataCache.find(d => d.mac.toUpperCase() === mac.toUpperCase());
|
||
const currentName = dev ? dev.name : '';
|
||
const newName = prompt(t('prompt_device_name', "Entrez un nom personnalisé pour cet appareil :"), currentName || "");
|
||
if (newName === null) return;
|
||
const trimmed = newName.trim();
|
||
if (!trimmed) return;
|
||
try {
|
||
const res = await apiFetch('/api/devices/rename', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ mac, name: trimmed })
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur lors du renommage');
|
||
await loadDevices();
|
||
await load();
|
||
} catch (e) {
|
||
alert(tErr(e.message));
|
||
}
|
||
}
|
||
|
||
async function toggleBlockDevice(mac, blocked) {
|
||
try {
|
||
await toggleBlock(mac, blocked);
|
||
await loadDevices();
|
||
if (typeof loadBlocked === 'function') loadBlocked();
|
||
} catch (e) {
|
||
alert(tErr(e.message));
|
||
}
|
||
}
|
||
|
||
async function deleteDeviceHistory(mac) {
|
||
const dev = devicesDataCache.find(d => d.mac.toUpperCase() === mac.toUpperCase());
|
||
const name = dev ? dev.name : mac;
|
||
if (!confirm(t('confirm_delete_device', "Voulez-vous vraiment supprimer l'appareil « {name} » ({mac}) de la base de données ?").replace('{name}', name).replace('{mac}', mac))) return;
|
||
try {
|
||
const res = await apiFetch('/api/devices/delete', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ mac })
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur lors de la suppression');
|
||
await loadDevices();
|
||
} catch (e) {
|
||
alert(tErr(e.message));
|
||
}
|
||
}
|
||
|
||
/* ============================================================
|
||
Gestion des Quotas & Limitation de Débit par Appareil
|
||
============================================================ */
|
||
let currentLimitsDev = null;
|
||
|
||
async function openDeviceLimitsModal(mac) {
|
||
const cleanMac = (mac || '').toUpperCase();
|
||
let dev = (devicesDataCache || []).find(d => (d.mac || '').toUpperCase() === cleanMac);
|
||
if (!dev && typeof clients !== 'undefined' && Array.isArray(clients)) {
|
||
dev = clients.find(c => (c.mac || '').toUpperCase() === cleanMac);
|
||
}
|
||
if (!dev) dev = { mac: cleanMac, name: 'Client ' + cleanMac.replace(/:/g, '').slice(-4), ip: '—', device_type: 'generic' };
|
||
|
||
currentLimitsDev = { ...dev };
|
||
if ($('limitsModalMac')) $('limitsModalMac').value = cleanMac;
|
||
if ($('limitsDevName')) $('limitsDevName').textContent = dev.name || 'Client sans nom';
|
||
if ($('limitsDevMac')) $('limitsDevMac').textContent = cleanMac;
|
||
if ($('limitsDevIp')) $('limitsDevIp').textContent = dev.ip && dev.ip !== 'Non attribuée' ? dev.ip : 'Non attribuée';
|
||
if ($('limitsDevAvatar')) $('limitsDevAvatar').innerHTML = getDeviceTypeIcon(dev.device_type);
|
||
if ($('deviceLimitsMsg')) $('deviceLimitsMsg').style.display = 'none';
|
||
|
||
function applyLimitsToForm(lim) {
|
||
lim = lim || {};
|
||
if ($('chkLimitsQuotaEnabled')) $('chkLimitsQuotaEnabled').checked = !!lim.quota_enabled;
|
||
|
||
// Quota bytes -> valeur + unité
|
||
const qBytes = lim.quota_bytes || 0;
|
||
if (qBytes > 0) {
|
||
if (qBytes % 1073741824 === 0 || qBytes >= 1073741824) {
|
||
if ($('inputQuotaValue')) $('inputQuotaValue').value = (qBytes / 1073741824);
|
||
if ($('selectQuotaUnit')) $('selectQuotaUnit').value = 'GB';
|
||
} else {
|
||
if ($('inputQuotaValue')) $('inputQuotaValue').value = Math.round(qBytes / 1048576);
|
||
if ($('selectQuotaUnit')) $('selectQuotaUnit').value = 'MB';
|
||
}
|
||
} else {
|
||
if ($('inputQuotaValue')) $('inputQuotaValue').value = 10;
|
||
if ($('selectQuotaUnit')) $('selectQuotaUnit').value = 'GB';
|
||
}
|
||
if ($('selectQuotaPeriod')) $('selectQuotaPeriod').value = lim.quota_period || 'total';
|
||
|
||
// Bande passante
|
||
if ($('chkLimitsBwEnabled')) $('chkLimitsBwEnabled').checked = !!lim.bandwidth_enabled;
|
||
const downKbps = lim.rate_down_kbps || 0;
|
||
if (downKbps >= 1000 && downKbps % 1000 === 0) {
|
||
if ($('inputRateDown')) $('inputRateDown').value = downKbps / 1000;
|
||
if ($('selectRateDownUnit')) $('selectRateDownUnit').value = 'Mbps';
|
||
} else {
|
||
if ($('inputRateDown')) $('inputRateDown').value = downKbps || 10;
|
||
if ($('selectRateDownUnit')) $('selectRateDownUnit').value = downKbps ? 'Kbps' : 'Mbps';
|
||
}
|
||
|
||
const upKbps = lim.rate_up_kbps || 0;
|
||
if (upKbps >= 1000 && upKbps % 1000 === 0) {
|
||
if ($('inputRateUp')) $('inputRateUp').value = upKbps / 1000;
|
||
if ($('selectRateUpUnit')) $('selectRateUpUnit').value = 'Mbps';
|
||
} else {
|
||
if ($('inputRateUp')) $('inputRateUp').value = upKbps || 5;
|
||
if ($('selectRateUpUnit')) $('selectRateUpUnit').value = upKbps ? 'Kbps' : 'Mbps';
|
||
}
|
||
|
||
toggleQuotaInputs();
|
||
toggleBwInputs();
|
||
updateQuotaPreview();
|
||
}
|
||
|
||
// Appliquer immédiatement les données en cache pour ouverture instantanée
|
||
applyLimitsToForm(currentLimitsDev.limits || {});
|
||
|
||
const modal = $('modalDeviceLimits');
|
||
if (modal) modal.classList.add('active');
|
||
|
||
// Rafraîchir en arrière-plan depuis l'API
|
||
try {
|
||
const res = await apiFetch(`/api/devices/limits?mac=${encodeURIComponent(cleanMac)}`, { timeout: 15000 });
|
||
if (res.ok) {
|
||
const data = await res.json();
|
||
if (data && data.limits) {
|
||
currentLimitsDev.limits = data.limits;
|
||
applyLimitsToForm(currentLimitsDev.limits);
|
||
}
|
||
}
|
||
} catch (e) {
|
||
console.warn("Impossible de rafraîchir les limites de l'appareil :", e);
|
||
}
|
||
}
|
||
|
||
function closeDeviceLimitsModal() {
|
||
const modal = $('modalDeviceLimits');
|
||
if (modal) modal.classList.remove('active');
|
||
currentLimitsDev = null;
|
||
}
|
||
|
||
function toggleQuotaInputs() {
|
||
const enabled = $('chkLimitsQuotaEnabled') && $('chkLimitsQuotaEnabled').checked;
|
||
const container = $('quotaInputsContainer');
|
||
if (container) container.style.display = enabled ? 'flex' : 'none';
|
||
updateQuotaPreview();
|
||
}
|
||
|
||
function toggleBwInputs() {
|
||
const enabled = $('chkLimitsBwEnabled') && $('chkLimitsBwEnabled').checked;
|
||
const container = $('bwInputsContainer');
|
||
if (container) container.style.display = enabled ? 'flex' : 'none';
|
||
}
|
||
|
||
function setQuotaPreset(val, unit) {
|
||
if ($('inputQuotaValue')) $('inputQuotaValue').value = val;
|
||
if ($('selectQuotaUnit')) $('selectQuotaUnit').value = unit;
|
||
updateQuotaPreview();
|
||
}
|
||
|
||
function setBwPreset(downMbps, upMbps) {
|
||
if ($('inputRateDown')) $('inputRateDown').value = downMbps;
|
||
if ($('selectRateDownUnit')) $('selectRateDownUnit').value = 'Mbps';
|
||
if ($('inputRateUp')) $('inputRateUp').value = upMbps;
|
||
if ($('selectRateUpUnit')) $('selectRateUpUnit').value = 'Mbps';
|
||
}
|
||
|
||
async function onQuotaPeriodChanged() {
|
||
if (!currentLimitsDev) return;
|
||
try {
|
||
const res = await apiFetch(`/api/devices/limits?mac=${encodeURIComponent(currentLimitsDev.mac)}`);
|
||
if (res.ok) {
|
||
const data = await res.json();
|
||
if (data && data.limits) {
|
||
currentLimitsDev.limits = data.limits;
|
||
}
|
||
}
|
||
} catch (_) { }
|
||
updateQuotaPreview();
|
||
}
|
||
|
||
function updateQuotaPreview() {
|
||
if (!currentLimitsDev) return;
|
||
const lim = currentLimitsDev.limits || {};
|
||
const usageBytes = lim.usage_bytes || 0;
|
||
const usageStr = lim.usage_bytes_str || formatBytes(usageBytes);
|
||
|
||
let qVal = parseFloat($('inputQuotaValue') ? $('inputQuotaValue').value : 0) || 0;
|
||
const qUnit = $('selectQuotaUnit') ? $('selectQuotaUnit').value : 'GB';
|
||
const qBytes = qUnit === 'GB' ? Math.round(qVal * 1073741824) : Math.round(qVal * 1048576);
|
||
|
||
const exceeded = qBytes > 0 && usageBytes >= qBytes;
|
||
const pct = qBytes > 0 ? Math.min(100, Math.round((usageBytes / qBytes) * 100)) : 0;
|
||
const remaining = Math.max(0, qBytes - usageBytes);
|
||
|
||
if ($('quotaExceededBadge')) $('quotaExceededBadge').style.display = exceeded ? 'inline-block' : 'none';
|
||
|
||
if ($('quotaUsageLabel')) {
|
||
$('quotaUsageLabel').textContent = `${usageStr} / ${formatBytes(qBytes)} (${pct}%)`;
|
||
$('quotaUsageLabel').style.color = exceeded ? 'var(--red)' : (pct >= 85 ? '#f59e0b' : 'var(--text)');
|
||
}
|
||
if ($('quotaUsageBar')) {
|
||
$('quotaUsageBar').style.width = `${pct}%`;
|
||
$('quotaUsageBar').style.background = exceeded ? 'var(--red)' : (pct >= 85 ? '#f59e0b' : 'var(--blue)');
|
||
}
|
||
if ($('quotaRemainingLabel')) {
|
||
$('quotaRemainingLabel').textContent = exceeded ? t('modal_quota_exhausted', 'Quota épuisé (0 o restant)') : `${t('modal_quota_remaining', 'Reste :')} ${formatBytes(remaining)}`;
|
||
$('quotaRemainingLabel').style.color = exceeded ? 'var(--red)' : 'var(--muted)';
|
||
}
|
||
}
|
||
|
||
async function resetDeviceTrafficUsage() {
|
||
if (!currentLimitsDev) return;
|
||
const mac = currentLimitsDev.mac;
|
||
const name = currentLimitsDev.name || mac;
|
||
if (!confirm(t('confirm_reset_quota', "Voulez-vous remettre à zéro le compteur de données de l'appareil « {name} » ?").replace('{name}', name))) return;
|
||
|
||
try {
|
||
const res = await apiFetch('/api/devices/limits', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
timeout: 30000,
|
||
body: JSON.stringify({
|
||
mac: mac,
|
||
quota_enabled: $('chkLimitsQuotaEnabled') && $('chkLimitsQuotaEnabled').checked,
|
||
quota_bytes: getSelectedQuotaBytes(),
|
||
quota_period: $('selectQuotaPeriod') ? $('selectQuotaPeriod').value : 'total',
|
||
bandwidth_enabled: $('chkLimitsBwEnabled') && $('chkLimitsBwEnabled').checked,
|
||
rate_down_kbps: getSelectedRateDownKbps(),
|
||
rate_up_kbps: getSelectedRateUpKbps(),
|
||
reset_usage: true
|
||
})
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur lors de la réinitialisation');
|
||
|
||
if (d.limits) currentLimitsDev.limits = d.limits;
|
||
updateQuotaPreview();
|
||
const msg = $('deviceLimitsMsg');
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(50,213,131,0.15)';
|
||
msg.style.color = 'var(--green)';
|
||
msg.textContent = t('modal_counter_reset_ok', '✓ Compteur de consommation remis à zéro !');
|
||
setTimeout(() => { if (msg) msg.style.display = 'none'; }, 4000);
|
||
}
|
||
try { await loadDevices(); } catch (_) { }
|
||
try { await load(); } catch (_) { }
|
||
} catch (e) {
|
||
alert(tErr(e.message));
|
||
}
|
||
}
|
||
|
||
function getSelectedQuotaBytes() {
|
||
const val = parseFloat($('inputQuotaValue') ? $('inputQuotaValue').value : 0) || 0;
|
||
const unit = $('selectQuotaUnit') ? $('selectQuotaUnit').value : 'GB';
|
||
return unit === 'GB' ? Math.round(val * 1073741824) : Math.round(val * 1048576);
|
||
}
|
||
|
||
function getSelectedRateDownKbps() {
|
||
const val = parseFloat($('inputRateDown') ? $('inputRateDown').value : 0) || 0;
|
||
const unit = $('selectRateDownUnit') ? $('selectRateDownUnit').value : 'Mbps';
|
||
return unit === 'Mbps' ? Math.round(val * 1000) : Math.round(val);
|
||
}
|
||
|
||
function getSelectedRateUpKbps() {
|
||
const val = parseFloat($('inputRateUp') ? $('inputRateUp').value : 0) || 0;
|
||
const unit = $('selectRateUpUnit') ? $('selectRateUpUnit').value : 'Mbps';
|
||
return unit === 'Mbps' ? Math.round(val * 1000) : Math.round(val);
|
||
}
|
||
|
||
async function submitDeviceLimits() {
|
||
if (!currentLimitsDev) return;
|
||
const mac = currentLimitsDev.mac;
|
||
const btn = $('btnSaveDeviceLimits');
|
||
const msg = $('deviceLimitsMsg');
|
||
|
||
const quotaEnabled = $('chkLimitsQuotaEnabled') && $('chkLimitsQuotaEnabled').checked;
|
||
const quotaBytes = getSelectedQuotaBytes();
|
||
const quotaPeriod = $('selectQuotaPeriod') ? $('selectQuotaPeriod').value : 'total';
|
||
|
||
const bwEnabled = $('chkLimitsBwEnabled') && $('chkLimitsBwEnabled').checked;
|
||
const rateDownKbps = getSelectedRateDownKbps();
|
||
const rateUpKbps = getSelectedRateUpKbps();
|
||
|
||
if (btn) { btn.disabled = true; btn.textContent = t('loading', 'Enregistrement…'); }
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||
msg.style.color = 'var(--blue)';
|
||
msg.textContent = t('modal_saving', 'Application des quotas et limitations réseau…');
|
||
}
|
||
|
||
try {
|
||
const res = await apiFetch('/api/devices/limits', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
timeout: 30000,
|
||
body: JSON.stringify({
|
||
mac,
|
||
quota_enabled: quotaEnabled,
|
||
quota_bytes: quotaBytes,
|
||
quota_period: quotaPeriod,
|
||
bandwidth_enabled: bwEnabled,
|
||
rate_down_kbps: rateDownKbps,
|
||
rate_up_kbps: rateUpKbps,
|
||
quota_action: 'block'
|
||
})
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur lors de l’enregistrement');
|
||
|
||
if (msg) {
|
||
msg.style.background = 'rgba(50,213,131,0.15)';
|
||
msg.style.color = 'var(--green)';
|
||
msg.textContent = t('modal_saved_ok', '✓ Limitations enregistrées et appliquées avec succès !');
|
||
}
|
||
|
||
setTimeout(() => {
|
||
closeDeviceLimitsModal();
|
||
}, 900);
|
||
|
||
try { await loadDevices(); } catch (_) { }
|
||
try { await load(); } catch (_) { }
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.background = 'rgba(239,68,68,0.15)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = tErr(e.message);
|
||
}
|
||
} finally {
|
||
if (btn) { btn.disabled = false; btn.innerHTML = '<span>💾</span> ' + t('modal_save_limits', 'Enregistrer les limitations'); }
|
||
}
|
||
}
|
||
|
||
let selectedDeviceType = 'generic';
|
||
|
||
function openDeviceTypeModal(mac) {
|
||
const dev = devicesDataCache.find(d => d.mac.toUpperCase() === mac.toUpperCase());
|
||
if (!dev) return;
|
||
$('deviceTypeModalMac').value = dev.mac;
|
||
$('deviceTypeModalName').textContent = dev.name || 'Client sans nom';
|
||
$('deviceTypeModalMacDisplay').textContent = dev.mac;
|
||
|
||
const statusEl = $('deviceTypeModalStatus');
|
||
if (statusEl) {
|
||
if (dev.blocked) {
|
||
statusEl.className = 'pill';
|
||
statusEl.style.cssText = 'background:rgba(255,107,107,.15);color:var(--red);border:1px solid rgba(255,107,107,.3);font-size:11px;font-weight:600';
|
||
statusEl.textContent = '🔴 ' + t('status_blocked', 'Bloqué');
|
||
} else if (dev.connected) {
|
||
statusEl.className = 'pill pill-green pill-no-dot';
|
||
statusEl.style.cssText = 'font-size:11px;font-weight:600';
|
||
statusEl.textContent = '🟢 ' + t('status_connected', 'Connecté');
|
||
} else {
|
||
statusEl.className = 'pill';
|
||
statusEl.style.cssText = 'background:var(--panel2);color:var(--muted);font-size:11px';
|
||
statusEl.textContent = '⚪ ' + t('status_offline_conn', 'Hors connexion');
|
||
}
|
||
}
|
||
|
||
selectedDeviceType = dev.device_type || 'generic';
|
||
renderDeviceTypeGrid();
|
||
if ($('deviceTypeModalMsg')) $('deviceTypeModalMsg').textContent = '';
|
||
$('modalDeviceType').classList.add('active');
|
||
}
|
||
|
||
function closeDeviceTypeModal() {
|
||
$('modalDeviceType').classList.remove('active');
|
||
}
|
||
|
||
function renderDeviceTypeGrid() {
|
||
const grid = $('deviceTypeOptionsGrid');
|
||
if (!grid) return;
|
||
grid.innerHTML = DEVICE_TYPE_LIST.map(opt => {
|
||
const isSelected = selectedDeviceType === opt.id;
|
||
return `
|
||
<div onclick="selectDeviceTypeChoice('${opt.id}')" ondblclick="saveDeviceType()" style="cursor:pointer;padding:10px 12px;border-radius:8px;border:1.5px solid ${isSelected ? 'var(--blue)' : 'var(--line)'};background:${isSelected ? 'rgba(56,189,248,0.1)' : 'var(--panel2)'};transition:all 0.15s ease;display:flex;flex-direction:column;gap:3px;user-select:none">
|
||
<div style="display:flex;align-items:center;justify-content:space-between">
|
||
<span style="font-size:18px">${opt.icon}</span>
|
||
${isSelected ? '<span style="color:var(--blue);font-size:12px;font-weight:bold">✓</span>' : ''}
|
||
</div>
|
||
<div style="font-weight:${isSelected ? '700' : '600'};font-size:13px;color:${isSelected ? 'var(--blue)' : 'var(--text)'};margin-top:2px">${escapeHtml(opt.label)}</div>
|
||
<div class="muted" style="font-size:10px;line-height:1.2">${escapeHtml(opt.desc)}</div>
|
||
</div>
|
||
`;
|
||
}).join('');
|
||
}
|
||
|
||
function selectDeviceTypeChoice(typeId) {
|
||
selectedDeviceType = typeId;
|
||
renderDeviceTypeGrid();
|
||
}
|
||
|
||
async function saveDeviceType() {
|
||
const mac = $('deviceTypeModalMac').value;
|
||
if (!mac) return;
|
||
const btn = $('btnSaveDeviceType');
|
||
const msg = $('deviceTypeModalMsg');
|
||
if (btn) btn.disabled = true;
|
||
if (msg) { msg.textContent = 'Enregistrement en cours…'; msg.style.color = 'var(--muted)'; }
|
||
try {
|
||
const res = await apiFetch('/api/devices/set_type', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ mac: mac, device_type: selectedDeviceType })
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur lors de la modification');
|
||
|
||
// Update local cache immediately
|
||
const dev = devicesDataCache.find(d => d.mac.toUpperCase() === mac.toUpperCase());
|
||
if (dev) dev.device_type = selectedDeviceType;
|
||
renderDevicesTable();
|
||
closeDeviceTypeModal();
|
||
} catch (e) {
|
||
if (msg) { msg.textContent = tErr(e.message); msg.style.color = 'var(--red)'; }
|
||
} finally {
|
||
if (btn) btn.disabled = false;
|
||
}
|
||
}
|
||
/* ========================================================
|
||
Gestion des catégories et logos de types d'appareils
|
||
======================================================== */
|
||
async function loadDeviceTypes() {
|
||
try {
|
||
const res = await apiFetch('/api/device-types', { cache: 'no-store' });
|
||
const data = await res.json();
|
||
if (res.ok && data && Array.isArray(data.device_types)) {
|
||
DEVICE_TYPE_LIST = data.device_types.map(t => ({
|
||
id: t.id,
|
||
label: t.label,
|
||
icon: t.icon === 'tablet_svg' ? ICON_TABLET : t.icon,
|
||
raw_icon: t.icon,
|
||
desc: t.desc || '',
|
||
sort_order: t.sort_order || 0
|
||
}));
|
||
renderDeviceTypesTable();
|
||
}
|
||
} catch (e) {
|
||
console.warn('Erreur loadDeviceTypes:', e);
|
||
}
|
||
}
|
||
|
||
function renderDeviceTypesTable() {
|
||
const tbody = $('deviceTypesTableBody');
|
||
if (!tbody) return;
|
||
if (!DEVICE_TYPE_LIST || !DEVICE_TYPE_LIST.length) {
|
||
tbody.innerHTML = '<tr><td colspan="5" class="empty">' + t('no_categories_defined', 'Aucune catégorie définie') + '</td></tr>';
|
||
return;
|
||
}
|
||
tbody.innerHTML = DEVICE_TYPE_LIST.map(tItem => {
|
||
const isTabletSvg = tItem.raw_icon === 'tablet_svg' || tItem.icon === 'tablet_svg';
|
||
const iconHtml = isTabletSvg ? ICON_TABLET : (tItem.icon && tItem.icon.startsWith('<svg') ? tItem.icon : escapeHtml(tItem.icon || '💻'));
|
||
const displayLabel = getDeviceTypeLabel(tItem.id, false) || tItem.label;
|
||
let displayDesc = tItem.desc || '—';
|
||
const isEn = typeof currentLanguage === 'string' && currentLanguage.startsWith('en');
|
||
if (isEn) {
|
||
if (tItem.id === 'desktop' && tItem.desc === 'PC Bureau, Mac Pro, Tour...') displayDesc = 'Desktop PC, Mac Pro, Tower...';
|
||
else if (tItem.id === 'iot' && tItem.desc === 'IoT, Caméra, Domotique, RPi...') displayDesc = 'IoT, Camera, Smart Home, RPi...';
|
||
else if (tItem.id === 'generic' && tItem.desc === 'Appareil générique / inconnu') displayDesc = 'Generic / unknown device';
|
||
}
|
||
return `
|
||
<tr>
|
||
<td style="text-align:center;font-size:22px;vertical-align:middle">${iconHtml}</td>
|
||
<td>
|
||
<strong style="font-size:14px;color:var(--text)">${escapeHtml(displayLabel)}</strong>
|
||
</td>
|
||
<td>
|
||
<code style="font-size:12px;background:var(--panel2);padding:2px 7px;border-radius:4px;border:1px solid var(--line);color:var(--blue)">${escapeHtml(tItem.id)}</code>
|
||
</td>
|
||
<td>
|
||
<span class="muted" style="font-size:12px">${escapeHtml(displayDesc)}</span>
|
||
</td>
|
||
<td style="text-align:right">
|
||
<div style="display:inline-flex;gap:6px;justify-content:flex-end">
|
||
<button class="secondary" type="button" style="padding:4px 9px;font-size:12px;display:inline-flex;align-items:center;gap:4px" onclick="openDeviceTypeEditorModal('${escapeHtml(tItem.id)}')">✏️ ${t('btn_edit', 'Modifier')}</button>
|
||
<button class="secondary" type="button" style="padding:4px 9px;font-size:12px;color:var(--red);display:inline-flex;align-items:center;gap:4px" onclick="deleteDeviceTypeCategory('${escapeHtml(tItem.id)}', '${escapeHtml(displayLabel)}')">🗑️ ${t('btn_delete', 'Supprimer')}</button>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
`;
|
||
}).join('');
|
||
}
|
||
|
||
function sanitizeAndFormatSvg(svgString) {
|
||
if (!svgString) return '💻';
|
||
let svg = String(svgString).trim();
|
||
// Nettoyage sécurité de base
|
||
svg = svg.replace(new RegExp('<scr' + 'ipt[\\s\\S]*?<\\/scr' + 'ipt>', 'gi'), '')
|
||
.replace(/\son\w+="[^"]*"/gi, '')
|
||
.replace(/\son\w+='[^']*'/gi, '');
|
||
if (!svg.toLowerCase().includes('<svg')) return svg;
|
||
// Déterminer ou préserver la viewBox
|
||
if (!/viewBox=/i.test(svg)) {
|
||
const wMatch = svg.match(/width=["']?(\d+(\.\d+)?)["']?/i);
|
||
const hMatch = svg.match(/height=["']?(\d+(\.\d+)?)["']?/i);
|
||
if (wMatch && hMatch) {
|
||
svg = svg.replace(/<svg\b/i, `<svg viewBox="0 0 ${wMatch[1]} ${hMatch[1]}"`);
|
||
} else {
|
||
svg = svg.replace(/<svg\b/i, `<svg viewBox="0 0 24 24"`);
|
||
}
|
||
}
|
||
// Normalisation des dimensions et style d'alignement pour l'interface
|
||
svg = svg.replace(/\bwidth=["'][^"']*["']/i, 'width="1.15em"')
|
||
.replace(/\bheight=["'][^"']*["']/i, 'height="1.15em"');
|
||
if (!/style=/i.test(svg)) {
|
||
svg = svg.replace(/<svg\b/i, '<svg style="display:inline-block;vertical-align:-0.18em;flex-shrink:0"');
|
||
} else {
|
||
svg = svg.replace(/style=["']([^"']*)["']/i, 'style="display:inline-block;vertical-align:-0.18em;flex-shrink:0;$1"');
|
||
}
|
||
return svg;
|
||
}
|
||
|
||
function updateDeviceTypeIconPreview() {
|
||
const preview = $('deviceTypeIconPreview');
|
||
const input = $('deviceTypeEditorIcon');
|
||
if (!preview || !input) return;
|
||
const val = input.value.trim() || '📱';
|
||
if (val === 'tablet_svg') {
|
||
preview.innerHTML = ICON_TABLET;
|
||
} else if (val === 'server_svg') {
|
||
preview.innerHTML = ICON_SERVER;
|
||
} else if (val === 'router_svg') {
|
||
preview.innerHTML = ICON_ROUTER;
|
||
} else if (val === 'laptop_svg') {
|
||
preview.innerHTML = ICON_LAPTOP;
|
||
} else if (val.startsWith('<svg') || val.includes('<svg')) {
|
||
preview.innerHTML = sanitizeAndFormatSvg(val);
|
||
} else {
|
||
preview.textContent = val;
|
||
}
|
||
}
|
||
|
||
/* ========================================================
|
||
Moteur de recherche d'icônes & emojis (Iconify, Emojis, Sites)
|
||
======================================================== */
|
||
const BUILTIN_EMOJI_CATALOG = [
|
||
{ icon: '📱', name: 'Smartphone', tags: 'smartphone phone telephone mobile iphone android galaxy pixel' },
|
||
{ icon: 'tablet_svg', name: 'Tablette (SVG)', tags: 'tablette tablet ipad galaxy-tab kindle liseuse' },
|
||
{ icon: 'laptop_svg', name: 'PC Portable (SVG)', tags: 'ordinateur portable laptop macbook thinkpad pc notebook' },
|
||
{ icon: 'server_svg', name: 'Serveur (SVG)', tags: 'serveur server nas synology rack baie datacenter cloud machine' },
|
||
{ icon: 'router_svg', name: 'Routeur / AP (SVG)', tags: 'routeur router gateway passerelle wifi borne ap network' },
|
||
{ icon: '💻', name: 'PC Portable', tags: 'ordinateur portable laptop macbook thinkpad pc notebook' },
|
||
{ icon: '🖥️', name: 'Ordinateur fixe', tags: 'ordinateur fixe desktop tour imac workstation ecran moniteur pc' },
|
||
{ icon: '📺', name: 'Smart TV / Box', tags: 'tv television tele box appletv chromecast smarttv ecran' },
|
||
{ icon: '🎮', name: 'Console de jeux', tags: 'console jeux gaming manette playstation xbox switch gamepad joystick' },
|
||
{ icon: '🕹️', name: 'Borne d’arcade', tags: 'arcade joystick gaming retro borne manette' },
|
||
{ icon: '⌚', name: 'Montre connectée', tags: 'montre smartwatch watch apple-watch garmin fitbit' },
|
||
{ icon: '🖨️', name: 'Imprimante', tags: 'imprimante printer scanner photocopieuse scan' },
|
||
{ icon: '📷', name: 'Caméra / Photo', tags: 'camera photo surveillance webcam ipcam cctv optique' },
|
||
{ icon: '📹', name: 'Caméra vidéo', tags: 'camera video cctv surveillance enregistreur nvr' },
|
||
{ icon: '🔊', name: 'Enceinte connectée', tags: 'enceinte speaker audio son sonos alexa homepod' },
|
||
{ icon: '🎧', name: 'Casque audio', tags: 'casque audio headphones ecouteurs airpods sound' },
|
||
{ icon: '🎙️', name: 'Microphone', tags: 'micro microphone podcast audio vocal voice' },
|
||
{ icon: '🤖', name: 'Robot / Domotique', tags: 'robot aspirateur vacuum cleaner bot domotique automate' },
|
||
{ icon: '🚗', name: 'Véhicule connecté', tags: 'voiture vehicule car tesla auto electric-car' },
|
||
{ icon: '🚲', name: 'Vélo électrique', tags: 'velo bike ebike cycle vtt vae' },
|
||
{ icon: '🛴', name: 'Trottinette électrique', tags: 'trottinette scooter mobility' },
|
||
{ icon: '🛸', name: 'Drone', tags: 'drone uav quadcopter aeronef camera' },
|
||
{ icon: '📟', name: 'Objet connecté (IoT)', tags: 'iot capteur sensor pager boitier rpi raspberry esp32 arduino' },
|
||
{ icon: '🌐', name: 'Passerelle / Routeur', tags: 'routeur router gateway reseau network internet wan' },
|
||
{ icon: '📡', name: 'Antenne / Wi-Fi', tags: 'antenne wifi borne ap satellite parabole repeteur wireless' },
|
||
{ icon: '🎛️', name: 'Switch réseau', tags: 'switch commutateur controleur rj45 lan ethernet' },
|
||
{ icon: '🗄️', name: 'Serveur / NAS', tags: 'serveur server nas synology rack baie stockage cloud' },
|
||
{ icon: '💾', name: 'Disque / Sauvegarde', tags: 'disque stockage hdd ssd save backup drive' },
|
||
{ icon: '🔌', name: 'Prise connectée', tags: 'prise plug socket electricite power connectee' },
|
||
{ icon: '💡', name: 'Éclairage connecté', tags: 'lumiere ampoule bulb light hue eclairage lampe' },
|
||
{ icon: '🌡️', name: 'Thermostat / Sonde', tags: 'thermostat temperature sonde capteur meteo climat heat' },
|
||
{ icon: '🔔', name: 'Sonnette connectée', tags: 'sonnette doorbell ring interphone carillon' },
|
||
{ icon: '🚪', name: 'Serrure connectée', tags: 'serrure porte door lock smartlock ouverture' },
|
||
{ icon: '🔒', name: 'Sécurité / Firewall', tags: 'securite lock cadenas firewall protection passkey' },
|
||
{ icon: '🛡️', name: 'Bouclier / Pare-feu', tags: 'bouclier shield antivirus protection securite vpn' },
|
||
{ icon: '🚨', name: 'Alarme / Sirène', tags: 'alarme sirene alarm intrusion alerte' },
|
||
{ icon: '🔋', name: 'Batterie / Onduleur', tags: 'batterie battery ups onduleur secours alim power' },
|
||
{ icon: '⚡', name: 'Borne de recharge', tags: 'borne electricite charge chargeur power energy' },
|
||
{ icon: '⌨️', name: 'Clavier', tags: 'clavier keyboard peripherique touches' },
|
||
{ icon: '🖱️', name: 'Souris', tags: 'souris mouse trackpad pointeur' },
|
||
{ icon: '🥽', name: 'Casque VR', tags: 'vr virtuel quest meta vision casque lunettes' },
|
||
{ icon: '🧹', name: 'Aspirateur robot', tags: 'aspirateur cleaner robot roomba roborock nettoyeur' },
|
||
{ icon: '🧺', name: 'Lave-linge connecté', tags: 'machine lave-linge electromenager washing' },
|
||
{ icon: '❄️', name: 'Climatiseur / PAC', tags: 'clim climatisation pompe froid ac heat' },
|
||
{ icon: '☀️', name: 'Panneau solaire', tags: 'solaire panneau solar onduleur energie sun' },
|
||
{ icon: '🏠', name: 'Maison connectée', tags: 'maison home domotique hub bridge' },
|
||
{ icon: '🔧', name: 'Maintenance', tags: 'outils maintenance service config reglage tool' },
|
||
{ icon: '🔑', name: 'Clé de sécurité', tags: 'cle passkey security yubikey fido usb token' },
|
||
{ icon: '📦', name: 'Module / Passerelle', tags: 'boitier module passerelle package hub' }
|
||
];
|
||
|
||
const ICONS_FR_TO_EN = {
|
||
'ordinateur': 'laptop',
|
||
'portable': 'laptop',
|
||
'fixe': 'desktop',
|
||
'tablette': 'tablet',
|
||
'telephone': 'smartphone',
|
||
'smartphone': 'smartphone',
|
||
'mobile': 'smartphone',
|
||
'liseuse': 'tablet',
|
||
'montre': 'smartwatch',
|
||
'console': 'gamepad',
|
||
'jeu': 'gamepad',
|
||
'jeux': 'gamepad',
|
||
'manette': 'gamepad',
|
||
'television': 'television',
|
||
'tele': 'tv',
|
||
'ecran': 'display',
|
||
'camera': 'camera',
|
||
'securite': 'shield',
|
||
'imprimante': 'printer',
|
||
'scanner': 'scanner',
|
||
'routeur': 'router',
|
||
'reseau': 'network',
|
||
'serveur': 'server',
|
||
'disque': 'harddrive',
|
||
'stockage': 'storage',
|
||
'enceinte': 'speaker',
|
||
'son': 'speaker',
|
||
'casque': 'headphones',
|
||
'ecouteurs': 'earphones',
|
||
'micro': 'microphone',
|
||
'robot': 'robot',
|
||
'aspirateur': 'vacuum',
|
||
'ampoule': 'bulb',
|
||
'lumiere': 'light',
|
||
'prise': 'plug',
|
||
'electrique': 'power',
|
||
'batterie': 'battery',
|
||
'onduleur': 'ups',
|
||
'panneau': 'solar',
|
||
'solaire': 'solar',
|
||
'voiture': 'car',
|
||
'vehicule': 'vehicle',
|
||
'velo': 'bicycle',
|
||
'trottinette': 'scooter',
|
||
'drone': 'drone',
|
||
'cle': 'key',
|
||
'thermostat': 'thermostat',
|
||
'temperature': 'thermometer',
|
||
'sonnette': 'doorbell',
|
||
'serrure': 'lock',
|
||
'porte': 'door',
|
||
'alarme': 'alarm',
|
||
'capteur': 'sensor',
|
||
'wifi': 'wifi',
|
||
'bluetooth': 'bluetooth'
|
||
};
|
||
|
||
let currentIconSearchFilter = 'all';
|
||
let iconSearchDebounceTimer = null;
|
||
let cachedIconifyResults = {};
|
||
|
||
function setIconSearchFilter(mode) {
|
||
currentIconSearchFilter = mode;
|
||
const btnAll = $('filterIconAll'), btnEmoji = $('filterIconEmoji'), btnSvg = $('filterIconSvg');
|
||
const activeStyle = 'background:var(--blue);color:var(--blue-text,#071326);font-weight:700';
|
||
const inactiveStyle = '';
|
||
if (btnAll) btnAll.style.cssText = mode === 'all' ? activeStyle : inactiveStyle;
|
||
if (btnEmoji) btnEmoji.style.cssText = mode === 'emoji' ? activeStyle : inactiveStyle;
|
||
if (btnSvg) btnSvg.style.cssText = mode === 'svg' ? activeStyle : inactiveStyle;
|
||
doIconSearch();
|
||
}
|
||
|
||
function onIconSearchInput(val) {
|
||
const cleanQ = (val || '').trim();
|
||
const qEnc = encodeURIComponent(cleanQ || 'device');
|
||
if ($('linkSearchIconify')) $('linkSearchIconify').href = 'https://icon-sets.iconify.design/?query=' + qEnc;
|
||
if ($('linkSearchSvgRepo')) $('linkSearchSvgRepo').href = 'https://www.svgrepo.com/vectors/' + qEnc + '/';
|
||
if ($('linkSearchTabler')) $('linkSearchTabler').href = 'https://tabler.io/icons?q=' + qEnc;
|
||
if ($('linkSearchEmojipedia')) $('linkSearchEmojipedia').href = 'https://emojipedia.org/search?q=' + qEnc;
|
||
|
||
if (iconSearchDebounceTimer) clearTimeout(iconSearchDebounceTimer);
|
||
iconSearchDebounceTimer = setTimeout(() => {
|
||
doIconSearch();
|
||
}, 280);
|
||
}
|
||
|
||
async function doIconSearch() {
|
||
const query = ($('iconSearchQuery') ? $('iconSearchQuery').value : '').trim();
|
||
const grid = $('iconSearchResultsGrid');
|
||
const statusEl = $('iconSearchStatus');
|
||
if (!grid) return;
|
||
|
||
const normQuery = query.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
|
||
|
||
// 1. Filtrer les emojis et SVG internes
|
||
let matchedEmojis = [];
|
||
if (currentIconSearchFilter === 'all' || currentIconSearchFilter === 'emoji') {
|
||
if (!normQuery) {
|
||
matchedEmojis = BUILTIN_EMOJI_CATALOG.slice(0, 24);
|
||
} else {
|
||
matchedEmojis = BUILTIN_EMOJI_CATALOG.filter(item => {
|
||
return item.name.toLowerCase().includes(normQuery) ||
|
||
item.tags.toLowerCase().includes(normQuery);
|
||
});
|
||
}
|
||
}
|
||
|
||
// Affichage immédiat d'un indicateur de chargement
|
||
if (currentIconSearchFilter === 'all' || currentIconSearchFilter === 'svg') {
|
||
if (statusEl) statusEl.textContent = '⏳ Recherche des icônes en cours…';
|
||
if (matchedEmojis.length && currentIconSearchFilter === 'all') {
|
||
// On affiche immédiatement les émojis/SVG locaux pendant que la recherche en ligne s'exécute
|
||
renderIconSearchResults(matchedEmojis, [], true);
|
||
} else {
|
||
grid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:24px 12px;color:var(--blue);font-size:13px"><div class="spinner" style="width:22px;height:22px;margin:0 auto 10px;border-width:2.5px;border-top-color:var(--blue)"></div>Chargement des icônes en cours…</div>';
|
||
}
|
||
}
|
||
|
||
// 2. Recherche SVG sur Iconify
|
||
let matchedSvgIcons = [];
|
||
if (currentIconSearchFilter === 'all' || currentIconSearchFilter === 'svg') {
|
||
let iconifyQuery = normQuery || 'device';
|
||
if (ICONS_FR_TO_EN[normQuery]) {
|
||
iconifyQuery = ICONS_FR_TO_EN[normQuery];
|
||
}
|
||
if (cachedIconifyResults[iconifyQuery]) {
|
||
matchedSvgIcons = cachedIconifyResults[iconifyQuery];
|
||
} else {
|
||
try {
|
||
let res = null;
|
||
try {
|
||
res = await fetch(`https://api.iconify.design/search?query=${encodeURIComponent(iconifyQuery)}&limit=36`, { signal: AbortSignal.timeout(3000) });
|
||
} catch (_) {
|
||
res = await apiFetch(`/api/icons/search?q=${encodeURIComponent(iconifyQuery)}&limit=36`);
|
||
}
|
||
if (res && res.ok) {
|
||
const data = await res.json();
|
||
if (data && Array.isArray(data.icons)) {
|
||
matchedSvgIcons = data.icons;
|
||
cachedIconifyResults[iconifyQuery] = data.icons;
|
||
}
|
||
}
|
||
} catch (e) {
|
||
console.warn('Recherche Iconify indisponible:', e);
|
||
}
|
||
}
|
||
}
|
||
|
||
if (statusEl) {
|
||
const totalFound = matchedEmojis.length + matchedSvgIcons.length;
|
||
statusEl.textContent = totalFound ? `${totalFound} icône(s) trouvée(s)` : 'Aucune icône trouvée';
|
||
}
|
||
|
||
renderIconSearchResults(matchedEmojis, matchedSvgIcons, false);
|
||
}
|
||
|
||
function getIconifySvgUrl(iconName, color) {
|
||
let clean = String(iconName || '').trim();
|
||
let path = clean;
|
||
if (clean.includes(':')) {
|
||
const parts = clean.split(':');
|
||
path = encodeURIComponent(parts[0]) + '/' + encodeURIComponent(parts[1]);
|
||
} else {
|
||
path = encodeURIComponent(clean);
|
||
}
|
||
let url = 'https://api.iconify.design/' + path + '.svg';
|
||
// Ne jamais forcer de couleur sur les sets d'émojis multi-couleurs
|
||
const isEmojiSet = /^(noto|twemoji|openmoji|emojione|joypixels|fluent-emoji|fxemoji|streamline-emojis|blobmoji)/i.test(clean);
|
||
if (color && !isEmojiSet && color !== 'currentColor') url += '?color=' + color;
|
||
return url;
|
||
}
|
||
|
||
function handleIconImgError(img, iconName, color) {
|
||
if (!img) return;
|
||
const isEmojiSet = /^(noto|twemoji|openmoji|emojione|joypixels|fluent-emoji|fxemoji|streamline-emojis|blobmoji)/i.test(iconName);
|
||
const cParam = (color && !isEmojiSet && color !== 'currentColor') ? '&color=' + encodeURIComponent(color) : '';
|
||
if (!img.dataset.tried) {
|
||
img.dataset.tried = '1';
|
||
img.src = '/api/icons/svg?name=' + encodeURIComponent(iconName) + cParam;
|
||
} else if (img.dataset.tried === '1') {
|
||
img.dataset.tried = '2';
|
||
const clean = String(iconName || '').trim();
|
||
const path = clean.includes(':') ? clean.replace(':', '/') : clean;
|
||
img.src = 'https://api.simplesvg.com/' + path + '.svg' + (cParam ? '?' + cParam.substring(1) : '');
|
||
} else {
|
||
img.style.display = 'none';
|
||
const ph = img.previousElementSibling;
|
||
if (ph) {
|
||
ph.textContent = isEmojiSet ? '😀' : '📄';
|
||
ph.style.opacity = '0.7';
|
||
}
|
||
}
|
||
}
|
||
|
||
function renderIconSearchResults(emojis, svgIcons, isSearching = false) {
|
||
const grid = $('iconSearchResultsGrid');
|
||
if (!grid) return;
|
||
if (!emojis.length && !svgIcons.length) {
|
||
if (isSearching) {
|
||
grid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:24px 12px;color:var(--blue);font-size:13px"><div class="spinner" style="width:22px;height:22px;margin:0 auto 10px;border-width:2.5px;border-top-color:var(--blue)"></div>Chargement des icônes en cours…</div>';
|
||
} else {
|
||
grid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:12px;color:var(--muted);font-size:12px">Aucun résultat trouvé pour ce mot-clé. Utilisez les liens ci-dessous pour trouver des SVG ou emojis et collez-les ici.</div>';
|
||
}
|
||
return;
|
||
}
|
||
|
||
const isLight = document.documentElement.getAttribute('data-theme') === 'light' || document.documentElement.getAttribute('data-theme') === 'winxp' || (document.documentElement.getAttribute('data-theme') === 'macos' && (typeof themeMedia !== 'undefined' ? themeMedia.matches : true));
|
||
const svgColor = isLight ? '%230284c7' : '%2338bdf8';
|
||
const rawColor = isLight ? '#0284c7' : '#38bdf8';
|
||
|
||
let html = '';
|
||
// Affichage des Emojis et SVG locaux
|
||
emojis.forEach(e => {
|
||
let displayHtml = e.icon;
|
||
if (e.icon === 'tablet_svg') displayHtml = ICON_TABLET;
|
||
else if (e.icon === 'server_svg') displayHtml = ICON_SERVER;
|
||
else if (e.icon === 'router_svg') displayHtml = ICON_ROUTER;
|
||
else if (e.icon === 'laptop_svg') displayHtml = ICON_LAPTOP;
|
||
html += `
|
||
<div class="icon-result-card" onclick="setQuickIcon('${escapeHtml(e.icon)}')" title="${escapeHtml(e.name)}">
|
||
<span style="font-size:20px;line-height:1;display:flex;align-items:center;justify-content:center">${displayHtml}</span>
|
||
<span class="icon-result-tag">${escapeHtml(e.name)}</span>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
// Si on est en attente du résultat en ligne, on montre un mini badge de chargement
|
||
if (isSearching && currentIconSearchFilter !== 'emoji') {
|
||
html += `
|
||
<div class="icon-result-card" style="opacity:0.6;pointer-events:none">
|
||
<div class="spinner" style="width:16px;height:16px;border-width:2px;border-top-color:var(--blue)"></div>
|
||
<span class="icon-result-tag">SVG…</span>
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
// Affichage des SVG Iconify
|
||
svgIcons.forEach(iconName => {
|
||
const shortName = iconName.includes(':') ? iconName.split(':')[1] : iconName;
|
||
const directUrl = getIconifySvgUrl(iconName, svgColor);
|
||
html += `
|
||
<div class="icon-result-card" onclick="selectIconifySvg('${escapeHtml(iconName)}', this)" title="${escapeHtml(iconName)} (SVG Iconify)">
|
||
<div style="width:24px;height:24px;display:flex;align-items:center;justify-content:center;position:relative">
|
||
<span class="icon-card-ph" style="position:absolute;font-size:13px;opacity:0.35;pointer-events:none">⚡</span>
|
||
<img src="${directUrl}" width="22" height="22" loading="lazy" style="vertical-align:middle;display:block;position:relative;z-index:1;min-height:22px" onload="const ph=this.previousElementSibling;if(ph)ph.style.display='none';" onerror="handleIconImgError(this, '${escapeHtml(iconName)}', '${rawColor}')">
|
||
</div>
|
||
<span class="icon-result-tag">${escapeHtml(shortName)}</span>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
grid.innerHTML = html;
|
||
}
|
||
|
||
async function selectIconifySvg(iconName, cardEl) {
|
||
const statusEl = $('iconSearchStatus');
|
||
const input = $('deviceTypeEditorIcon');
|
||
const cleanName = String(iconName || '').trim();
|
||
const isEmojiSet = /^(noto|twemoji|openmoji|emojione|joypixels|fluent-emoji|fxemoji|streamline-emojis|blobmoji)/i.test(cleanName);
|
||
|
||
if (statusEl) statusEl.textContent = `Téléchargement du SVG (${cleanName})…`;
|
||
try {
|
||
let svgText = '';
|
||
|
||
// 1. Essayer le proxy local d'abord (en format JSON)
|
||
try {
|
||
const res = await apiFetch(`/api/icons/svg?name=${encodeURIComponent(cleanName)}&format=json`);
|
||
if (res && res.ok) {
|
||
const d = await res.json();
|
||
if (d && d.svg && d.svg.includes('<svg')) {
|
||
svgText = d.svg;
|
||
}
|
||
}
|
||
} catch (_) { }
|
||
|
||
// 2. Si le proxy JSON n'a pas répondu, essayer le proxy en direct (raw SVG)
|
||
if (!svgText) {
|
||
try {
|
||
const res = await apiFetch(`/api/icons/svg?name=${encodeURIComponent(cleanName)}`);
|
||
if (res && res.ok) {
|
||
const txt = await res.text();
|
||
if (txt && txt.includes('<svg')) {
|
||
svgText = txt;
|
||
}
|
||
}
|
||
} catch (_) { }
|
||
}
|
||
|
||
// 3. Essayer en direct les miroirs CDNs Iconify (sans forcer de couleur pour les émojis)
|
||
if (!svgText) {
|
||
const path = cleanName.includes(':') ? cleanName.replace(':', '/') : cleanName;
|
||
const hosts = [
|
||
'https://api.iconify.design',
|
||
'https://api.simplesvg.com',
|
||
'https://api.unisvg.com'
|
||
];
|
||
for (const host of hosts) {
|
||
if (svgText) break;
|
||
try {
|
||
const url = `${host}/${path}.svg`;
|
||
const res = await fetch(url, { signal: AbortSignal.timeout(6000) });
|
||
if (res && res.ok) {
|
||
const txt = await res.text();
|
||
if (txt && txt.includes('<svg')) {
|
||
svgText = txt;
|
||
break;
|
||
}
|
||
}
|
||
} catch (_) { }
|
||
}
|
||
}
|
||
|
||
// 4. Essayer l'API JSON {prefix}.json?icons={name}
|
||
if (!svgText && cleanName.includes(':')) {
|
||
const parts = cleanName.split(':');
|
||
const p = parts[0], n = parts[1];
|
||
const hosts = [
|
||
'https://api.iconify.design',
|
||
'https://api.simplesvg.com'
|
||
];
|
||
for (const host of hosts) {
|
||
if (svgText) break;
|
||
try {
|
||
const url = `${host}/${encodeURIComponent(p)}.json?icons=${encodeURIComponent(n)}`;
|
||
const res = await fetch(url, { signal: AbortSignal.timeout(6000) });
|
||
if (res && res.ok) {
|
||
const d = await res.json();
|
||
if (d && d.icons && d.icons[n] && d.icons[n].body) {
|
||
const w = d.icons[n].width || d.width || 24;
|
||
const h = d.icons[n].height || d.height || 24;
|
||
svgText = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="1.15em" height="1.15em">${d.icons[n].body}</svg>`;
|
||
break;
|
||
}
|
||
}
|
||
} catch (_) { }
|
||
}
|
||
}
|
||
|
||
// 5. Récupérer depuis l'image <img> déjà rendue dans la carte
|
||
if (!svgText && cardEl) {
|
||
const img = cardEl.querySelector('img');
|
||
if (img && img.complete && img.naturalWidth > 0) {
|
||
try {
|
||
const canvas = document.createElement('canvas');
|
||
canvas.width = Math.max(img.naturalWidth, 24);
|
||
canvas.height = Math.max(img.naturalHeight, 24);
|
||
const ctx = canvas.getContext('2d');
|
||
ctx.drawImage(img, 0, 0);
|
||
const dataUri = canvas.toDataURL('image/png');
|
||
svgText = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${canvas.width} ${canvas.height}" width="1.15em" height="1.15em"><image href="${dataUri}" width="${canvas.width}" height="${canvas.height}"/></svg>`;
|
||
} catch (_) { }
|
||
}
|
||
}
|
||
|
||
// 6. Si aucun réseau disponible, générer un SVG vectoriel propre
|
||
if (!svgText) {
|
||
const sName = (cleanName.includes(':') ? cleanName.split(':')[1] : cleanName);
|
||
const shortLabel = (sName.split('-')[0] || sName).substring(0, 5).toUpperCase();
|
||
const symbol = isEmojiSet ? '😀' : shortLabel;
|
||
svgText = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1.15em" height="1.15em" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="4"/><text x="12" y="16" font-size="10" text-anchor="middle" fill="currentColor" stroke="none" font-weight="bold">${escapeHtml(symbol)}</text></svg>`;
|
||
}
|
||
|
||
const cleanSvg = sanitizeAndFormatSvg(svgText);
|
||
if (input) {
|
||
input.value = cleanSvg;
|
||
updateDeviceTypeIconPreview();
|
||
}
|
||
if (statusEl) {
|
||
statusEl.style.color = 'var(--green)';
|
||
statusEl.textContent = `✓ SVG ${cleanName} appliqué !`;
|
||
setTimeout(() => { if (statusEl) statusEl.style.color = 'var(--muted)'; }, 3000);
|
||
}
|
||
} catch (e) {
|
||
if (statusEl) {
|
||
statusEl.style.color = 'var(--red)';
|
||
statusEl.textContent = 'Erreur chargement SVG: ' + e.message;
|
||
}
|
||
}
|
||
}
|
||
|
||
async function pasteSvgFromClipboard() {
|
||
const statusEl = $('iconSearchStatus');
|
||
const input = $('deviceTypeEditorIcon');
|
||
try {
|
||
let clipText = '';
|
||
if (navigator.clipboard && navigator.clipboard.readText) {
|
||
clipText = await navigator.clipboard.readText();
|
||
}
|
||
if (!clipText) {
|
||
clipText = prompt('Collez ici votre code SVG ou votre emoji :');
|
||
}
|
||
if (clipText && clipText.trim()) {
|
||
const clean = sanitizeAndFormatSvg(clipText.trim());
|
||
if (input) {
|
||
input.value = clean;
|
||
updateDeviceTypeIconPreview();
|
||
}
|
||
if (statusEl) {
|
||
statusEl.style.color = 'var(--green)';
|
||
statusEl.textContent = '✓ SVG ou emoji collé avec succès !';
|
||
setTimeout(() => { if (statusEl) statusEl.style.color = 'var(--muted)'; }, 3000);
|
||
}
|
||
}
|
||
} catch (e) {
|
||
const manual = prompt('Collez votre code SVG ou emoji ici :');
|
||
if (manual && manual.trim() && input) {
|
||
input.value = sanitizeAndFormatSvg(manual.trim());
|
||
updateDeviceTypeIconPreview();
|
||
}
|
||
}
|
||
}
|
||
|
||
function setQuickIcon(icon) {
|
||
const input = $('deviceTypeEditorIcon');
|
||
if (input) {
|
||
if (icon === 'server_svg') input.value = ICON_SERVER;
|
||
else if (icon === 'router_svg') input.value = ICON_ROUTER;
|
||
else if (icon === 'laptop_svg') input.value = ICON_LAPTOP;
|
||
else input.value = icon;
|
||
updateDeviceTypeIconPreview();
|
||
}
|
||
}
|
||
|
||
function autoSuggestTypeId() {
|
||
const origId = $('deviceTypeEditorOriginalId').value;
|
||
if (origId) return;
|
||
const label = $('deviceTypeEditorLabel').value.trim();
|
||
const idInput = $('deviceTypeEditorId');
|
||
if (idInput && (!idInput.dataset.manual || !idInput.value)) {
|
||
idInput.value = label.toLowerCase()
|
||
.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
|
||
.replace(/[^a-z0-9]+/g, '_')
|
||
.replace(/^_+|_+$/g, '')
|
||
.slice(0, 24);
|
||
}
|
||
}
|
||
|
||
function openDeviceTypeEditorModal(typeId) {
|
||
const titleEl = $('deviceTypeEditorTitle');
|
||
const origIdInput = $('deviceTypeEditorOriginalId');
|
||
const labelInput = $('deviceTypeEditorLabel');
|
||
const idInput = $('deviceTypeEditorId');
|
||
const iconInput = $('deviceTypeEditorIcon');
|
||
const descInput = $('deviceTypeEditorDesc');
|
||
const msgEl = $('deviceTypeEditorMsg');
|
||
if (msgEl) msgEl.textContent = '';
|
||
|
||
if (typeId) {
|
||
const item = (DEVICE_TYPE_LIST || []).find(t => t.id === typeId);
|
||
const editLabel = (item && item.label) || typeId;
|
||
const displayEditLabel = getDeviceTypeLabel(typeId, false) || editLabel;
|
||
if (titleEl) titleEl.innerHTML = `✏️ ${t('modal_cat_edit_title_with_name', "Modifier la catégorie « {label} »").replace('{label}', escapeHtml(displayEditLabel))}`;
|
||
if (origIdInput) origIdInput.value = typeId;
|
||
if (labelInput) labelInput.value = (item && item.label) || '';
|
||
if (idInput) {
|
||
idInput.value = typeId;
|
||
idInput.dataset.manual = '1';
|
||
}
|
||
if (iconInput) iconInput.value = (item && (item.raw_icon || item.icon)) || '📱';
|
||
if (descInput) descInput.value = (item && item.desc) || '';
|
||
} else {
|
||
if (titleEl) titleEl.innerHTML = escapeHtml(t('modal_cat_add_title', '➕ Ajouter une catégorie d’appareil'));
|
||
if (origIdInput) origIdInput.value = '';
|
||
if (labelInput) labelInput.value = '';
|
||
if (idInput) {
|
||
idInput.value = '';
|
||
idInput.dataset.manual = '';
|
||
}
|
||
if (iconInput) iconInput.value = '📱';
|
||
if (descInput) descInput.value = '';
|
||
}
|
||
updateDeviceTypeIconPreview();
|
||
if ($('iconSearchQuery')) $('iconSearchQuery').value = '';
|
||
setIconSearchFilter('all');
|
||
const modal = $('modalDeviceTypeEditor');
|
||
if (modal) modal.classList.add('active');
|
||
if (labelInput) setTimeout(() => labelInput.focus(), 80);
|
||
}
|
||
|
||
function closeDeviceTypeEditorModal() {
|
||
const modal = $('modalDeviceTypeEditor');
|
||
if (modal) modal.classList.remove('active');
|
||
}
|
||
|
||
async function saveDeviceTypeCategory() {
|
||
const origId = $('deviceTypeEditorOriginalId').value.trim();
|
||
const label = $('deviceTypeEditorLabel').value.trim();
|
||
const id = $('deviceTypeEditorId').value.trim().toLowerCase();
|
||
const icon = $('deviceTypeEditorIcon').value.trim();
|
||
const desc = $('deviceTypeEditorDesc').value.trim();
|
||
const msgEl = $('deviceTypeEditorMsg');
|
||
const btn = $('btnSaveDeviceTypeEditor');
|
||
|
||
if (!label) {
|
||
if (msgEl) { msgEl.style.color = 'var(--red)'; msgEl.textContent = t('modal_cat_err_name', 'Veuillez indiquer un nom pour la catégorie.'); }
|
||
$('deviceTypeEditorLabel').focus();
|
||
return;
|
||
}
|
||
if (!id) {
|
||
if (msgEl) { msgEl.style.color = 'var(--red)'; msgEl.textContent = t('modal_cat_err_id', 'Veuillez indiquer un identifiant technique unique.'); }
|
||
$('deviceTypeEditorId').focus();
|
||
return;
|
||
}
|
||
if (!/^[a-z0-9_-]+$/.test(id)) {
|
||
if (msgEl) { msgEl.style.color = 'var(--red)'; msgEl.textContent = t('modal_cat_err_id_chars', 'L’identifiant ne peut contenir que des lettres minuscules, chiffres, tirets ou soulignés.'); }
|
||
$('deviceTypeEditorId').focus();
|
||
return;
|
||
}
|
||
|
||
try {
|
||
btn.disabled = true;
|
||
if (msgEl) { msgEl.style.color = 'var(--muted)'; msgEl.textContent = t('saving_in_progress', 'Enregistrement en cours…'); }
|
||
const res = await apiFetch('/api/device-types/save', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
original_id: origId,
|
||
id: id,
|
||
label: label,
|
||
icon: icon || '📱',
|
||
desc: desc
|
||
})
|
||
});
|
||
const data = await res.json();
|
||
if (!res.ok) throw new Error(data.error || 'Erreur lors de l’enregistrement');
|
||
closeDeviceTypeEditorModal();
|
||
const tableMsg = $('deviceTypesMsg');
|
||
if (tableMsg) {
|
||
tableMsg.style.color = 'var(--green)';
|
||
tableMsg.textContent = tMsg(data.message || 'Catégorie enregistrée avec succès !');
|
||
}
|
||
await loadDeviceTypes();
|
||
if (typeof loadDevices === 'function') loadDevices();
|
||
if (typeof updateTopology === 'function') updateTopology();
|
||
} catch (e) {
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--red)';
|
||
msgEl.textContent = tErr(e.message);
|
||
}
|
||
} finally {
|
||
btn.disabled = false;
|
||
}
|
||
}
|
||
|
||
async function deleteDeviceTypeCategory(id, label) {
|
||
if (DEVICE_TYPE_LIST.length <= 1) {
|
||
alert(t('modal_cat_cannot_delete_last', "Impossible de supprimer la dernière catégorie d’appareil."));
|
||
return;
|
||
}
|
||
const confirmMsg = t('modal_cat_confirm_delete', `Êtes-vous sûr de vouloir supprimer la catégorie « {label} » ?\n\nTous les appareils associés à cette catégorie basculeront automatiquement sur la catégorie Standard.`).replace('{label}', label);
|
||
if (!confirm(confirmMsg)) return;
|
||
const msgEl = $('deviceTypesMsg');
|
||
try {
|
||
if (msgEl) { msgEl.style.color = 'var(--muted)'; msgEl.textContent = t('deleting_in_progress', 'Suppression en cours…'); }
|
||
const res = await apiFetch('/api/device-types/delete', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ id: id })
|
||
});
|
||
const data = await res.json();
|
||
if (!res.ok) throw new Error(data.error || 'Erreur lors de la suppression');
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--green)';
|
||
msgEl.textContent = tMsg(data.message || 'Catégorie supprimée avec succès');
|
||
}
|
||
await loadDeviceTypes();
|
||
if (typeof loadDevices === 'function') loadDevices();
|
||
if (typeof updateTopology === 'function') updateTopology();
|
||
} catch (e) {
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--red)';
|
||
msgEl.textContent = tErr(e.message);
|
||
}
|
||
alert(tErr(e.message));
|
||
}
|
||
}
|
||
|
||
async function resetDefaultDeviceTypes() {
|
||
if (!confirm(t('confirm_reset_device_types', "Voulez-vous vraiment réinitialiser toutes les catégories d’appareils à leurs valeurs par défaut ?"))) return;
|
||
const msgEl = $('deviceTypesMsg');
|
||
try {
|
||
if (msgEl) { msgEl.style.color = 'var(--muted)'; msgEl.textContent = t('resetting_in_progress', 'Réinitialisation en cours…'); }
|
||
const res = await apiFetch('/api/device-types/reset', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({})
|
||
});
|
||
const data = await res.json();
|
||
if (!res.ok) throw new Error(data.error || 'Erreur lors de la réinitialisation');
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--green)';
|
||
msgEl.textContent = tMsg(data.message || 'Catégories réinitialisées avec succès');
|
||
}
|
||
await loadDeviceTypes();
|
||
if (typeof loadDevices === 'function') loadDevices();
|
||
if (typeof updateTopology === 'function') updateTopology();
|
||
} catch (e) {
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--red)';
|
||
msgEl.textContent = tErr(e.message);
|
||
}
|
||
alert(tErr(e.message));
|
||
}
|
||
}
|
||
|
||
function formatSpeed(bps) {
|
||
if (bps === null || bps === undefined || bps <= 0) return '0 o/s';
|
||
const isEn = (typeof currentLanguage !== 'undefined' && (currentLanguage === 'en-us' || currentLanguage === 'en-gb'));
|
||
const uBs = isEn ? ' B/s' : ' o/s';
|
||
const uKs = isEn ? ' KB/s' : ' Ko/s';
|
||
const uMs = isEn ? ' MB/s' : ' Mo/s';
|
||
const uGs = isEn ? ' GB/s' : ' Go/s';
|
||
const uTs = isEn ? ' TB/s' : ' To/s';
|
||
if (bps < 1024) return Math.round(bps) + uBs;
|
||
if (bps < 1048576) return (bps / 1024).toFixed(1) + uKs;
|
||
if (bps < 1073741824) return (bps / 1048576).toFixed(1) + uMs;
|
||
if (bps < 1099511627776) return (bps / 1073741824).toFixed(2) + uGs;
|
||
return (bps / 1099511627776).toFixed(2) + uTs;
|
||
}
|
||
function formatBytes(b) {
|
||
const isEn = (typeof currentLanguage !== 'undefined' && (currentLanguage === 'en-us' || currentLanguage === 'en-gb'));
|
||
const uB = isEn ? ' B' : ' o';
|
||
const uK = isEn ? ' KB' : ' Ko';
|
||
const uM = isEn ? ' MB' : ' Mo';
|
||
const uG = isEn ? ' GB' : ' Go';
|
||
const uT = isEn ? ' TB' : ' To';
|
||
if (b === null || b === undefined || b <= 0) return '0' + uB;
|
||
if (b < 1024) return Math.round(b) + uB;
|
||
if (b < 1048576) return (b / 1024).toFixed(1) + uK;
|
||
if (b < 1073741824) return (b / 1048576).toFixed(1) + uM;
|
||
if (b < 1099511627776) return (b / 1073741824).toFixed(2) + uG;
|
||
return (b / 1099511627776).toFixed(2) + uT;
|
||
}
|
||
|
||
function renderTopClientsTable(topClients) {
|
||
const tbody = $('statsTopClientsBody'); if (!tbody) return;
|
||
if (!topClients || !topClients.length) { tbody.innerHTML = '<tr><td colspan="7" class="empty">' + t('no_traffic_history', 'Aucun historique de consommation disponible') + '</td></tr>'; renderPagination('statsTopClientsPagination', 1, 0, 'changeTopClientsPage', 10); return }
|
||
const totalPages = Math.max(1, Math.ceil(topClients.length / 10));
|
||
if (topClientsPage > totalPages) topClientsPage = totalPages; if (topClientsPage < 1) topClientsPage = 1;
|
||
const paged = topClients.slice((topClientsPage - 1) * 10, topClientsPage * 10);
|
||
tbody.innerHTML = paged.map((c, idx) => {
|
||
const rank = (topClientsPage - 1) * 10 + idx + 1; const rankBadge = rank === 1 ? '🥇 1' : rank === 2 ? '🥈 2' : rank === 3 ? '🥉 3' : '#' + rank;
|
||
const nameEsc = String(c.name || t('unknown_client', 'Nom non communiqué')).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const initial = String(c.name || '?')[0].toUpperCase();
|
||
return `<tr><td style="font-weight:700;color:var(--muted);width:45px">${rankBadge}</td><td><div class="client"><div class="avatar">${initial}</div><div><strong>${nameEsc}</strong><div class="muted" style="font-size:11px">${t('last_activity', 'Dernière activité :')} ${c.last_seen || '—'}</div></div></div></td><td><code>${c.ip || '—'}</code></td><td><code>${c.mac || '—'}</code></td><td style="font-family:monospace;font-weight:700;color:var(--blue)">↓ ${c.download_str || formatBytes(c.download_bytes)}</td><td style="font-family:monospace;font-weight:700;color:var(--green)">↑ ${c.upload_str || formatBytes(c.upload_bytes)}</td><td style="font-family:monospace;font-weight:800;color:var(--text)">${c.total_str || formatBytes(c.total_bytes)}</td></tr>`;
|
||
}).join('');
|
||
renderPagination('statsTopClientsPagination', topClientsPage, topClients.length, 'changeTopClientsPage', 10);
|
||
}
|
||
function getTopClientsForCurrentRange(data) {
|
||
if (!data) return [];
|
||
const range = currentStatsRange || 'day';
|
||
if (data.top_clients_by_range && data.top_clients_by_range[range]) {
|
||
return data.top_clients_by_range[range];
|
||
}
|
||
return data.top_clients || [];
|
||
}
|
||
|
||
function updateTopClientsForRange(range) {
|
||
const subMap = {
|
||
day: t('top_clients_sub_day', 'Appareils ayant le plus consommé aujourd’hui (Par jour)'),
|
||
week: t('top_clients_sub_week', 'Appareils ayant le plus consommé cette semaine (Par semaine)'),
|
||
month: t('top_clients_sub_month', 'Appareils ayant le plus consommé ce mois-ci (Par mois)'),
|
||
year: t('top_clients_sub_year', 'Appareils ayant le plus consommé cette année (Par année)')
|
||
};
|
||
const subEl = $('statsTopClientsSubtitle');
|
||
if (subEl) subEl.textContent = subMap[range] || subMap.day;
|
||
if (statsDataCache) {
|
||
renderTopClientsTable(getTopClientsForCurrentRange(statsDataCache));
|
||
const updateText = formatLastUpdated(statsDataCache.updated_at);
|
||
if ($('statsTrafficUpdated')) $('statsTrafficUpdated').textContent = updateText;
|
||
if ($('statsHistoryUpdated')) $('statsHistoryUpdated').textContent = updateText;
|
||
if ($('statsChartUpdated')) $('statsChartUpdated').textContent = updateText;
|
||
}
|
||
}
|
||
|
||
window.changeTopClientsPage = (p) => {
|
||
topClientsPage = p;
|
||
if (statsDataCache) renderTopClientsTable(getTopClientsForCurrentRange(statsDataCache));
|
||
};
|
||
|
||
function getStatsTableSub(range) {
|
||
if (range === 'day') {
|
||
const nowH = new Date().getHours();
|
||
const curHStr = String(nowH).padStart(2, '0');
|
||
return `${t('stats_today', 'Aujourd’hui')} • ${t('chart_current_slot', 'Tranche actuelle :')} ${curHStr}:00 – ${curHStr}:59`;
|
||
}
|
||
const subTitles = {
|
||
week: t('chart_sub_week', 'Nombre de connectés par semaine (12 dernières semaines)'),
|
||
month: t('chart_sub_month', 'Nombre de connectés par mois (12 derniers mois)'),
|
||
year: t('chart_sub_year', 'Nombre de connectés par année')
|
||
};
|
||
return subTitles[range] || '';
|
||
}
|
||
|
||
function getStatsChartSub(range) {
|
||
if (range === 'day') {
|
||
const nowH = new Date().getHours();
|
||
const curHStr = String(nowH).padStart(2, '0');
|
||
return `${t('chart_sub_day', 'Fréquentation par heure (aujourd’hui)')} • ${t('chart_current_slot', 'Tranche actuelle :')} ${curHStr}:00 – ${curHStr}:59`;
|
||
}
|
||
const subTitles = {
|
||
day: t('chart_sub_day', 'Fréquentation par heure (aujourd’hui)'),
|
||
week: t('chart_sub_week', 'Nombre de connectés par semaine (12 dernières semaines)'),
|
||
month: t('chart_sub_month', 'Nombre de connectés par mois (12 derniers mois)'),
|
||
year: t('chart_sub_year', 'Nombre de connectés par année')
|
||
};
|
||
return subTitles[range] || '';
|
||
}
|
||
|
||
let isStatsLoading = false;
|
||
async function loadStats() {
|
||
if (isStatsLoading) return;
|
||
isStatsLoading = true;
|
||
try {
|
||
const response = await apiFetch('/api/stats', { cache: 'no-store', timeout: 10000 }); if (!response.ok) throw Error('API indisponible');
|
||
const data = await response.json(); statsDataCache = data;
|
||
if ($('statsTodayUnique')) $('statsTodayUnique').textContent = data.summary.today.unique;
|
||
if ($('statsTodayTotal')) $('statsTodayTotal').textContent = data.summary.today.total;
|
||
if ($('statsWeekUnique')) $('statsWeekUnique').textContent = data.summary.week.unique;
|
||
if ($('statsWeekTotal')) $('statsWeekTotal').textContent = data.summary.week.total;
|
||
if ($('statsMonthUnique')) $('statsMonthUnique').textContent = data.summary.month.unique;
|
||
if ($('statsMonthTotal')) $('statsMonthTotal').textContent = data.summary.month.total;
|
||
if ($('statsYearUnique')) $('statsYearUnique').textContent = data.summary.year.unique;
|
||
if ($('statsYearTotal')) $('statsYearTotal').textContent = data.summary.year.total;
|
||
if ($('statsChartSubtitle')) $('statsChartSubtitle').textContent = getStatsChartSub(currentStatsRange);
|
||
if ($('statsTableSub')) $('statsTableSub').textContent = getStatsTableSub(currentStatsRange);
|
||
renderStatsChart(currentStatsRange);
|
||
updateTopClientsForRange(currentStatsRange);
|
||
const updateText = formatLastUpdated(data.updated_at);
|
||
if ($('statsTrafficUpdated')) $('statsTrafficUpdated').textContent = updateText;
|
||
if ($('statsHistoryUpdated')) $('statsHistoryUpdated').textContent = updateText;
|
||
if ($('statsChartUpdated')) $('statsChartUpdated').textContent = updateText;
|
||
} catch (e) {
|
||
const isAbort = e.name === 'AbortError' || e.name === 'TimeoutError' || (e.message && e.message.toLowerCase().includes('abort'));
|
||
if (isAbort && statsDataCache) return;
|
||
console.error('Erreur stats:', e);
|
||
if ($('statsTableBody')) $('statsTableBody').innerHTML = '<tr><td colspan="4" class="empty">API indisponible : ' + e.message + '</td></tr>';
|
||
if ($('statsTopClientsBody')) $('statsTopClientsBody').innerHTML = '<tr><td colspan="7" class="empty">API indisponible : ' + e.message + '</td></tr>';
|
||
} finally {
|
||
isStatsLoading = false;
|
||
}
|
||
}
|
||
|
||
function setStatsRange(range) {
|
||
currentStatsRange = range; statsTablePage = 1; topClientsPage = 1;
|
||
document.querySelectorAll('.stats-range-btn').forEach(btn => btn.classList.remove('active'));
|
||
const btnMap = { day: 'statsRangeDay', week: 'statsRangeWeek', month: 'statsRangeMonth', year: 'statsRangeYear' };
|
||
const btn = $(btnMap[range]); if (btn) btn.classList.add('active');
|
||
if ($('statsChartSubtitle')) $('statsChartSubtitle').textContent = getStatsChartSub(range);
|
||
if ($('statsTableSub')) $('statsTableSub').textContent = getStatsTableSub(range);
|
||
const box = $('statsChartBox'); if (box) box.style.height = range === 'day' ? '540px' : '340px';
|
||
renderStatsChart(range, true);
|
||
updateTopClientsForRange(range);
|
||
}
|
||
|
||
function localizeStatsLabel(it, isDay) {
|
||
if (!it) return { label: '', fullLabel: '' };
|
||
const isEn = typeof currentLanguage === 'string' && currentLanguage.startsWith('en');
|
||
if (!isEn) {
|
||
return { label: it.label || '', fullLabel: it.full_label || it.label || '' };
|
||
}
|
||
if (it.full_label_en || it.label_en) {
|
||
return { label: it.label_en || it.label || '', fullLabel: it.full_label_en || it.full_label || '' };
|
||
}
|
||
let label = it.label || '';
|
||
let full = it.full_label || it.label || '';
|
||
if (it.hour !== undefined || isDay || (full && full.includes('Aujourd’hui'))) {
|
||
const h = it.hour !== undefined ? it.hour : (it.period ? parseInt(it.period.split(' ')[1] || '0', 10) : 0);
|
||
const hPad = String(h).padStart(2, '0');
|
||
return { label: `${hPad}:00`, fullLabel: `Today from ${hPad}:00 to ${hPad}:59` };
|
||
}
|
||
if (label.startsWith('Sem ') || full.startsWith('Semaine ')) {
|
||
label = label.replace(/^Sem\s+/i, 'Wk ');
|
||
full = full.replace(/^Semaine\s+/i, 'Week ').replace(/\(du\s+/i, '(from ').replace(/\s+au\s+/i, ' to ');
|
||
return { label, fullLabel: full };
|
||
}
|
||
if (full.startsWith('Année ')) {
|
||
return { label, fullLabel: full.replace(/^Année\s+/i, 'Year ') };
|
||
}
|
||
const dayFr = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'];
|
||
const dayEn = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
|
||
const dayShortFr = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'];
|
||
const dayShortEn = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
||
const monthFr = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
|
||
const monthEn = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
||
const monthShortFr = ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil', 'Août', 'Sep', 'Oct', 'Nov', 'Déc'];
|
||
const monthShortEn = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||
for (let i = 0; i < 7; i++) {
|
||
if (label.startsWith(dayShortFr[i] + ' ')) label = dayShortEn[i] + label.slice(dayShortFr[i].length);
|
||
if (full.startsWith(dayFr[i] + ' ')) full = dayEn[i] + full.slice(dayFr[i].length);
|
||
}
|
||
for (let i = 0; i < 12; i++) {
|
||
full = full.replace(new RegExp('\\b' + monthFr[i] + '\\b', 'gi'), monthEn[i]);
|
||
const reShort = new RegExp('^' + monthShortFr[i] + '\\b', 'i');
|
||
if (reShort.test(label)) label = label.replace(reShort, monthShortEn[i]);
|
||
}
|
||
return { label, fullLabel: full };
|
||
}
|
||
|
||
function renderStatsChart(range, force = false) {
|
||
if (!statsDataCache) return;
|
||
const isDay = range === 'day';
|
||
const items = isDay ? (statsDataCache.hours || statsDataCache.days || []) : (statsDataCache[range + 's'] || []);
|
||
const isLight = document.documentElement.dataset.theme === 'light' || document.documentElement.dataset.theme === 'winxp' || (document.documentElement.dataset.theme === 'macos' && (typeof themeMedia !== 'undefined' ? themeMedia.matches : true));
|
||
const textColor = isLight ? '#15203a' : '#eef4ff';
|
||
const mutedColor = isLight ? '#5b6b8c' : '#9aa8c5';
|
||
const gridColor = isLight ? 'rgba(0,0,0,0.08)' : 'rgba(255,255,255,0.08)';
|
||
const canvas = $('statsChartCanvas'); const svgBox = $('statsSvgFallback');
|
||
const box = $('statsChartBox'); const targetHeight = isDay ? '540px' : '340px';
|
||
if (box && box.style.height !== targetHeight) box.style.height = targetHeight;
|
||
const currentAxis = isDay ? 'y' : 'x';
|
||
const dataKey = range + '|' + (isLight ? 'light' : 'dark') + '|' + items.map(x => x.unique_clients + ',' + x.total_connections).join(';');
|
||
|
||
if (window.Chart) {
|
||
svgBox.style.display = 'none'; canvas.style.display = 'block';
|
||
if (statsChartInstance && previousChartAxis === currentAxis && !force) {
|
||
if (previousChartDataKey === dataKey) { renderStatsTable(items, isDay); return }
|
||
statsChartInstance.data.labels = items.map((x, i) => { const loc = localizeStatsLabel(x, isDay); return (isDay && (x.hour === (new Date().getHours()) || i === (new Date().getHours()))) ? (loc.label + ' ●') : loc.label });
|
||
statsChartInstance.data.datasets[0].data = items.map(x => x.unique_clients);
|
||
statsChartInstance.data.datasets[1].data = items.map(x => x.total_connections);
|
||
statsChartInstance.update('none'); previousChartDataKey = dataKey; renderStatsTable(items, isDay); return;
|
||
}
|
||
if (statsChartInstance) { statsChartInstance.destroy(); statsChartInstance = null }
|
||
previousChartAxis = currentAxis; previousChartDataKey = dataKey;
|
||
const ctx = canvas.getContext('2d');
|
||
statsChartInstance = new Chart(ctx, {
|
||
type: 'bar',
|
||
data: {
|
||
labels: items.map((x, i) => { const loc = localizeStatsLabel(x, isDay); return (isDay && (x.hour === (new Date().getHours()) || i === (new Date().getHours()))) ? (loc.label + ' ●') : loc.label }),
|
||
datasets: [
|
||
{ label: t('stats_chart_unique_devices', 'Appareils uniques'), data: items.map(x => x.unique_clients), backgroundColor: isLight ? 'rgba(30, 110, 240, 0.75)' : 'rgba(92, 167, 255, 0.75)', borderColor: isLight ? '#1e6ef0' : '#5ca7ff', borderWidth: 1.5, borderRadius: 4, maxBarThickness: isDay ? 13 : 28 },
|
||
{ label: t('stats_chart_total_connections', 'Connexions totales'), data: items.map(x => x.total_connections), backgroundColor: isLight ? 'rgba(19, 160, 106, 0.75)' : 'rgba(50, 213, 131, 0.75)', borderColor: isLight ? '#13a06a' : '#32d583', borderWidth: 1.5, borderRadius: 4, maxBarThickness: isDay ? 13 : 28 }
|
||
]
|
||
},
|
||
options: {
|
||
indexAxis: currentAxis, responsive: true, maintainAspectRatio: false, animation: false,
|
||
plugins: { legend: { position: 'top', labels: { color: textColor, font: { family: 'system-ui, sans-serif', size: 12, weight: '600' }, usePointStyle: true, pointStyle: 'circle' } }, tooltip: { callbacks: { title: arr => { const idx = arr[0].dataIndex; if (!items[idx]) return ''; const loc = localizeStatsLabel(items[idx], isDay); return loc.fullLabel || loc.label } } } },
|
||
scales: isDay ? { x: { beginAtZero: true, grid: { color: gridColor }, ticks: { color: mutedColor, precision: 0, font: { size: 11 } } }, y: { grid: { color: gridColor }, ticks: { color: textColor, font: { size: 11, weight: '700' }, autoSkip: false } } } : { x: { grid: { color: gridColor }, ticks: { color: mutedColor, font: { size: 11 }, maxRotation: 45, autoSkip: true, maxTicksLimit: 15 } }, y: { beginAtZero: true, grid: { color: gridColor }, ticks: { color: mutedColor, precision: 0, font: { size: 11 } } } }
|
||
}
|
||
});
|
||
} else {
|
||
canvas.style.display = 'none'; svgBox.style.display = 'block';
|
||
if (previousChartDataKey !== dataKey) { renderSvgStatsChart(svgBox, items, isLight, isDay); previousChartDataKey = dataKey; }
|
||
}
|
||
renderStatsTable(items, isDay);
|
||
}
|
||
|
||
function renderSvgStatsChart(container, items, isLight, isDay) {
|
||
const width = 800, height = isDay ? 540 : 320, padL = isDay ? 50 : 45, padR = 20, padT = 38, padB = isDay ? 30 : 45, plotW = width - padL - padR, plotH = height - padT - padB;
|
||
const textColor = isLight ? '#15203a' : '#eef4ff', mutedColor = isLight ? '#5b6b8c' : '#9aa8c5', gridColor = isLight ? '#d5deee' : '#283757', blueColor = isLight ? '#1e6ef0' : '#5ca7ff', greenColor = isLight ? '#13a06a' : '#32d583';
|
||
let maxVal = 0; items.forEach(it => { if (it.unique_clients > maxVal) maxVal = it.unique_clients; if (it.total_connections > maxVal) maxVal = it.total_connections });
|
||
let scaleMax = maxVal <= 4 ? 4 : Math.ceil(maxVal * 1.2);
|
||
const lblUnique = t('stats_chart_unique_devices', 'Appareils uniques'); const lblTotal = t('stats_chart_total_connections', 'Connexions totales'); let svg = `<svg viewBox="0 0 ${width} ${height}" width="100%" height="100%" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" style="font-family:system-ui,sans-serif"><g transform="translate(${width / 2 - 130}, 16)"><circle cx="0" cy="0" r="5" fill="${blueColor}" /><text x="10" y="4" font-size="12" font-weight="600" fill="${textColor}">${lblUnique}</text><circle cx="160" cy="0" r="5" fill="${greenColor}" /><text x="170" y="4" font-size="12" font-weight="600" fill="${textColor}">${lblTotal}</text></g>`;
|
||
if (isDay) {
|
||
for (let step = 0; step <= 4; step++) { const xVal = Math.round((scaleMax / 4) * step), xPos = padL + (xVal / scaleMax) * plotW; svg += `<line x1="${xPos}" y1="${padT}" x2="${xPos}" y2="${padT + plotH}" stroke="${gridColor}" stroke-dasharray="3,3" stroke-width="1" /><text x="${xPos}" y="${height - 12}" font-size="10" text-anchor="middle" fill="${mutedColor}">${xVal}</text>` }
|
||
const n = Math.max(items.length, 1), slotH = plotH / n, barH = Math.min(8, Math.max(3, (slotH - 4) / 2));
|
||
items.forEach((it, i) => {
|
||
const isCur = isDay && (it.hour === (new Date().getHours()) || i === (new Date().getHours()));
|
||
const loc = localizeStatsLabel(it, isDay);
|
||
const cy = padT + i * slotH + slotH / 2, uW = Math.max(0, (it.unique_clients / scaleMax) * plotW), tW = Math.max(0, (it.total_connections / scaleMax) * plotW), tip = `${loc.fullLabel || loc.label} : ${it.unique_clients} ${t('stats_tip_clients', 'client(s) unique(s)')}, ${it.total_connections} ${t('stats_tip_connections', 'connexion(s)')}`;
|
||
const lblText = isCur ? `${loc.label} ●` : loc.label;
|
||
const lblColor = isCur ? greenColor : textColor;
|
||
svg += `<text x="${padL - 8}" y="${cy + 4}" font-size="11" font-weight="700" text-anchor="end" fill="${lblColor}">${lblText}</text><rect class="svg-bar" x="${padL}" y="${cy - barH - 1}" width="${uW}" height="${barH}" fill="${blueColor}" rx="2"><title>${tip}</title></rect><rect class="svg-bar" x="${padL}" y="${cy + 1}" width="${tW}" height="${barH}" fill="${greenColor}" rx="2"><title>${tip}</title></rect>`;
|
||
});
|
||
} else {
|
||
for (let step = 0; step <= 4; step++) { const yVal = Math.round((scaleMax / 4) * step), yPos = padT + plotH - (yVal / scaleMax) * plotH; svg += `<line x1="${padL}" y1="${yPos}" x2="${width - padR}" y2="${yPos}" stroke="${gridColor}" stroke-dasharray="3,3" stroke-width="1" /><text x="${padL - 8}" y="${yPos + 4}" font-size="11" text-anchor="end" fill="${mutedColor}">${yVal}</text>` }
|
||
const n = Math.max(items.length, 1), slotW = plotW / n, barW = Math.min(22, Math.max(3, (slotW - 6) / 2)), skipLabel = n > 16 ? Math.ceil(n / 12) : 1;
|
||
items.forEach((it, i) => {
|
||
const loc = localizeStatsLabel(it, false);
|
||
const cx = padL + i * slotW + slotW / 2, uH = Math.max(0, (it.unique_clients / scaleMax) * plotH), tH = Math.max(0, (it.total_connections / scaleMax) * plotH), tip = `${loc.fullLabel || loc.label} : ${it.unique_clients} ${t('stats_tip_clients', 'client(s) unique(s)')}, ${it.total_connections} ${t('stats_tip_connections', 'connexion(s)')}`;
|
||
svg += `<rect class="svg-bar" x="${cx - barW - 1}" y="${padT + plotH - uH}" width="${barW}" height="${uH}" fill="${blueColor}" rx="3"><title>${tip}</title></rect><rect class="svg-bar" x="${cx + 1}" y="${padT + plotH - tH}" width="${barW}" height="${tH}" fill="${greenColor}" rx="3"><title>${tip}</title></rect>`;
|
||
if (i % skipLabel === 0 || i === items.length - 1) svg += `<text x="${cx}" y="${height - 14}" font-size="10" text-anchor="middle" fill="${mutedColor}">${loc.label}</text>`;
|
||
});
|
||
}
|
||
svg += '</svg>'; container.innerHTML = svg;
|
||
}
|
||
|
||
function renderStatsTable(items, isDay) {
|
||
const tbody = $('statsTableBody'); if (!tbody) return;
|
||
let list = [];
|
||
if (isDay && items && items.length === 24) {
|
||
const curH = new Date().getHours();
|
||
const currentAndPast = [];
|
||
for (let h = curH; h >= 0; h--) {
|
||
const it = items[h];
|
||
if (it) currentAndPast.push({ ...it, isCurrentHour: h === curH, isPast: h < curH });
|
||
}
|
||
const future = [];
|
||
for (let h = 23; h > curH; h--) {
|
||
const it = items[h];
|
||
if (it) future.push({ ...it, isFuture: true });
|
||
}
|
||
list = [...currentAndPast, ...future];
|
||
} else {
|
||
list = [...items].reverse();
|
||
}
|
||
if (!list.length) { tbody.innerHTML = `<tr><td colspan="4" class="empty">${t('stats_no_data', 'Aucune statistique disponible')}</td></tr>`; renderPagination('statsTablePagination', 1, 0, 'changeStatsTablePage', 10); return }
|
||
const totalPages = Math.max(1, Math.ceil(list.length / 10));
|
||
if (statsTablePage > totalPages) statsTablePage = totalPages; if (statsTablePage < 1) statsTablePage = 1;
|
||
const paged = list.slice((statsTablePage - 1) * 10, statsTablePage * 10);
|
||
tbody.innerHTML = paged.map(it => {
|
||
const devHtml = it.devices && it.devices.length ? it.devices.map(d => `<span class="device-pill">${String(d).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';')}</span>`).join('') : '<span class="muted">—</span>';
|
||
let labelText = '';
|
||
let rowStyle = '';
|
||
const loc = localizeStatsLabel(it, isDay);
|
||
if (isDay) {
|
||
const curBadge = it.isCurrentHour ? `<span class="pill pill-green" style="font-size:11px;padding:2px 8px;margin-left:8px;font-weight:700;box-shadow:0 0 8px rgba(50,213,131,.35)">${t('stats_current_slot_badge', 'Tranche actuelle')}</span>` : (it.isFuture ? `<span class="muted" style="font-size:11px;margin-left:8px;opacity:.7">${t('stats_upcoming', '(À venir)')}</span>` : '');
|
||
labelText = `<strong>${loc.label}</strong> <span class="muted" style="font-size:12px;margin-left:6px">${loc.fullLabel}</span>${curBadge}`;
|
||
if (it.isCurrentHour) {
|
||
rowStyle = 'style="background:rgba(92,167,255,0.08);border-left:3px solid var(--blue)"';
|
||
}
|
||
} else {
|
||
labelText = `<strong>${loc.fullLabel || loc.label}</strong>`;
|
||
}
|
||
return `<tr ${rowStyle}><td>${labelText}</td><td><span class="pill" style="font-size:12px;background:var(--panel2);color:var(--blue)">${it.unique_clients}</span></td><td><strong>${it.total_connections}</strong></td><td>${devHtml}</td></tr>`;
|
||
}).join('');
|
||
renderPagination('statsTablePagination', statsTablePage, list.length, 'changeStatsTablePage', 10);
|
||
}
|
||
window.changeStatsTablePage = (p) => { statsTablePage = p; if (statsDataCache) { const isDay = currentStatsRange === 'day'; const itms = isDay ? (statsDataCache.hours || statsDataCache.days || []) : (statsDataCache[currentStatsRange + 's'] || []); renderStatsTable(itms, isDay) } };
|
||
|
||
let captureStartTime = null;
|
||
let captureTimerInterval = null;
|
||
|
||
function formatCaptureDuration(sec) {
|
||
sec = Math.max(0, Math.floor(sec || 0));
|
||
const h = Math.floor(sec / 3600);
|
||
const m = Math.floor((sec % 3600) / 60);
|
||
const s = sec % 60;
|
||
const pad = n => String(n).padStart(2, '0');
|
||
return h > 0 ? `${pad(h)}:${pad(m)}:${pad(s)}` : `${pad(m)}:${pad(s)}`;
|
||
}
|
||
|
||
function updateCaptureTimerDisplay() {
|
||
const badge = $('captureDurationBadge');
|
||
if (!badge) return;
|
||
if (!captureRunning || !captureStartTime) {
|
||
badge.textContent = '00:00';
|
||
return;
|
||
}
|
||
const now = Date.now() / 1000;
|
||
const elapsed = Math.max(0, now - captureStartTime);
|
||
const timeStr = formatCaptureDuration(elapsed);
|
||
badge.textContent = timeStr;
|
||
if ($('captureStatusBadge') && captureRunning) {
|
||
$('captureStatusBadge').textContent = '● ' + t('adv_pcap_capture_in_progress', 'Capture en cours ({time})').replace('{time}', timeStr);
|
||
}
|
||
}
|
||
|
||
function ensureCaptureTimer() {
|
||
if (captureTimerInterval) return;
|
||
captureTimerInterval = setInterval(updateCaptureTimerDisplay, 500);
|
||
}
|
||
|
||
function stopCaptureTimer() {
|
||
if (captureTimerInterval) {
|
||
clearInterval(captureTimerInterval);
|
||
captureTimerInterval = null;
|
||
}
|
||
const badge = $('captureDurationBadge');
|
||
if (badge) badge.textContent = '00:00';
|
||
}
|
||
|
||
async function loadCaptureStatus() {
|
||
try {
|
||
const r = await apiFetch('/api/advanced/capture/status', { cache: 'no-store' });
|
||
if (!r.ok) return;
|
||
const d = await r.json();
|
||
captureRunning = !!d.running;
|
||
captureStats = d.stats || {};
|
||
|
||
if (captureRunning) {
|
||
if (d.started_at && d.started_at > 0) {
|
||
captureStartTime = d.started_at;
|
||
} else if (!captureStartTime) {
|
||
captureStartTime = Date.now() / 1000;
|
||
}
|
||
ensureCaptureTimer();
|
||
updateCaptureTimerDisplay();
|
||
$('captureStatusBadge').style.background = 'rgba(34,197,94,.18)';
|
||
$('captureStatusBadge').style.color = 'var(--green)';
|
||
} else {
|
||
captureStartTime = null;
|
||
stopCaptureTimer();
|
||
$('captureStatusBadge').textContent = '○ ' + t('adv_pcap_status_inactive', 'Inactif');
|
||
$('captureStatusBadge').style.background = 'var(--panel2)';
|
||
$('captureStatusBadge').style.color = 'var(--muted)';
|
||
}
|
||
|
||
$('captureIfaceInfo').textContent = t('adv_pcap_iface_label', 'Interface Wi-Fi : ') + (d.interface || status.interface || 'Wi-Fi');
|
||
|
||
const total = d.total_captured !== undefined ? d.total_captured : (d.total_packets || 0);
|
||
const buf = d.packet_count !== undefined ? d.packet_count : (d.buffer_packets || 0);
|
||
const pcapSz = d.pcap_bytes !== undefined ? d.pcap_bytes : (d.pcap_size_bytes || 0);
|
||
|
||
const isEn = typeof currentLanguage !== 'undefined' && currentLanguage.startsWith('en');
|
||
const numLocale = isEn ? 'en-US' : 'fr-FR';
|
||
$('captureTotalCount').textContent = Number(total).toLocaleString(numLocale);
|
||
const keptWord = (capturePackets.length || buf) > 1 ? t('packets_kept_plural', 'paquets conservés') : t('packets_kept_singular', 'paquet conservé');
|
||
$('captureBufferSize').textContent = (capturePackets.length || buf) + ' ' + keptWord;
|
||
$('capturePcapSize').textContent = formatBytes(pcapSz);
|
||
if ($('captureDomainsCount')) $('captureDomainsCount').textContent = d.unique_domains_count !== undefined ? d.unique_domains_count : (d.domains ? d.domains.length : 0);
|
||
$('startCaptureBtn').style.display = captureRunning ? 'none' : '';
|
||
$('stopCaptureBtn').style.display = captureRunning ? 'inline-flex' : 'none';
|
||
if ($('statDns')) $('statDns').textContent = captureStats.dns || 0;
|
||
if ($('statIcmp')) $('statIcmp').textContent = captureStats.icmp || 0;
|
||
if ($('statTcp')) $('statTcp').textContent = captureStats.tcp || 0;
|
||
if ($('statUdp')) $('statUdp').textContent = captureStats.udp || 0;
|
||
if ($('statArp')) $('statArp').textContent = captureStats.arp || 0;
|
||
if ($('statTls')) $('statTls').textContent = captureStats.tls || 0;
|
||
if ($('statDhcp')) $('statDhcp').textContent = captureStats.dhcp || 0;
|
||
if ($('captureUpdated')) $('captureUpdated').textContent = formatLastUpdated();
|
||
} catch (_) { }
|
||
}
|
||
|
||
function escHtml(str) {
|
||
if (str === null || str === undefined) return '';
|
||
return String(str).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
}
|
||
|
||
const OFFLINE_SVG_FLAGS = {
|
||
fr: '<svg class="flag-icon" viewBox="0 0 3 2" width="16" height="11"><rect width="1" height="2" fill="#002654"/><rect x="1" width="1" height="2" fill="#ffffff"/><rect x="2" width="1" height="2" fill="#ce1126"/></svg>',
|
||
us: '<svg class="flag-icon" viewBox="0 0 19 10" width="16" height="11"><rect width="19" height="10" fill="#b22234"/><path d="M0,1.54h19M0,3.08h19M0,4.62h19M0,6.15h19M0,7.69h19M0,9.23h19" stroke="#ffffff" stroke-width="0.77"/><rect width="7.6" height="5.38" fill="#3c3b6e"/></svg>',
|
||
de: '<svg class="flag-icon" viewBox="0 0 5 3" width="16" height="11"><rect width="5" height="1" fill="#000000"/><rect y="1" width="5" height="1" fill="#dd0000"/><rect y="2" width="5" height="1" fill="#ffce00"/></svg>',
|
||
gb: '<svg class="flag-icon" viewBox="0 0 60 30" width="16" height="11"><clipPath id="fgb"><path d="M0 0v30h60V0z"/></clipPath><g clip-path="url(#fgb)"><path d="M0 0v30h60V0z" fill="#012169"/><path d="M0 0l60 30M60 0L0 30" stroke="#fff" stroke-width="6"/><path d="M0 0l60 30M60 0L0 30" stroke="#C8102E" stroke-width="4"/><path d="M30 0v30M0 15h60" stroke="#fff" stroke-width="10"/><path d="M30 0v30M0 15h60" stroke="#C8102E" stroke-width="6"/></g></svg>',
|
||
ch: '<svg class="flag-icon" viewBox="0 0 32 32" width="12" height="12"><rect width="32" height="32" fill="#d52b1e"/><rect x="13" y="6" width="6" height="20" fill="#ffffff"/><rect x="6" y="13" width="20" height="6" fill="#ffffff"/></svg>',
|
||
be: '<svg class="flag-icon" viewBox="0 0 3 2" width="16" height="11"><rect width="1" height="2" fill="#000000"/><rect x="1" width="1" height="2" fill="#ffd90c"/><rect x="2" width="1" height="2" fill="#f31830"/></svg>',
|
||
nl: '<svg class="flag-icon" viewBox="0 0 3 2" width="16" height="11"><rect width="3" height="1" fill="#ae1c28"/><rect y="1" width="3" height="1" fill="#ffffff"/><rect y="2" width="3" height="1" fill="#21468b"/></svg>',
|
||
es: '<svg class="flag-icon" viewBox="0 0 3 2" width="16" height="11"><rect width="3" height="2" fill="#aa151b"/><rect y="0.5" width="3" height="1" fill="#f1bf00"/></svg>',
|
||
it: '<svg class="flag-icon" viewBox="0 0 3 2" width="16" height="11"><rect width="1" height="2" fill="#009246"/><rect x="1" width="1" height="2" fill="#ffffff"/><rect x="2" width="1" height="2" fill="#ce2b37"/></svg>',
|
||
ca: '<svg class="flag-icon" viewBox="0 0 4 2" width="16" height="11"><rect width="1" height="2" fill="#d80027"/><rect x="1" width="2" height="2" fill="#ffffff"/><rect x="3" width="1" height="2" fill="#d80027"/><polygon points="2,0.4 2.15,0.7 2.45,0.6 2.35,0.85 2.65,1 2.35,1.1 2.4,1.35 2.1,1.25 2.05,1.55 1.95,1.55 1.9,1.25 1.6,1.35 1.65,1.1 1.35,1 1.65,0.85 1.55,0.6 1.85,0.7" fill="#d80027"/></svg>',
|
||
jp: '<svg class="flag-icon" viewBox="0 0 3 2" width="16" height="11"><rect width="3" height="2" fill="#ffffff"/><circle cx="1.5" cy="1" r="0.6" fill="#bc002d"/></svg>',
|
||
ie: '<svg class="flag-icon" viewBox="0 0 3 2" width="16" height="11"><rect width="1" height="2" fill="#169b62"/><rect x="1" width="1" height="2" fill="#ffffff"/><rect x="2" width="1" height="2" fill="#ff883e"/></svg>',
|
||
pt: '<svg class="flag-icon" viewBox="0 0 3 2" width="16" height="11"><rect width="1.2" height="2" fill="#046a38"/><rect x="1.2" width="1.8" height="2" fill="#da291c"/><circle cx="1.2" cy="1" r="0.35" fill="#ffcd00"/></svg>',
|
||
at: '<svg class="flag-icon" viewBox="0 0 3 2" width="16" height="11"><rect width="3" height="2" fill="#ed2939"/><rect y="0.67" width="3" height="0.66" fill="#ffffff"/></svg>',
|
||
se: '<svg class="flag-icon" viewBox="0 0 16 10" width="16" height="11"><rect width="16" height="10" fill="#006aa7"/><rect x="5" width="2" height="10" fill="#fecc00"/><rect y="4" width="16" height="2" fill="#fecc00"/></svg>',
|
||
pl: '<svg class="flag-icon" viewBox="0 0 16 10" width="16" height="11"><rect width="16" height="5" fill="#ffffff"/><rect y="5" width="16" height="5" fill="#dc143c"/></svg>',
|
||
eu: '<svg class="flag-icon" viewBox="0 0 3 2" width="16" height="11"><rect width="3" height="2" fill="#003399"/><circle cx="1.5" cy="1" r="0.6" fill="none" stroke="#ffcc00" stroke-width="0.15" stroke-dasharray="0.08 0.23"/></svg>'
|
||
};
|
||
|
||
function getCountryFlagHtml(code, flagEmoji, countryName, isLan) {
|
||
if (isLan || code === 'LAN') {
|
||
return '<span class="flag-icon-wrap" title="Réseau local (LAN)"><span style="font-size:12px;line-height:1">🏠</span></span>';
|
||
}
|
||
if (code === 'MCAST' || code === 'BCAST') {
|
||
return '<span class="flag-icon-wrap" title="Diffusion / Multicast"><span style="font-size:12px;line-height:1">📡</span></span>';
|
||
}
|
||
if (!code || code === 'WAN' || code === 'EXT') {
|
||
return '<span class="flag-icon-wrap" title="Internet / WAN"><span style="font-size:12px;line-height:1">🌐</span></span>';
|
||
}
|
||
const c = String(code).trim().toUpperCase();
|
||
const cLow = c.toLowerCase();
|
||
const cEsc = escHtml(countryName || c);
|
||
if (/^[A-Z]{2}$/.test(c)) {
|
||
if (OFFLINE_SVG_FLAGS[cLow]) {
|
||
return `<span class="flag-icon-wrap" title="${cEsc} (${c})">${OFFLINE_SVG_FLAGS[cLow]}</span>`;
|
||
}
|
||
return `<span class="flag-icon-wrap" title="${cEsc} (${c})"><img class="flag-icon" src="https://flagcdn.com/24x18/${cLow}.png" srcset="https://flagcdn.com/48x36/${cLow}.png 2x" width="16" height="11" alt="${c}" loading="lazy" style="border-radius:2px;object-fit:cover;vertical-align:middle;box-shadow:0 0 1px rgba(0,0,0,0.5);display:inline-block" onerror="this.style.display='none';this.nextElementSibling.style.display='inline'"><span class="flag-fallback" style="display:none">${flagEmoji || '🌐'}</span></span>`;
|
||
}
|
||
return `<span class="flag-icon-wrap" title="${cEsc}">${flagEmoji || '🌐'}</span>`;
|
||
}
|
||
|
||
function formatIpWithGeo(ip, geo, mac) {
|
||
if (!ip) return '<span class="muted">—</span>';
|
||
const ipStr = String(ip);
|
||
const ipEsc = escHtml(ipStr);
|
||
if (!geo && ipStr.includes(':') && ipStr.length === 17 && (ipStr.match(/:/g) || []).length === 5) {
|
||
return `<code style="font-size:12px;color:var(--muted)" title="Adresse MAC : ${ipEsc}">${ipEsc}</code>`;
|
||
}
|
||
let isLan = false;
|
||
let code = 'WAN';
|
||
let flag = '🌐';
|
||
let country = 'IP Internet';
|
||
let badgeClass = 'badge-ext';
|
||
if (geo && geo.is_ip) {
|
||
isLan = !!geo.is_local;
|
||
code = geo.code || (isLan ? 'LAN' : 'WAN');
|
||
flag = geo.flag || (isLan ? '🏠' : '🌐');
|
||
country = geo.country || (isLan ? 'Réseau local' : 'IP Publique');
|
||
badgeClass = isLan ? 'badge-lan' : (code === 'WAN' ? 'badge-ext' : 'badge-country');
|
||
} else {
|
||
if (ipStr.startsWith('10.') || ipStr.startsWith('192.168.') || ipStr.startsWith('127.') || /^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(ipStr)) {
|
||
isLan = true; code = 'LAN'; flag = '🏠'; country = 'Réseau local'; badgeClass = 'badge-lan';
|
||
}
|
||
}
|
||
const flagHtml = getCountryFlagHtml(code, flag, country, isLan);
|
||
const titleText = `${country} (${code}) : ${ipEsc}` + (mac && mac !== ipStr ? ` [MAC: ${mac}]` : '');
|
||
return `<div class="ip-cell" style="display:inline-flex;align-items:center;gap:6px;max-width:100%">` +
|
||
`<span class="ip-country-badge ${badgeClass} country-filter-tag" data-country="${escHtml(code)}" title="${escHtml(country)} (${escHtml(code)})">${flagHtml} <span class="country-code">${escHtml(code)}</span></span>` +
|
||
`<code style="font-size:12px;white-space:nowrap" title="${escHtml(titleText)}">${ipEsc}</code>` +
|
||
`</div>`;
|
||
}
|
||
|
||
const VPN_LOGOS = {
|
||
wireguard: '<svg class="vpn-type-logo vpn-logo-wg" viewBox="0 0 24 24" width="18" height="18" style="vertical-align:middle;flex-shrink:0"><path fill="#88171A" d="M23.98 11.645S24.533 0 11.735 0C.418 0 .064 11.17.064 11.17S-1.6 24 11.997 24C25.04 24 23.98 11.645 23.98 11.645z"/><path fill="#ffffff" d="M8.155 7.576c2.4-1.47 5.469-.571 6.618 1.638.218.419.246 1.063.108 1.503-.477 1.516-1.601 2.366-3.145 2.728.455-.39.817-.832.933-1.442a2.112 2.112 0 0 0-.364-1.677 2.14 2.14 0 0 0-2.465-.75c-.95.36-1.47 1.228-1.377 2.294.087.99.839 1.632 2.245 1.876-.21.111-.372.193-.53.281a5.113 5.113 0 0 0-1.644 1.43c-.143.192-.24.208-.458.075-2.827-1.729-3.009-6.067.078-7.956zM6.04 18.258c-.455.116-.895.286-1.359.438.227-1.532 2.021-2.943 3.539-2.782a3.91 3.91 0 0 0-.74 2.072c-.504.093-.98.155-1.44.272zM15.703 3.3c.448.017.898.01 1.347.02a2.324 2.324 0 0 1 .334.047 3.249 3.249 0 0 1-.34.434c-.16.15-.341.296-.573.069-.055-.055-.187-.042-.283-.044-.447-.005-.894-.02-1.34-.003a8.323 8.323 0 0 0-1.154.118c-.072.013-.178.25-.146.338.078.207.191.435.359.567.619.49 1.277.928 1.9 1.413.604.472 1.167.99 1.51 1.7.446.928.46 1.9.267 2.877-.322 1.63-1.147 2.98-2.483 3.962-.538.395-1.205.62-1.821.903-.543.25-1.1.465-1.644.712-.98.446-1.53 1.51-1.369 2.615.149 1.015 1.04 1.862 2.059 2.037 1.223.21 2.486-.586 2.785-1.83.336-1.397-.423-2.646-1.845-3.024l-.256-.066c.38-.17.708-.291 1.012-.458q.793-.437 1.558-.925c.15-.096.231-.096.36.014.977.846 1.56 1.898 1.724 3.187.27 2.135-.74 4.096-2.646 5.101-2.948 1.555-6.557-.215-7.208-3.484-.558-2.8 1.418-5.34 3.797-5.83 1.023-.211 1.958-.637 2.685-1.425.47-.508.697-.944.775-1.141a3.165 3.165 0 0 0 .217-1.158 2.71 2.71 0 0 0-.237-.992c-.248-.566-1.2-1.466-1.435-1.656l-2.24-1.754c-.079-.065-.168-.06-.36-.047-.23.016-.815.048-1.067-.018.204-.155.76-.38 1-.56-.726-.49-1.554-.314-2.315-.46.176-.328 1.046-.831 1.541-.888a7.323 7.323 0 0 0-.135-.822c-.03-.111-.154-.22-.263-.283-.262-.154-.541-.281-.843-.434a1.755 1.755 0 0 1 .906-.28 3.385 3.385 0 0 1 .908.088c.54.123.97.042 1.399-.324-.338-.136-.676-.26-1.003-.407a9.843 9.843 0 0 1-.942-.493c.85.118 1.671.437 2.54.32l.022-.118-2.018-.47c1.203-.11 2.323-.128 3.384.388.299.146.61.266.897.432.14.08.233.24.348.365.09.098.164.23.276.29.424.225.89.234 1.366.223l.01-.16c.479.15 1.017.702 1.017 1.105-.776 0-1.55-.003-2.325.004-.083 0-.165.061-.247.094.078.046.155.128.235.131z M14.703 2.153a.118.118 0 0 0-.016.19.179.179 0 0 0 .246.065c.075-.038.148-.078.238-.125-.072-.062-.13-.114-.19-.163-.106-.087-.193-.032-.278.033z"/></svg>',
|
||
openvpn: '<svg class="vpn-type-logo vpn-logo-ovpn" viewBox="0 0 24 24" width="18" height="18" style="vertical-align:middle;flex-shrink:0" fill="#EA580C"><path d="M12 .357C5.385.357 0 5.69 0 12.254c0 4.36 2.358 8.153 5.896 10.204l.77-5.076a7.046 7.046 0 01-1.846-4.719c0-3.897 3.18-7.076 7.13-7.076 3.948 0 7.126 3.18 7.126 7.076 0 1.847-.717 3.488-1.846 4.77L18 22.51c3.59-2.05 6-5.899 6-10.258C24 5.69 18.615.357 12 .357zm-.05 8.157a3.786 3.786 0 00-3.796 3.795 3.738 3.738 0 002.461 3.54L9.13 23.643h5.64l-1.435-7.795c1.385-.564 2.41-1.898 2.41-3.54a3.786 3.786 0 00-3.795-3.794z"/></svg>'
|
||
};
|
||
|
||
function getVpnTypeBadgeHtml(type, showLabel = true) {
|
||
const isWg = (type === 'wireguard');
|
||
const logo = isWg ? VPN_LOGOS.wireguard : VPN_LOGOS.openvpn;
|
||
const label = isWg ? 'WireGuard' : 'OpenVPN';
|
||
const badgeClass = isWg ? 'badge-vpn-wg' : 'badge-vpn-ovpn';
|
||
if (!showLabel) {
|
||
return `<span class="vpn-badge-mini ${badgeClass}" title="${t('vpn_protocol_label', 'Protocole :')} ${label}" style="display:inline-flex;align-items:center">${logo}</span>`;
|
||
}
|
||
return `<span class="vpn-badge-full ${badgeClass}" style="display:inline-flex;align-items:center;gap:6px;padding:3px 8px;border-radius:6px;font-size:12px;font-weight:700">` +
|
||
`${logo}<span>${label}</span>` +
|
||
`</span>`;
|
||
}
|
||
|
||
let capturePolling = false;
|
||
async function pollCaptureData() {
|
||
if (capturePolling) return;
|
||
if (currentTab !== 'advanced' || currentAdvSubTab !== 'pcap') return;
|
||
capturePolling = true;
|
||
try {
|
||
await loadCaptureStatus();
|
||
await loadCapturePackets();
|
||
} catch (e) {
|
||
console.error('Erreur actualisation flux capture:', e);
|
||
} finally {
|
||
capturePolling = false;
|
||
}
|
||
}
|
||
|
||
function ensureCapturePolling() {
|
||
if (typeof capturePollTimer !== 'undefined' && capturePollTimer) {
|
||
clearInterval(capturePollTimer);
|
||
capturePollTimer = null;
|
||
}
|
||
capturePollTimer = setInterval(() => {
|
||
if (currentTab === 'advanced' && currentAdvSubTab === 'pcap') {
|
||
pollCaptureData();
|
||
}
|
||
}, 1500);
|
||
}
|
||
|
||
async function loadCapturePackets(force = false) {
|
||
try {
|
||
const lastExistingId = capturePackets.length ? capturePackets[capturePackets.length - 1].id : 0;
|
||
const url = lastExistingId > 0
|
||
? `/api/advanced/capture/packets?since=${lastExistingId}&limit=2000`
|
||
: `/api/advanced/capture/packets?limit=50000`;
|
||
const r = await apiFetch(url, { cache: 'no-store' });
|
||
if (!r.ok) {
|
||
console.warn('Erreur API capture paquets HTTP', r.status);
|
||
return;
|
||
}
|
||
const data = await r.json();
|
||
const pkts = Array.isArray(data) ? data : (data.packets || []);
|
||
const totCount = data.total_packets !== undefined ? data.total_packets : (data.total_captured || 0);
|
||
|
||
let isNew = false;
|
||
if (totCount === 0 && capturePackets.length > 0) {
|
||
capturePackets = [];
|
||
isNew = true;
|
||
} else if (lastExistingId > 0) {
|
||
if (pkts.length > 0) {
|
||
if (pkts[0].id === 1 && lastExistingId > 1) {
|
||
// La capture a été réinitialisée côté serveur
|
||
capturePackets = pkts;
|
||
isNew = true;
|
||
} else {
|
||
const existingIds = new Set(capturePackets.map(p => p.id));
|
||
for (const p of pkts) {
|
||
if (!existingIds.has(p.id)) {
|
||
capturePackets.push(p);
|
||
existingIds.add(p.id);
|
||
isNew = true;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} else {
|
||
if (pkts.length > 0 || capturePackets.length !== pkts.length) {
|
||
capturePackets = pkts;
|
||
isNew = true;
|
||
}
|
||
}
|
||
|
||
const tbody = $('capturePacketsBody');
|
||
const tableEmpty = !tbody || !tbody.children.length || !!tbody.querySelector('.empty');
|
||
|
||
if (isNew || force || tableEmpty || !capturePackets.length) {
|
||
if (isNew && $('autoScrollCheck') && $('autoScrollCheck').checked) { capturePage = 1; }
|
||
renderCaptureTable();
|
||
if ($('captureBufferSize')) {
|
||
const keptWord = capturePackets.length > 1 ? t('packets_kept_plural', 'paquets conservés') : t('packets_kept_singular', 'paquet conservé');
|
||
$('captureBufferSize').textContent = capturePackets.length + ' ' + keptWord;
|
||
}
|
||
}
|
||
} catch (err) {
|
||
console.error('loadCapturePackets erreur:', err);
|
||
}
|
||
}
|
||
|
||
function renderCaptureTable() {
|
||
const tbody = $('capturePacketsBody'); if (!tbody) return;
|
||
const list = Array.isArray(capturePackets) ? capturePackets : [];
|
||
const q = (captureFilter || '').trim().toLowerCase();
|
||
const filtered = q ? list.filter(p => {
|
||
if (q === 'domain:' || q === 'domain' || q === 'domaines') return !!p.domain;
|
||
const srcGeoCode = (p.src_geo && p.src_geo.code) ? String(p.src_geo.code).toLowerCase() : '';
|
||
const dstGeoCode = (p.dst_geo && p.dst_geo.code) ? String(p.dst_geo.code).toLowerCase() : '';
|
||
const srcGeoCountry = (p.src_geo && p.src_geo.country) ? String(p.src_geo.country).toLowerCase() : '';
|
||
const dstGeoCountry = (p.dst_geo && p.dst_geo.country) ? String(p.dst_geo.country).toLowerCase() : '';
|
||
return (p.proto && p.proto.toLowerCase().includes(q)) ||
|
||
(p.src && p.src.toLowerCase().includes(q)) ||
|
||
(p.dst && p.dst.toLowerCase().includes(q)) ||
|
||
(p.domain && p.domain.toLowerCase().includes(q)) ||
|
||
(p.info && p.info.toLowerCase().includes(q)) ||
|
||
(p.details && p.details.toLowerCase().includes(q)) ||
|
||
srcGeoCode.includes(q) || dstGeoCode.includes(q) ||
|
||
srcGeoCountry.includes(q) || dstGeoCountry.includes(q);
|
||
}) : list;
|
||
|
||
const count = filtered.length;
|
||
const isEn = typeof currentLanguage !== 'undefined' && currentLanguage.startsWith('en');
|
||
const pktWord = count > 1 ? t('packets_count_plural', 'paquets') : t('packets_count_singular', 'paquet');
|
||
if ($('packetFilterCount')) $('packetFilterCount').textContent = count + ' ' + pktWord;
|
||
|
||
if (!count) {
|
||
const emptyMsg = q
|
||
? t('no_packets_match', 'Aucun paquet ne correspond au filtre "{filter}"').replace('{filter}', escHtml(q))
|
||
: t('no_packets_captured', 'Aucun paquet capturé. Cliquez sur « Démarrer » pour lancer l’analyse Wireshark.');
|
||
tbody.innerHTML = '<tr><td colspan="8" class="empty">' + emptyMsg + '</td></tr>';
|
||
renderPagination('capturePagination', 1, 0, 'changeCapturePage', 10);
|
||
return;
|
||
}
|
||
|
||
const totalPages = Math.max(1, Math.ceil(count / 10));
|
||
if (capturePage > totalPages) capturePage = totalPages; if (capturePage < 1) capturePage = 1;
|
||
const rev = [...filtered].reverse();
|
||
const paged = rev.slice((capturePage - 1) * 10, capturePage * 10);
|
||
|
||
tbody.innerHTML = paged.map(c => {
|
||
const pLow = (c.proto || 'other').toLowerCase();
|
||
const protoClass = 'proto-' + (pLow === 'mdns' ? 'mdns' : ['dns', 'icmp', 'tcp', 'udp', 'arp', 'dhcp', 'tls', 'http'].includes(pLow) ? pLow : 'other');
|
||
const infoEsc = escHtml(c.info || '');
|
||
const domEsc = c.domain ? escHtml(c.domain) : '';
|
||
const domCell = c.domain ? `<strong class="domain-filter-tag" data-domain="${domEsc}" style="font-family:monospace;font-size:12px;color:var(--blue);cursor:pointer;white-space:nowrap" title="${t('adv_pcap_filter_domain_tooltip', 'Filtrer sur ce domaine')}">🌐 ${domEsc}</strong>` : `<span style="color:var(--muted)">—</span>`;
|
||
const srcHtml = formatIpWithGeo(c.src, c.src_geo, c.src_mac);
|
||
const dstHtml = formatIpWithGeo(c.dst, c.dst_geo, c.dst_mac);
|
||
return `<tr class="packet-row" data-id="${c.id}">` +
|
||
`<td><code style="color:var(--muted)">#${c.id}</code></td>` +
|
||
`<td><code style="font-size:12px">${escHtml(c.time || '')}</code></td>` +
|
||
`<td>${srcHtml}</td>` +
|
||
`<td>${dstHtml}</td>` +
|
||
`<td><span class="proto-badge ${protoClass}">${escHtml(c.proto || 'ETH')}</span></td>` +
|
||
`<td>${domCell}</td>` +
|
||
`<td style="font-size:12px">${c.len || 0} B</td>` +
|
||
`<td style="font-family:monospace;font-size:12px;color:var(--text);max-width:320px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${infoEsc}">${infoEsc}</td>` +
|
||
`</tr>`;
|
||
}).join('');
|
||
|
||
if (!tbody._hasClickDelegated) {
|
||
tbody._hasClickDelegated = true;
|
||
tbody.onclick = function (e) {
|
||
const domTag = e.target.closest('.domain-filter-tag');
|
||
if (domTag) {
|
||
e.stopPropagation();
|
||
setPacketFilter(domTag.getAttribute('data-domain'));
|
||
return;
|
||
}
|
||
const countryTag = e.target.closest('.country-filter-tag');
|
||
if (countryTag) {
|
||
e.stopPropagation();
|
||
const c = countryTag.getAttribute('data-country');
|
||
if (c && c !== 'LAN' && c !== 'WAN') {
|
||
setPacketFilter(c);
|
||
return;
|
||
}
|
||
}
|
||
const row = e.target.closest('.packet-row');
|
||
if (row && row.getAttribute('data-id')) {
|
||
showPacketModal(parseInt(row.getAttribute('data-id'), 10));
|
||
}
|
||
};
|
||
}
|
||
|
||
renderPagination('capturePagination', capturePage, count, 'changeCapturePage', 10);
|
||
}
|
||
|
||
window.changeCapturePage = (p) => {
|
||
capturePage = p;
|
||
if (p > 1 && $('autoScrollCheck')) $('autoScrollCheck').checked = false;
|
||
renderCaptureTable();
|
||
};
|
||
window.setPacketFilter = (dom) => {
|
||
if ($('packetFilterInput')) {
|
||
$('packetFilterInput').value = dom;
|
||
captureFilter = dom.toLowerCase();
|
||
capturePage = 1;
|
||
document.querySelectorAll('.filter-chip').forEach(c => c.classList.remove('active'));
|
||
renderCaptureTable();
|
||
$('packetFilterInput').scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||
}
|
||
};
|
||
|
||
function showPacketModal(id) {
|
||
const p = capturePackets.find(x => x.id === id); if (!p) return;
|
||
const isEn = typeof currentLanguage !== 'undefined' && currentLanguage.startsWith('en');
|
||
$('modalPacketNum').textContent = p.id;
|
||
$('modalPacketProto').textContent = p.proto || '—';
|
||
$('modalPacketSrc').innerHTML = formatIpWithGeo(p.src, p.src_geo, p.src_mac);
|
||
$('modalPacketDst').innerHTML = formatIpWithGeo(p.dst, p.dst_geo, p.dst_mac);
|
||
$('modalPacketTime').textContent = p.time || '';
|
||
$('modalPacketLen').textContent = (p.len || 0) + ' ' + (isEn ? 'bytes' : 'octets');
|
||
$('modalPacketDetails').textContent = p.details || p.info || '';
|
||
$('modalPacketHex').textContent = p.hexdump || '';
|
||
$('packetModal').classList.add('active');
|
||
}
|
||
function hidePacketModal() { $('packetModal').classList.remove('active') }
|
||
|
||
function selectTab(tab) {
|
||
if (!status.configured) return;
|
||
currentTab = tab; sessionStorage.setItem('apDashboardTab', tab);
|
||
const dashboard = tab === 'dashboard', stats = tab === 'stats', devices = tab === 'devices', advanced = tab === 'advanced', settings = tab === 'settings', logs = tab === 'logs', blocked = tab === 'blocked';
|
||
if ($('dashboardView')) $('dashboardView').classList.toggle('active', dashboard);
|
||
if ($('statsView')) $('statsView').classList.toggle('active', stats);
|
||
if ($('devicesView')) $('devicesView').classList.toggle('active', devices);
|
||
if ($('advancedView')) $('advancedView').classList.toggle('active', advanced);
|
||
if ($('settingsView')) $('settingsView').classList.toggle('active', settings);
|
||
if ($('logsView')) $('logsView').classList.toggle('active', logs);
|
||
if ($('blockedView')) $('blockedView').classList.toggle('active', blocked);
|
||
if ($('dashboardTab')) { $('dashboardTab').classList.toggle('active', dashboard); $('dashboardTab').setAttribute('aria-selected', dashboard); }
|
||
if ($('statsTab')) { $('statsTab').classList.toggle('active', stats); $('statsTab').setAttribute('aria-selected', stats); }
|
||
if ($('devicesTab')) { $('devicesTab').classList.toggle('active', devices); $('devicesTab').setAttribute('aria-selected', devices); }
|
||
if ($('advancedTab')) { $('advancedTab').classList.toggle('active', advanced); $('advancedTab').setAttribute('aria-selected', advanced); }
|
||
if ($('settingsTab')) { $('settingsTab').classList.toggle('active', settings); $('settingsTab').setAttribute('aria-selected', settings); }
|
||
if ($('logsTab')) { $('logsTab').classList.toggle('active', logs); $('logsTab').setAttribute('aria-selected', logs); }
|
||
if ($('blockedTab')) { $('blockedTab').classList.toggle('active', blocked); $('blockedTab').setAttribute('aria-selected', blocked); }
|
||
if (stats) { selectStatsSubTab(currentStatsSubTab || 'metrics'); }
|
||
if (devices) { loadDevices(); }
|
||
if (advanced) {
|
||
if (typeof selectAdvSubTab === 'function') selectAdvSubTab(currentAdvSubTab || 'vpn');
|
||
if (currentAdvSubTab === 'pcap') { ensureCapturePolling(); }
|
||
} else {
|
||
if (typeof capturePollTimer !== 'undefined' && capturePollTimer) { clearInterval(capturePollTimer); capturePollTimer = null; }
|
||
stopCaptureTimer();
|
||
}
|
||
if (logs) loadLogs();
|
||
if (blocked) loadBlocked();
|
||
if (settings) { selectSettingsTab(currentSettingsTab || 'wifi'); load2fa(); if ((currentSettingsTab || 'wifi') === 'admin') { if (typeof loadAdminUser === 'function') loadAdminUser(); if (typeof loadSessions === 'function') loadSessions(); if (typeof loadPasskeysList === 'function') loadPasskeysList(); } }
|
||
}
|
||
|
||
if ($('dashboardTab')) $('dashboardTab').onclick = () => selectTab('dashboard');
|
||
if ($('statsTab')) $('statsTab').onclick = () => selectTab('stats');
|
||
if ($('devicesTab')) $('devicesTab').onclick = () => selectTab('devices');
|
||
if ($('advancedTab')) $('advancedTab').onclick = () => selectTab('advanced');
|
||
if ($('settingsTab')) $('settingsTab').onclick = () => selectTab('settings');
|
||
if ($('logsTab')) $('logsTab').onclick = () => selectTab('logs');
|
||
if ($('blockedTab')) $('blockedTab').onclick = () => selectTab('blocked');
|
||
if ($('refreshStats')) $('refreshStats').onclick = () => runAction(loadStats);
|
||
if ($('refreshLogs')) $('refreshLogs').onclick = () => runAction(loadLogs);
|
||
if ($('refreshBlocked')) $('refreshBlocked').onclick = () => runAction(loadBlocked);
|
||
$('statsRangeDay').onclick = () => setStatsRange('day');
|
||
$('statsRangeWeek').onclick = () => setStatsRange('week');
|
||
$('statsRangeMonth').onclick = () => setStatsRange('month');
|
||
$('statsRangeYear').onclick = () => setStatsRange('year');
|
||
|
||
$('startCaptureBtn').onclick = () => runAction(async () => {
|
||
captureStartTime = Date.now() / 1000;
|
||
captureRunning = true;
|
||
ensureCaptureTimer();
|
||
updateCaptureTimerDisplay();
|
||
await apiFetch('/api/advanced/capture/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
|
||
await loadCaptureStatus();
|
||
await loadCapturePackets(true);
|
||
ensureCapturePolling();
|
||
});
|
||
$('stopCaptureBtn').onclick = () => runAction(async () => {
|
||
stopCaptureTimer();
|
||
captureStartTime = null;
|
||
if ($('captureStatusBadge')) {
|
||
$('captureStatusBadge').textContent = '○ ' + t('adv_pcap_status_stopping', 'Arrêt...');
|
||
}
|
||
await apiFetch('/api/advanced/capture/stop', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
|
||
await loadCaptureStatus();
|
||
await loadCapturePackets(true);
|
||
});
|
||
$('clearCaptureBtn').onclick = () => runAction(async () => {
|
||
if (!confirm(t('adv_pcap_confirm_clear', 'Effacer tous les paquets capturés ?'))) return;
|
||
await apiFetch('/api/advanced/capture/clear', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
|
||
capturePackets = []; capturePage = 1;
|
||
await loadCaptureStatus(); renderCaptureTable();
|
||
});
|
||
$('exportPcapBtn').onclick = () => {
|
||
const tokenParam = authToken ? ('?token=' + encodeURIComponent(authToken)) : '';
|
||
const url = API_URL + '/api/advanced/capture/export' + tokenParam;
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = 'capture_wireshark_' + new Date().toISOString().replace(/[:.]/g, '-') + '.pcap';
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
};
|
||
$('exportCsvBtn').onclick = () => {
|
||
if (!capturePackets.length) { alert(t('adv_pcap_no_packets_export', 'Aucun paquet à exporter')); return; }
|
||
const isEn = typeof currentLanguage !== 'undefined' && currentLanguage.startsWith('en');
|
||
const header = isEn
|
||
? "NO,TIME,SOURCE,DESTINATION,PROTOCOL,SIZE_BYTES,INFO\r\n"
|
||
: "N°,HEURE,SOURCE,DESTINATION,PROTOCOLE,TAILLE_OCTETS,INFO\r\n";
|
||
let csv = header;
|
||
capturePackets.forEach(p => {
|
||
const line = [p.id, p.time, `"${p.src}"`, `"${p.dst}"`, p.proto, p.len, `"${(p.info || '').replace(/"/g, '""')}"`];
|
||
csv += line.join(',') + "\r\n";
|
||
});
|
||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = 'capture_wireshark_' + new Date().toISOString().replace(/[:.]/g, '-') + '.csv';
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
URL.revokeObjectURL(url);
|
||
};
|
||
$('packetFilterInput').oninput = function () {
|
||
captureFilter = this.value.trim().toLowerCase();
|
||
capturePage = 1;
|
||
document.querySelectorAll('.filter-chip').forEach(c => c.classList.remove('active'));
|
||
renderCaptureTable();
|
||
};
|
||
$('clearFilterBtn').onclick = function () {
|
||
$('packetFilterInput').value = '';
|
||
captureFilter = '';
|
||
capturePage = 1;
|
||
document.querySelectorAll('.filter-chip').forEach(c => c.classList.remove('active'));
|
||
const allChip = document.querySelector('.filter-chip[data-filter=""]');
|
||
if (allChip) allChip.classList.add('active');
|
||
renderCaptureTable();
|
||
};
|
||
document.querySelectorAll('.filter-chip').forEach(chip => {
|
||
chip.onclick = function () {
|
||
document.querySelectorAll('.filter-chip').forEach(c => c.classList.remove('active'));
|
||
this.classList.add('active');
|
||
const f = this.getAttribute('data-filter') || '';
|
||
$('packetFilterInput').value = f;
|
||
captureFilter = f.toLowerCase();
|
||
capturePage = 1;
|
||
renderCaptureTable();
|
||
};
|
||
});
|
||
$('closePacketModal').onclick = hidePacketModal;
|
||
$('closePacketModalBtn').onclick = hidePacketModal;
|
||
$('packetModal').onclick = (e) => { if (e.target === $('packetModal')) hidePacketModal() };
|
||
|
||
window.addEventListener('resize', () => {
|
||
if (currentTab === 'stats' && currentStatsSubTab === 'topology') drawTopologySvgLines();
|
||
if (!window.Chart && currentTab === 'stats' && statsDataCache) {
|
||
const sb = $('statsSvgFallback');
|
||
if (sb) renderSvgStatsChart(sb, currentStatsRange === 'day' ? (statsDataCache.hours || []) : (statsDataCache[currentStatsRange + 's'] || []), (document.documentElement.dataset.theme === 'light' || document.documentElement.dataset.theme === 'winxp' || (document.documentElement.dataset.theme === 'macos' && (typeof themeMedia !== 'undefined' ? themeMedia.matches : true))), currentStatsRange === 'day');
|
||
}
|
||
});
|
||
|
||
$('clearLogs').onclick = () => runAction(async () => { if (!confirm('Supprimer tous les journaux ?')) return; const response = await apiFetch('/api/logs/clear', { method: 'POST' }); if (response.ok) { logsPage = 1; await loadLogs() } });
|
||
|
||
/* ============================================================
|
||
Sauvegarde & Restauration (Export / Import)
|
||
============================================================ */
|
||
let pendingBackupData = null;
|
||
|
||
async function exportBackup() {
|
||
const msg = $('backupActionMsg');
|
||
const btn = $('btnExportBackup');
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||
msg.style.color = 'var(--blue)';
|
||
msg.textContent = 'Génération de l’archive de sauvegarde (configuration & base de données) en cours…';
|
||
}
|
||
if (btn) btn.disabled = true;
|
||
|
||
try {
|
||
const res = await apiFetch('/api/backup/export?format=zip');
|
||
if (!res.ok) {
|
||
let errText = 'Erreur lors du téléchargement';
|
||
try { const d = await res.json(); if (d.error) errText = d.error; } catch (_) { }
|
||
throw new Error(errText);
|
||
}
|
||
const blob = await res.blob();
|
||
const now = new Date();
|
||
const pad = n => String(n).padStart(2, '0');
|
||
const dateStr = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
||
const filename = `ap-manageur-sauvegarde-${dateStr}.zip`;
|
||
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = filename;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
setTimeout(() => URL.revokeObjectURL(url), 2000);
|
||
|
||
if (msg) {
|
||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||
msg.style.color = 'var(--green)';
|
||
msg.textContent = t('backup_downloaded_success', '✓ Sauvegarde complète téléchargée ({size} Ko) ! Contient la configuration JSON et la base SQLite brute.').replace('{size}', (blob.size / 1024).toFixed(1));
|
||
setTimeout(() => { if (msg) msg.style.display = 'none'; }, 6000);
|
||
}
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = t('backup_export_err', 'Erreur exportation : ') + tErr(e.message);
|
||
}
|
||
} finally {
|
||
if (btn) btn.disabled = false;
|
||
}
|
||
}
|
||
|
||
function triggerImportBackup() {
|
||
const inp = $('backupFileInput');
|
||
if (inp) {
|
||
inp.value = '';
|
||
inp.click();
|
||
}
|
||
}
|
||
|
||
async function handleBackupFileSelected(event) {
|
||
const file = event.target.files && event.target.files[0];
|
||
if (!file) return;
|
||
|
||
const msg = $('backupActionMsg');
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||
msg.style.color = 'var(--blue)';
|
||
msg.textContent = `Inspection du fichier « ${file.name} » en cours…`;
|
||
}
|
||
|
||
// Cas 1 : Fichier texte JSON classique
|
||
if (file.name.toLowerCase().endsWith('.json')) {
|
||
const reader = new FileReader();
|
||
reader.onload = (e) => {
|
||
try {
|
||
const text = e.target.result;
|
||
const data = JSON.parse(text);
|
||
|
||
const isBackup = data && (data.ap_manageur_backup || data.preferences || data.vpn_profiles || data.client_names);
|
||
if (!isBackup) {
|
||
alert(t('backup_invalid_file', "Le fichier sélectionné ne semble pas être une sauvegarde valide d'AP Manageur (clés de sauvegarde introuvables)."));
|
||
if (msg) msg.style.display = 'none';
|
||
return;
|
||
}
|
||
|
||
if (msg) msg.style.display = 'none';
|
||
pendingBackupData = data;
|
||
showImportBackupModal(file.name, data);
|
||
} catch (err) {
|
||
alert(t('backup_json_read_err', "Erreur lors de la lecture du fichier JSON : ") + tErr(err.message));
|
||
if (msg) msg.style.display = 'none';
|
||
}
|
||
};
|
||
reader.onerror = () => {
|
||
alert(t('backup_read_file_err', "Impossible de lire le fichier sélectionné."));
|
||
if (msg) msg.style.display = 'none';
|
||
};
|
||
reader.readAsText(file);
|
||
return;
|
||
}
|
||
|
||
// Cas 2 : Archive ZIP ou SQLite binaire : inspection via l'API backend
|
||
const reader = new FileReader();
|
||
reader.onload = async (e) => {
|
||
try {
|
||
const dataUrl = e.target.result;
|
||
const b64 = dataUrl.split(',')[1];
|
||
const res = await apiFetch('/api/backup/inspect', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
filename: file.name,
|
||
data_base64: b64
|
||
})
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || "Impossible d'analyser le fichier de sauvegarde");
|
||
if (msg) msg.style.display = 'none';
|
||
pendingBackupData = d.backup;
|
||
showImportBackupModal(file.name, d.backup);
|
||
} catch (err) {
|
||
alert(t('backup_parse_err', "Erreur d'analyse de la sauvegarde : ") + tErr(err.message));
|
||
if (msg) msg.style.display = 'none';
|
||
}
|
||
};
|
||
reader.onerror = () => {
|
||
alert(t('backup_read_file_err', "Impossible de lire le fichier sélectionné."));
|
||
if (msg) msg.style.display = 'none';
|
||
};
|
||
reader.readAsDataURL(file);
|
||
}
|
||
|
||
function showImportBackupModal(fileName, data) {
|
||
const modal = $('modalImportBackup');
|
||
if (!modal) return;
|
||
|
||
if ($('importFileName')) $('importFileName').textContent = fileName;
|
||
const meta = data.ap_manageur_backup || {};
|
||
if ($('importFileVersion')) $('importFileVersion').textContent = meta.app_version || 'Inconnue';
|
||
if ($('importFileMeta')) {
|
||
const dateFormatted = meta.exported_at ? new Date(meta.exported_at).toLocaleString() : 'Non précisée';
|
||
$('importFileMeta').textContent = `Date de sauvegarde : ${dateFormatted} • Système : ${meta.app_name || 'AP Manageur'}`;
|
||
}
|
||
|
||
const pillsEl = $('importSummaryPills');
|
||
if (pillsEl) {
|
||
const vpnCount = Array.isArray(data.vpn_profiles) ? data.vpn_profiles.length : 0;
|
||
const devCount = Array.isArray(data.client_names) ? data.client_names.length : 0;
|
||
const catCount = Array.isArray(data.custom_device_types) ? data.custom_device_types.length : 0;
|
||
const blockCount = Array.isArray(data.blocked_clients) ? data.blocked_clients.length : 0;
|
||
const prefCount = (data.preferences && typeof data.preferences === 'object') ? Object.keys(data.preferences).length : 0;
|
||
const authCount = Array.isArray(data.auth_users) ? data.auth_users.length : 0;
|
||
|
||
pillsEl.innerHTML = `
|
||
<span class="pill pill-blue" style="font-size:11px">🌐 ${vpnCount} Profil(s) VPN</span>
|
||
<span class="pill pill-green" style="font-size:11px">📱 ${devCount} Appareil(s)</span>
|
||
<span class="pill" style="background:var(--panel);color:var(--text);border:1px solid var(--line);font-size:11px">🎨 ${catCount} Catégorie(s)</span>
|
||
<span class="pill" style="background:rgba(239,68,68,0.15);color:var(--red);border:1px solid rgba(239,68,68,0.3);font-size:11px">🚫 ${blockCount} Bloqué(s)</span>
|
||
<span class="pill" style="background:var(--panel);color:var(--muted);border:1px solid var(--line);font-size:11px">⚙️ ${prefCount} Paramètre(s)</span>
|
||
${authCount ? `<span class="pill" style="background:rgba(245,158,11,0.15);color:#d97706;border:1px solid rgba(245,158,11,0.3);font-size:11px">🔐 ${authCount} Compte(s)</span>` : ''}
|
||
`;
|
||
}
|
||
|
||
if ($('importModalMsg')) $('importModalMsg').style.display = 'none';
|
||
if ($('chkRestoreAuth')) $('chkRestoreAuth').checked = false;
|
||
modal.style.display = 'flex';
|
||
}
|
||
|
||
function closeImportBackupModal() {
|
||
const modal = $('modalImportBackup');
|
||
if (modal) modal.style.display = 'none';
|
||
pendingBackupData = null;
|
||
}
|
||
|
||
async function submitImportBackup() {
|
||
if (!pendingBackupData) {
|
||
alert(t('backup_no_pending', "Aucune donnée de sauvegarde en attente."));
|
||
return;
|
||
}
|
||
const btn = $('btnConfirmImportAction');
|
||
const msg = $('importModalMsg');
|
||
const mainMsg = $('backupActionMsg');
|
||
|
||
const options = {
|
||
restore_vpn: $('chkRestoreVpn') ? $('chkRestoreVpn').checked : true,
|
||
restore_devices: $('chkRestoreDevices') ? $('chkRestoreDevices').checked : true,
|
||
restore_blocked: $('chkRestoreBlocked') ? $('chkRestoreBlocked').checked : true,
|
||
restore_categories: $('chkRestoreCategories') ? $('chkRestoreCategories').checked : true,
|
||
restore_preferences: $('chkRestorePrefs') ? $('chkRestorePrefs').checked : true,
|
||
restore_auth: $('chkRestoreAuth') ? $('chkRestoreAuth').checked : false
|
||
};
|
||
|
||
if (!options.restore_vpn && !options.restore_devices && !options.restore_blocked && !options.restore_categories && !options.restore_preferences && !options.restore_auth) {
|
||
alert(t('backup_select_one_category', "Veuillez cocher au moins une catégorie d'éléments à restaurer."));
|
||
return;
|
||
}
|
||
|
||
if (options.restore_auth && !confirm(t('backup_confirm_restore_auth', "⚠️ ATTENTION : Vous avez choisi de restaurer le compte administrateur. Cela écrasera les identifiants, mots de passe et clés passkeys actuels. Voulez-vous continuer ?"))) {
|
||
return;
|
||
}
|
||
|
||
if (btn) { btn.disabled = true; btn.textContent = t('backup_restoring', 'Restauration en cours…'); }
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||
msg.style.color = 'var(--blue)';
|
||
msg.textContent = t('backup_applying_to_db', 'Application de la sauvegarde dans la base de données…');
|
||
}
|
||
|
||
try {
|
||
const res = await apiFetch('/api/backup/import', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
backup: pendingBackupData,
|
||
options: options
|
||
})
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur lors de la restauration');
|
||
|
||
closeImportBackupModal();
|
||
|
||
if (mainMsg) {
|
||
mainMsg.style.display = 'block';
|
||
mainMsg.style.background = 'rgba(50,213,131,0.15)';
|
||
mainMsg.style.color = 'var(--green)';
|
||
mainMsg.textContent = '✓ ' + tMsg(d.message || 'Sauvegarde restaurée avec succès !');
|
||
setTimeout(() => { if (mainMsg) mainMsg.style.display = 'none'; }, 8000);
|
||
}
|
||
|
||
// Rafraîchir les données
|
||
try { await load(); } catch (_) { }
|
||
try { if (typeof loadVpnProfiles === 'function') await loadVpnProfiles(); } catch (_) { }
|
||
try { if (typeof loadDevices === 'function') await loadDevices(); } catch (_) { }
|
||
try { if (typeof loadDeviceTypesList === 'function') await loadDeviceTypesList(); } catch (_) { }
|
||
try { if (typeof loadBlocked === 'function') await loadBlocked(); } catch (_) { }
|
||
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(239,68,68,0.15)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = tErr(e.message);
|
||
}
|
||
} finally {
|
||
if (btn) { btn.disabled = false; btn.textContent = 'Confirmer et restaurer'; }
|
||
}
|
||
}
|
||
|
||
/* ============================================================
|
||
Onglet Sauvegardes : Planification Cron & Gestion des fichiers
|
||
============================================================ */
|
||
let serverBackupsCache = [];
|
||
let serverBackupsTotalSize = '0 o';
|
||
|
||
function initBackupCronSelects() {
|
||
const hSel = $('backupCronHour');
|
||
const mSel = $('backupCronMinute');
|
||
if (hSel && hSel.options.length <= 1) {
|
||
let hHtml = '<option value="*">' + t('stats_cron_day_all', 'Toutes les heures (*)') + '</option>';
|
||
for (let i = 0; i < 24; i++) {
|
||
const v = String(i).padStart(2, '0');
|
||
hHtml += `<option value="${i}"${i === 3 ? ' selected' : ''}>${v}h (${v}:00)</option>`;
|
||
}
|
||
hSel.innerHTML = hHtml;
|
||
}
|
||
if (mSel && mSel.options.length <= 1) {
|
||
let mHtml = '';
|
||
for (let i = 0; i < 60; i++) {
|
||
const v = String(i).padStart(2, '0');
|
||
mHtml += `<option value="${i}"${i === 0 ? ' selected' : ''}>${v} min (:${v})</option>`;
|
||
}
|
||
mSel.innerHTML = mHtml;
|
||
}
|
||
}
|
||
|
||
async function onBackupCronToggle(fromUserClick = false) {
|
||
const en = !!($('backupCronEnabled') && $('backupCronEnabled').checked);
|
||
const body = $('backupCronBody');
|
||
if (body) {
|
||
body.style.display = en ? 'block' : 'none';
|
||
}
|
||
if (en) {
|
||
initBackupCronSelects();
|
||
updateBackupCronSummary();
|
||
}
|
||
if (fromUserClick && !en) {
|
||
await saveBackupSchedule(true);
|
||
}
|
||
}
|
||
|
||
function syncBackupCronFromSelects() {
|
||
const d = $('backupCronDay')?.value || '*';
|
||
const h = $('backupCronHour')?.value ?? '3';
|
||
const m = $('backupCronMinute')?.value ?? '0';
|
||
const expr = `${m} ${h} * * ${d}`;
|
||
if ($('backupCronExpr')) $('backupCronExpr').value = expr;
|
||
updateBackupCronSummary();
|
||
}
|
||
|
||
function applyBackupCronPreset(expr, day, hour, minute) {
|
||
initBackupCronSelects();
|
||
if ($('backupCronEnabled')) $('backupCronEnabled').checked = true;
|
||
if ($('backupCronDay')) $('backupCronDay').value = String(day);
|
||
if ($('backupCronHour')) $('backupCronHour').value = String(hour);
|
||
if ($('backupCronMinute')) $('backupCronMinute').value = String(minute);
|
||
if ($('backupCronExpr')) $('backupCronExpr').value = expr;
|
||
onBackupCronToggle();
|
||
}
|
||
|
||
function updateBackupCronSummary() {
|
||
const badge = $('backupCronHuman');
|
||
if (!badge) return;
|
||
const expr = ($('backupCronExpr')?.value || '').trim();
|
||
const parts = expr.split(/\s+/);
|
||
if (parts.length !== 5) {
|
||
badge.textContent = '⚠️ ' + t('backup_cron_invalid', 'Expression Cron invalide (5 champs requis)');
|
||
return;
|
||
}
|
||
const [minPart, hourPart, domPart, monthPart, dowPart] = parts;
|
||
if (domPart !== '*' || monthPart !== '*' || hourPart.includes('/') || minPart.includes('/')) {
|
||
badge.textContent = '⚙️ Cron : ' + expr;
|
||
return;
|
||
}
|
||
const daysMap = {
|
||
'*': t('stats_cron_day_all_short', 'Tous les jours'),
|
||
'1-5': t('stats_cron_day_workdays_short', 'Jours ouvrés (Lun-Ven)'),
|
||
'6,7': t('stats_cron_day_weekend_short', 'Week-end (Sam-Dim)'),
|
||
'1': t('stats_cron_day_mon', 'Chaque Lundi'),
|
||
'2': t('stats_cron_day_tue', 'Chaque Mardi'),
|
||
'3': t('stats_cron_day_wed', 'Chaque Mercredi'),
|
||
'4': t('stats_cron_day_thu', 'Chaque Jeudi'),
|
||
'5': t('stats_cron_day_fri', 'Chaque Vendredi'),
|
||
'6': t('stats_cron_day_sat', 'Chaque Samedi'),
|
||
'0': t('stats_cron_day_sun', 'Chaque Dimanche'),
|
||
'7': t('stats_cron_day_sun', 'Chaque Dimanche')
|
||
};
|
||
const dStr = daysMap[dowPart] || (t('stats_cron_day_prefix', 'Jour ') + dowPart);
|
||
let timeStr = '';
|
||
if (hourPart === '*') {
|
||
timeStr = t('stats_cron_hourly_at', 'toutes les heures à :{min}').replace('{min}', String(minPart).padStart(2, '0'));
|
||
} else {
|
||
timeStr = t('stats_cron_at_time', 'à {time}').replace('{time}', `${String(hourPart).padStart(2, '0')}:${String(minPart).padStart(2, '0')}`);
|
||
}
|
||
badge.textContent = `📅 ${dStr} ${timeStr}`;
|
||
}
|
||
|
||
function renderServerBackupsTable(backups, totalSizeStr) {
|
||
serverBackupsCache = Array.isArray(backups) ? backups : [];
|
||
if (typeof totalSizeStr === 'string' && totalSizeStr) {
|
||
const cleanSize = totalSizeStr.replace(/^.*:\s*/, '').trim();
|
||
if (cleanSize) serverBackupsTotalSize = cleanSize;
|
||
}
|
||
const tbody = $('backupsTableBody');
|
||
const summary = $('backupsListSummary');
|
||
if (summary) {
|
||
summary.textContent = t('backup_list_summary', '{count} sauvegarde(s) • Espace utilisé : {size}')
|
||
.replace('{count}', String(serverBackupsCache.length))
|
||
.replace('{size}', serverBackupsTotalSize || '0 o');
|
||
}
|
||
if (!tbody) return;
|
||
if (!serverBackupsCache.length) {
|
||
tbody.innerHTML = `<tr><td colspan="5" class="empty">${escapeHtml(t('backup_list_empty', 'Aucune sauvegarde dans le dossier pour le moment.'))}</td></tr>`;
|
||
return;
|
||
}
|
||
const isRemoteEn = !!($('backupRemoteEnabled') && $('backupRemoteEnabled').checked);
|
||
const curProv = $('backupRemoteProvider')?.value || 'ftp';
|
||
const provIconHtml = (typeof getRemoteProviderIconHtml === 'function') ? getRemoteProviderIconHtml(curProv) : '☁️ ';
|
||
const provNames = {
|
||
gdrive: 'Google Drive',
|
||
dropbox: 'Dropbox',
|
||
sftp: 'SFTP',
|
||
ftp: 'FTP',
|
||
webdav: 'WebDAV',
|
||
s3: 'S3',
|
||
webhook: 'Webhook'
|
||
};
|
||
const curProvName = provNames[curProv] || curProv.toUpperCase();
|
||
|
||
tbody.innerHTML = serverBackupsCache.map(bk => {
|
||
const fname = bk.filename || '';
|
||
const safeArg = escapeHtml(fname).replace(/'/g, ''');
|
||
const isUploaded = !!bk.remote_uploaded;
|
||
const upProv = bk.remote_provider || curProv;
|
||
const upIconHtml = (typeof getRemoteProviderIconHtml === 'function') ? getRemoteProviderIconHtml(upProv) : provIconHtml;
|
||
const upProvName = provNames[upProv] || upProv.toUpperCase();
|
||
|
||
const typePill = bk.trigger === 'auto'
|
||
? `<span class="pill pill-green pill-no-dot" style="font-size:11px;padding:2px 8px">🤖 ${escapeHtml(t('backup_type_auto', 'Auto (Cron)'))}</span>`
|
||
: (bk.trigger === 'manual'
|
||
? `<span class="pill pill-blue pill-no-dot" style="font-size:11px;padding:2px 8px">👤 ${escapeHtml(t('backup_type_manual', 'Manuel'))}</span>`
|
||
: `<span class="pill pill-no-dot" style="font-size:11px;padding:2px 8px">📄 ${escapeHtml(t('backup_type_external', 'Externe'))}</span>`);
|
||
|
||
// Badge statut distant à côté du nom de fichier : coche verte et logo du service
|
||
const remoteBadge = (isRemoteEn && isUploaded)
|
||
? `<span class="pill pill-green pill-no-dot" style="font-size:10px;padding:2px 6px;margin-left:6px;display:inline-flex;align-items:center;gap:3px;vertical-align:middle" title="${escapeHtml(t('backup_remote_already_uploaded', 'Présent sur {prov}').replace('{prov}', upProvName))}${bk.remote_uploaded_at ? ' (' + escapeHtml(bk.remote_uploaded_at) + ')' : ''}"><span style="color:var(--green);font-weight:bold">✓</span> ${upIconHtml}<span>${escapeHtml(upProvName)}</span></span>`
|
||
: '';
|
||
|
||
// Bouton d'action Distant :
|
||
// - Si pas encore téléversé : affiche le logo du service distant (ex: GDrive, Dropbox, SFTP, FTP...)
|
||
// - Si déjà présent dessus : affiche une coche verte avec le logo du service distant !
|
||
let remoteBtnHtml = '';
|
||
if (isRemoteEn) {
|
||
if (isUploaded) {
|
||
remoteBtnHtml = `<button type="button" class="secondary" style="padding:5px 10px;font-size:12px;border-color:var(--green);color:var(--green);background:rgba(50,213,131,0.14);font-weight:600" onclick="uploadServerBackupToRemote('${safeArg}')" title="${escapeHtml(t('backup_btn_remote_synced_title', 'Déjà présent sur {prov} (cliquer pour renvoyer)').replace('{prov}', upProvName))}"><span style="color:var(--green);font-weight:bold;margin-right:4px">✓</span>${upIconHtml}${escapeHtml(t('backup_btn_remote_short', 'Distant'))}</button>`;
|
||
} else {
|
||
remoteBtnHtml = `<button type="button" class="secondary" style="padding:5px 10px;font-size:12px;border-color:var(--line);color:var(--text)" onclick="uploadServerBackupToRemote('${safeArg}')" title="${escapeHtml(t('backup_btn_remote_push_title', 'Envoyer vers {prov}').replace('{prov}', curProvName))}">${provIconHtml}${escapeHtml(t('backup_btn_remote_short', 'Distant'))}</button>`;
|
||
}
|
||
}
|
||
|
||
return `<tr>
|
||
<td style="font-family:monospace;font-size:12px;word-break:break-all"><strong>${escapeHtml(fname)}</strong>${remoteBadge}</td>
|
||
<td>${typePill}</td>
|
||
<td style="white-space:nowrap;font-size:12px" class="muted">${escapeHtml(bk.created_at || '—')}</td>
|
||
<td style="white-space:nowrap;font-size:12px">${escapeHtml(bk.size_str || '—')}</td>
|
||
<td style="text-align:right;white-space:nowrap">
|
||
<div style="display:inline-flex;gap:6px;flex-wrap:wrap;justify-content:flex-end">
|
||
<button type="button" class="secondary" style="padding:5px 10px;font-size:12px" onclick="downloadServerBackup('${safeArg}')" title="${escapeHtml(t('backup_btn_export', 'Exporter'))}">⬇️ ${escapeHtml(t('backup_btn_export', 'Exporter'))}</button>
|
||
${remoteBtnHtml}
|
||
<button type="button" class="secondary" style="padding:5px 10px;font-size:12px;border-color:var(--blue);color:var(--blue)" onclick="restoreServerBackup('${safeArg}')" title="${escapeHtml(t('backup_btn_restore', 'Restaurer'))}">♻️ ${escapeHtml(t('backup_btn_restore', 'Restaurer'))}</button>
|
||
<button type="button" class="secondary danger" style="padding:5px 10px;font-size:12px;border-color:rgba(239,68,68,0.45);color:var(--red)" onclick="deleteServerBackup('${safeArg}')" title="${escapeHtml(t('btn_delete', 'Supprimer'))}">🗑️</button>
|
||
</div>
|
||
</td>
|
||
</tr>`;
|
||
}).join('');
|
||
}
|
||
|
||
function applyBackupScheduleToUI(sched) {
|
||
if (!sched) return;
|
||
initBackupCronSelects();
|
||
if ($('backupCronEnabled')) $('backupCronEnabled').checked = !!sched.enabled;
|
||
if ($('backupCronDay') && sched.day !== undefined) $('backupCronDay').value = String(sched.day);
|
||
if ($('backupCronHour') && sched.hour !== undefined) $('backupCronHour').value = String(sched.hour);
|
||
if ($('backupCronMinute') && sched.minute !== undefined) $('backupCronMinute').value = String(sched.minute);
|
||
if ($('backupCronRetention') && sched.retention !== undefined) $('backupCronRetention').value = String(sched.retention);
|
||
if ($('backupCronExpr') && sched.cron_expr) $('backupCronExpr').value = sched.cron_expr;
|
||
if ($('backupCronLastRun')) {
|
||
$('backupCronLastRun').textContent = sched.last_run
|
||
? `${t('backup_last_run', 'Dernière exécution :')} ${sched.last_run}${sched.last_file ? ' (' + sched.last_file + ')' : ''}`
|
||
: t('backup_never_run', 'Aucune exécution enregistrée');
|
||
}
|
||
onBackupCronToggle();
|
||
}
|
||
|
||
async function refreshBackupsTab() {
|
||
const btn = $('btnRefreshBackups');
|
||
if (btn) {
|
||
btn.disabled = true;
|
||
btn.innerHTML = `<span class="spin">🔄</span> ${escapeHtml(t('backup_refreshing', 'Vérification…'))}`;
|
||
}
|
||
try {
|
||
await loadBackupsTab(true);
|
||
} finally {
|
||
if (btn) {
|
||
btn.disabled = false;
|
||
btn.innerHTML = `🔄 ${escapeHtml(t('btn_refresh', 'Actualiser'))}`;
|
||
}
|
||
}
|
||
}
|
||
|
||
async function loadBackupsTab(syncRemote = false) {
|
||
initBackupCronSelects();
|
||
try {
|
||
const url = syncRemote ? '/api/backups/list?sync_remote=1' : '/api/backups/list';
|
||
const res = await apiFetch(url, { cache: 'no-store' });
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur chargement sauvegardes');
|
||
if ($('backupDirBadge') && d.backup_dir) $('backupDirBadge').textContent = '📁 ' + d.backup_dir;
|
||
applyBackupScheduleToUI(d.schedule);
|
||
if (d.remote) applyBackupRemoteToUI(d.remote);
|
||
renderServerBackupsTable(d.backups || [], d.total_size_str || '0 o');
|
||
} catch (e) {
|
||
const tbody = $('backupsTableBody');
|
||
if (tbody) tbody.innerHTML = `<tr><td colspan="5" class="empty">${escapeHtml(tErr(e.message))}</td></tr>`;
|
||
}
|
||
}
|
||
|
||
async function saveBackupSchedule(silent = false) {
|
||
const msg = $('backupScheduleMsg');
|
||
const btn = $('btnSaveBackupSchedule');
|
||
const expr = ($('backupCronExpr')?.value || '0 3 * * *').trim();
|
||
const en = !!($('backupCronEnabled') && $('backupCronEnabled').checked);
|
||
if (en && expr.split(/\s+/).length !== 5) {
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = t('backup_cron_invalid', 'Expression Cron invalide (5 champs requis)');
|
||
}
|
||
return;
|
||
}
|
||
if (btn) btn.disabled = true;
|
||
try {
|
||
const payload = {
|
||
enabled: en,
|
||
day: $('backupCronDay')?.value || '*',
|
||
hour: $('backupCronHour')?.value ?? '3',
|
||
minute: parseInt($('backupCronMinute')?.value || '0', 10) || 0,
|
||
retention: parseInt($('backupCronRetention')?.value || '7', 10) || 0,
|
||
cron_expr: expr
|
||
};
|
||
const res = await apiFetch('/api/backups/schedule', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(payload)
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur enregistrement');
|
||
applyBackupScheduleToUI(d.schedule);
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||
msg.style.color = 'var(--green)';
|
||
msg.textContent = '✓ ' + (en ? t('backup_schedule_saved', 'Planification Cron enregistrée avec succès !') : t('backup_schedule_disabled', 'Planification automatique désactivée'));
|
||
setTimeout(() => { if (msg) msg.style.display = 'none'; }, 5000);
|
||
}
|
||
} catch (e) {
|
||
if (msg && !silent) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = '❌ ' + tErr(e.message);
|
||
}
|
||
} finally {
|
||
if (btn) btn.disabled = false;
|
||
}
|
||
}
|
||
|
||
async function createServerBackupNow() {
|
||
const msg = $('backupActionMsg');
|
||
const btn = $('btnCreateServerBackup');
|
||
if (btn) btn.disabled = true;
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||
msg.style.color = 'var(--blue)';
|
||
msg.textContent = t('backup_creating_server', 'Création de la sauvegarde sur le serveur en cours…');
|
||
}
|
||
try {
|
||
const res = await apiFetch('/api/backups/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur création sauvegarde');
|
||
if (d.schedule) applyBackupScheduleToUI(d.schedule);
|
||
renderServerBackupsTable(d.backups || [], d.total_size_str || '0 o');
|
||
if (msg) {
|
||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||
msg.style.color = 'var(--green)';
|
||
msg.textContent = '✓ ' + (d.message || t('backup_created_success', 'Sauvegarde créée avec succès !'));
|
||
setTimeout(() => { if (msg) msg.style.display = 'none'; }, 6000);
|
||
}
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = '❌ ' + tErr(e.message);
|
||
}
|
||
} finally {
|
||
if (btn) btn.disabled = false;
|
||
}
|
||
}
|
||
|
||
async function downloadServerBackup(filename) {
|
||
const msg = $('backupActionMsg');
|
||
try {
|
||
const res = await apiFetch('/api/backups/download?file=' + encodeURIComponent(filename));
|
||
if (!res.ok) {
|
||
let errText = 'Erreur téléchargement';
|
||
try { const d = await res.json(); if (d.error) errText = d.error; } catch (_) { }
|
||
throw new Error(errText);
|
||
}
|
||
const blob = await res.blob();
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = filename;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
setTimeout(() => URL.revokeObjectURL(url), 2000);
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = '❌ ' + tErr(e.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
async function restoreServerBackup(filename) {
|
||
const msg = $('backupActionMsg');
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||
msg.style.color = 'var(--blue)';
|
||
msg.textContent = t('backup_analyzing', 'Analyse de la sauvegarde en cours…');
|
||
}
|
||
try {
|
||
const res = await apiFetch('/api/backups/inspect', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ filename })
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Fichier invalide');
|
||
if (msg) msg.style.display = 'none';
|
||
pendingBackupData = d.backup;
|
||
showImportBackupModal(filename, d.backup);
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = '❌ ' + tErr(e.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
async function openRemoteDriveModal() {
|
||
const modal = $('modalRemoteDriveFiles');
|
||
if (!modal) return;
|
||
modal.classList.add('active');
|
||
modal.style.display = 'flex';
|
||
await loadRemoteDriveFiles();
|
||
}
|
||
|
||
function closeRemoteDriveModal() {
|
||
const modal = $('modalRemoteDriveFiles');
|
||
if (modal) {
|
||
modal.classList.remove('active');
|
||
modal.style.display = 'none';
|
||
}
|
||
}
|
||
|
||
async function loadRemoteDriveFiles() {
|
||
const tbody = $('remoteDriveFilesTableBody');
|
||
const sub = $('remoteDriveModalSub');
|
||
const iconEl = $('remoteDriveModalIcon');
|
||
const msg = $('remoteDriveActionMsg');
|
||
if (msg) msg.style.display = 'none';
|
||
if (tbody) tbody.innerHTML = `<tr><td colspan="5" class="empty"><span class="spin">🔄</span> ${escapeHtml(t('remote_drive_loading', 'Connexion et récupération des fichiers sur le drive…'))}</td></tr>`;
|
||
|
||
try {
|
||
const res = await apiFetch('/api/backups/remote/files');
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur lors de la récupération des fichiers distants');
|
||
|
||
const prov = d.provider || 'ftp';
|
||
const pName = d.provider_name || prov.toUpperCase();
|
||
const provIconHtml = (typeof getRemoteProviderIconHtml === 'function') ? getRemoteProviderIconHtml(prov) : '☁️ ';
|
||
if (iconEl) iconEl.innerHTML = provIconHtml;
|
||
if (sub) {
|
||
sub.innerHTML = `<span>${provIconHtml}<strong>${escapeHtml(pName)}</strong> • ${d.count || 0} sauvegarde(s) détectée(s)</span>`;
|
||
}
|
||
|
||
if (!d.files || !d.files.length) {
|
||
if (tbody) tbody.innerHTML = `<tr><td colspan="5" class="empty">${escapeHtml(t('remote_drive_empty', 'Aucun fichier de sauvegarde trouvé sur le stockage distant.'))}</td></tr>`;
|
||
return;
|
||
}
|
||
|
||
if (tbody) {
|
||
tbody.innerHTML = d.files.map(f => {
|
||
const fname = f.name || '';
|
||
const safeArg = escapeHtml(fname).replace(/'/g, ''');
|
||
const isLocal = !!f.is_local;
|
||
const localBadge = isLocal
|
||
? `<span class="pill pill-green pill-no-dot" style="font-size:10px;padding:2px 6px" title="${escapeHtml(t('backup_already_local', 'Déjà présent dans les sauvegardes locales'))}">💾 Local</span>`
|
||
: `<span class="pill pill-no-dot" style="font-size:10px;padding:2px 6px;opacity:0.75">☁️ Drive seul</span>`;
|
||
|
||
const pullBtn = isLocal
|
||
? `<button type="button" class="secondary" style="padding:4px 8px;font-size:11px" onclick="pullRemoteBackupToLocal('${safeArg}')" title="${escapeHtml(t('backup_reimport', 'Réimporter / Écraser la version locale'))}">📥 Réimporter</button>`
|
||
: `<button type="button" class="secondary" style="padding:4px 8px;font-size:11px;border-color:var(--blue);color:var(--blue)" onclick="pullRemoteBackupToLocal('${safeArg}')" title="${escapeHtml(t('backup_import_local', 'Rapatrier dans AP Manageur'))}">📥 Rapatrier</button>`;
|
||
|
||
return `<tr>
|
||
<td style="font-family:monospace;font-size:12px;word-break:break-all"><strong>${escapeHtml(fname)}</strong></td>
|
||
<td style="white-space:nowrap;font-size:12px" class="muted">${escapeHtml(f.date || '—')}</td>
|
||
<td style="white-space:nowrap;font-size:12px">${escapeHtml(f.size_str || '—')}</td>
|
||
<td>${localBadge}</td>
|
||
<td style="text-align:right;white-space:nowrap">
|
||
<div style="display:inline-flex;gap:6px;justify-content:flex-end">
|
||
<button type="button" class="secondary" style="padding:4px 8px;font-size:11px" onclick="downloadRemoteFileDirect('${safeArg}')" title="${escapeHtml(t('backup_btn_download_pc', 'Télécharger sur mon PC'))}">⬇️ ${escapeHtml(t('btn_download', 'Télécharger'))}</button>
|
||
${pullBtn}
|
||
<button type="button" class="secondary danger" style="padding:4px 8px;font-size:11px;border-color:rgba(239,68,68,0.45);color:var(--red)" onclick="deleteRemoteDriveFile('${safeArg}')" title="${escapeHtml(t('btn_delete', 'Supprimer du drive'))}">🗑️</button>
|
||
</div>
|
||
</td>
|
||
</tr>`;
|
||
}).join('');
|
||
}
|
||
} catch (e) {
|
||
if (tbody) {
|
||
tbody.innerHTML = `<tr><td colspan="5" class="empty" style="color:var(--red)">❌ ${escapeHtml(tErr(e.message))}</td></tr>`;
|
||
}
|
||
if (sub) sub.textContent = 'Erreur de connexion au stockage distant';
|
||
}
|
||
}
|
||
|
||
function downloadRemoteFileDirect(filename) {
|
||
window.location.href = '/api/backups/remote/file/download?file=' + encodeURIComponent(filename);
|
||
}
|
||
|
||
async function pullRemoteBackupToLocal(filename) {
|
||
const msg = $('remoteDriveActionMsg');
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||
msg.style.color = 'var(--blue)';
|
||
msg.innerHTML = `<span class="spin">🔄</span> Rapatriement de « ${escapeHtml(filename)} » vers le serveur local…`;
|
||
}
|
||
try {
|
||
const res = await apiFetch('/api/backups/remote/file/pull', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ filename })
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur lors du rapatriement');
|
||
if (msg) {
|
||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||
msg.style.color = 'var(--green)';
|
||
msg.textContent = '✓ ' + (d.message || 'Sauvegarde rapatriée avec succès !');
|
||
}
|
||
if (Array.isArray(d.backups)) renderServerBackupsTable(d.backups, serverBackupsTotalSize);
|
||
await loadRemoteDriveFiles();
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = '❌ ' + tErr(e.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
async function deleteRemoteDriveFile(filename) {
|
||
const confirmTxt = t('backup_confirm_remote_delete', 'Supprimer définitivement la sauvegarde « {file} » du stockage distant (Drive) ?\n\nAttention, cette action est irréversible.').replace('{file}', filename);
|
||
if (!confirm(confirmTxt)) return;
|
||
const msg = $('remoteDriveActionMsg');
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.innerHTML = `<span class="spin">🔄</span> Suppression de « ${escapeHtml(filename)} » sur le drive…`;
|
||
}
|
||
try {
|
||
const res = await apiFetch('/api/backups/remote/file/delete', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ filename })
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur suppression distante');
|
||
if (msg) {
|
||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||
msg.style.color = 'var(--green)';
|
||
msg.textContent = '✓ ' + (d.message || 'Fichier supprimé du drive.');
|
||
}
|
||
if (Array.isArray(d.backups)) renderServerBackupsTable(d.backups, serverBackupsTotalSize);
|
||
await loadRemoteDriveFiles();
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = '❌ ' + tErr(e.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
async function deleteServerBackup(filename) {
|
||
const confirmTxt = t('backup_confirm_delete', 'Supprimer définitivement la sauvegarde « {file} » ?').replace('{file}', filename);
|
||
if (!confirm(confirmTxt)) return;
|
||
const msg = $('backupActionMsg');
|
||
try {
|
||
const res = await apiFetch('/api/backups/delete', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ filename })
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur suppression');
|
||
renderServerBackupsTable(d.backups || [], d.total_size_str || '0 o');
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||
msg.style.color = 'var(--green)';
|
||
msg.textContent = '✓ ' + (d.message || t('backup_deleted_success', 'Sauvegarde supprimée.'));
|
||
setTimeout(() => { if (msg) msg.style.display = 'none'; }, 5000);
|
||
}
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = '❌ ' + tErr(e.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
function getRemoteProviderIconHtml(prov) {
|
||
if (prov === 'gdrive') return '<img src="/images/gdrive.svg" width="13" height="12" alt="Drive" style="vertical-align:middle;margin-right:4px;object-fit:contain">';
|
||
if (prov === 'dropbox') return '<img src="/images/dropbox.svg" width="13" height="13" alt="Dropbox" style="vertical-align:middle;margin-right:4px;object-fit:contain">';
|
||
if (prov === 'sftp') return '🔐 ';
|
||
if (prov === 'webdav') return '🌐 ';
|
||
if (prov === 's3') return '🪣 ';
|
||
if (prov === 'webhook') return '🔗 ';
|
||
return '📡 ';
|
||
}
|
||
|
||
function selectBackupRemoteProvider(prov) {
|
||
if (!$('backupRemoteEnabled')?.checked) return;
|
||
if ($('backupRemoteProvider')) $('backupRemoteProvider').value = prov;
|
||
onBackupRemoteProviderChange();
|
||
}
|
||
|
||
async function onBackupRemoteToggle() {
|
||
const en = !!($('backupRemoteEnabled') && $('backupRemoteEnabled').checked);
|
||
onBackupRemoteProviderChange();
|
||
if (!en) {
|
||
await saveBackupRemoteConfig(true);
|
||
}
|
||
}
|
||
|
||
function onBackupRemoteProviderChange() {
|
||
const prov = $('backupRemoteProvider')?.value || 'ftp';
|
||
const en = !!($('backupRemoteEnabled') && $('backupRemoteEnabled').checked);
|
||
const body = $('backupRemoteBody');
|
||
if (body) {
|
||
body.style.display = en ? 'block' : 'none';
|
||
body.querySelectorAll('input, select, textarea, button').forEach(el => {
|
||
el.disabled = !en;
|
||
});
|
||
}
|
||
['ftp', 'sftp', 'gdrive', 'dropbox', 'webdav', 's3', 'webhook'].forEach(k => {
|
||
const el = $('remoteFields_' + k);
|
||
if (el) el.style.display = (k === prov) ? 'block' : 'none';
|
||
});
|
||
document.querySelectorAll('.backup-prov-btn').forEach(btn => {
|
||
const isSelected = (btn.getAttribute('data-provider') === prov);
|
||
btn.classList.toggle('active', isSelected);
|
||
btn.style.borderColor = '';
|
||
btn.style.background = '';
|
||
btn.style.boxShadow = '';
|
||
btn.style.color = '';
|
||
btn.style.fontWeight = '';
|
||
btn.querySelectorAll('span').forEach(sp => { sp.style.color = ''; });
|
||
btn.disabled = !en;
|
||
});
|
||
// Mettre à jour les boutons Distant dans la table des sauvegardes
|
||
if (serverBackupsCache && serverBackupsCache.length) {
|
||
renderServerBackupsTable(serverBackupsCache, serverBackupsTotalSize);
|
||
}
|
||
}
|
||
|
||
function getBackupRemotePayload() {
|
||
return {
|
||
enabled: !!($('backupRemoteEnabled') && $('backupRemoteEnabled').checked),
|
||
auto_upload: !!($('backupRemoteAutoUpload') && $('backupRemoteAutoUpload').checked),
|
||
provider: $('backupRemoteProvider')?.value || 'ftp',
|
||
ftp: {
|
||
host: $('remoteFtpHost')?.value?.trim() || '',
|
||
port: parseInt($('remoteFtpPort')?.value || '21', 10) || 21,
|
||
tls: $('remoteFtpTls')?.value || 'none',
|
||
user: $('remoteFtpUser')?.value?.trim() || '',
|
||
password: $('remoteFtpPass')?.value || '',
|
||
path: $('remoteFtpPath')?.value?.trim() || '/backups/'
|
||
},
|
||
sftp: {
|
||
host: $('remoteSftpHost')?.value?.trim() || '',
|
||
port: parseInt($('remoteSftpPort')?.value || '22', 10) || 22,
|
||
user: $('remoteSftpUser')?.value?.trim() || '',
|
||
password: $('remoteSftpPass')?.value || '',
|
||
key: $('remoteSftpKey')?.value?.trim() || '',
|
||
path: $('remoteSftpPath')?.value?.trim() || '/backups/'
|
||
},
|
||
gdrive: {
|
||
token: $('remoteGdriveToken')?.value?.trim() || '',
|
||
folder_id: $('remoteGdriveFolder')?.value?.trim() || ''
|
||
},
|
||
dropbox: {
|
||
token: $('remoteDropboxToken')?.value?.trim() || '',
|
||
path: $('remoteDropboxPath')?.value?.trim() || '/AP-Manageur-Backups/'
|
||
},
|
||
webdav: {
|
||
url: $('remoteWebdavUrl')?.value?.trim() || '',
|
||
user: $('remoteWebdavUser')?.value?.trim() || '',
|
||
password: $('remoteWebdavPass')?.value || ''
|
||
},
|
||
s3: {
|
||
endpoint: $('remoteS3Endpoint')?.value?.trim() || 'https://s3.amazonaws.com',
|
||
region: $('remoteS3Region')?.value?.trim() || 'us-east-1',
|
||
bucket: $('remoteS3Bucket')?.value?.trim() || '',
|
||
access_key: $('remoteS3AccessKey')?.value?.trim() || '',
|
||
secret_key: $('remoteS3SecretKey')?.value || '',
|
||
path: $('remoteS3Path')?.value?.trim() || 'backups/'
|
||
},
|
||
webhook: {
|
||
url: $('remoteWebhookUrl')?.value?.trim() || '',
|
||
method: $('remoteWebhookMethod')?.value || 'POST',
|
||
field_name: $('remoteWebhookField')?.value?.trim() || 'backup',
|
||
headers: $('remoteWebhookHeaders')?.value || ''
|
||
}
|
||
};
|
||
}
|
||
|
||
function applyBackupRemoteToUI(rcfg) {
|
||
if (!rcfg) return;
|
||
if ($('backupRemoteEnabled')) $('backupRemoteEnabled').checked = !!rcfg.enabled;
|
||
if ($('backupRemoteAutoUpload')) $('backupRemoteAutoUpload').checked = rcfg.auto_upload !== false;
|
||
if ($('backupRemoteProvider') && rcfg.provider) $('backupRemoteProvider').value = rcfg.provider;
|
||
|
||
const f = rcfg.ftp || {};
|
||
if ($('remoteFtpHost')) $('remoteFtpHost').value = f.host || '';
|
||
if ($('remoteFtpPort')) $('remoteFtpPort').value = f.port || 21;
|
||
if ($('remoteFtpTls')) $('remoteFtpTls').value = f.tls || 'none';
|
||
if ($('remoteFtpUser')) $('remoteFtpUser').value = f.user || '';
|
||
if ($('remoteFtpPass')) $('remoteFtpPass').value = f.password || '';
|
||
if ($('remoteFtpPath')) $('remoteFtpPath').value = f.path || '/backups/';
|
||
|
||
const s = rcfg.sftp || {};
|
||
if ($('remoteSftpHost')) $('remoteSftpHost').value = s.host || '';
|
||
if ($('remoteSftpPort')) $('remoteSftpPort').value = s.port || 22;
|
||
if ($('remoteSftpUser')) $('remoteSftpUser').value = s.user || '';
|
||
if ($('remoteSftpPass')) $('remoteSftpPass').value = s.password || '';
|
||
if ($('remoteSftpKey')) $('remoteSftpKey').value = s.key || '';
|
||
if ($('remoteSftpPath')) $('remoteSftpPath').value = s.path || '/backups/';
|
||
|
||
const g = rcfg.gdrive || {};
|
||
if ($('remoteGdriveToken')) $('remoteGdriveToken').value = g.token || '';
|
||
if ($('remoteGdriveFolder')) $('remoteGdriveFolder').value = g.folder_id || '';
|
||
|
||
const dbx = rcfg.dropbox || {};
|
||
if ($('remoteDropboxToken')) $('remoteDropboxToken').value = dbx.token || '';
|
||
if ($('remoteDropboxPath')) $('remoteDropboxPath').value = dbx.path || '/AP-Manageur-Backups/';
|
||
|
||
const wd = rcfg.webdav || {};
|
||
if ($('remoteWebdavUrl')) $('remoteWebdavUrl').value = wd.url || '';
|
||
if ($('remoteWebdavUser')) $('remoteWebdavUser').value = wd.user || '';
|
||
if ($('remoteWebdavPass')) $('remoteWebdavPass').value = wd.password || '';
|
||
|
||
const s3 = rcfg.s3 || {};
|
||
if ($('remoteS3Endpoint')) $('remoteS3Endpoint').value = s3.endpoint || 'https://s3.amazonaws.com';
|
||
if ($('remoteS3Region')) $('remoteS3Region').value = s3.region || 'us-east-1';
|
||
if ($('remoteS3Bucket')) $('remoteS3Bucket').value = s3.bucket || '';
|
||
if ($('remoteS3AccessKey')) $('remoteS3AccessKey').value = s3.access_key || '';
|
||
if ($('remoteS3SecretKey')) $('remoteS3SecretKey').value = s3.secret_key || '';
|
||
if ($('remoteS3Path')) $('remoteS3Path').value = s3.path || 'backups/';
|
||
|
||
const wh = rcfg.webhook || {};
|
||
if ($('remoteWebhookUrl')) $('remoteWebhookUrl').value = wh.url || '';
|
||
if ($('remoteWebhookMethod')) $('remoteWebhookMethod').value = wh.method || 'POST';
|
||
if ($('remoteWebhookField')) $('remoteWebhookField').value = wh.field_name || 'backup';
|
||
if ($('remoteWebhookHeaders')) $('remoteWebhookHeaders').value = wh.headers || '';
|
||
|
||
const stEl = $('backupRemoteLastStatus');
|
||
if (stEl) {
|
||
if (rcfg.last_upload_time) {
|
||
const icon = rcfg.last_upload_status === 'ok' ? '✅' : '❌';
|
||
const provIcon = (typeof getRemoteProviderIconHtml === 'function') ? getRemoteProviderIconHtml(rcfg.provider || 'ftp') : '';
|
||
stEl.innerHTML = `${icon} ${provIcon}${escapeHtml(t('backup_remote_last_upload', 'Dernier envoi :'))} ${escapeHtml(rcfg.last_upload_time)} (${escapeHtml(rcfg.last_upload_file || '')})${rcfg.last_upload_error ? ' — ' + escapeHtml(rcfg.last_upload_error) : ''}`;
|
||
} else {
|
||
stEl.textContent = '';
|
||
}
|
||
}
|
||
onBackupRemoteProviderChange();
|
||
}
|
||
|
||
async function saveBackupRemoteConfig(silent) {
|
||
const msg = $('backupRemoteMsg');
|
||
const btn = $('btnSaveBackupRemote');
|
||
if (btn) btn.disabled = true;
|
||
try {
|
||
const res = await apiFetch('/api/backups/remote', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(getBackupRemotePayload())
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur enregistrement');
|
||
if (d.remote) applyBackupRemoteToUI(d.remote);
|
||
if (msg && !silent) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||
msg.style.color = 'var(--green)';
|
||
msg.textContent = '✓ ' + t('backup_remote_saved', 'Configuration du stockage distant enregistrée !');
|
||
setTimeout(() => { if (msg) msg.style.display = 'none'; }, 5000);
|
||
}
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = '❌ ' + tErr(e.message);
|
||
}
|
||
} finally {
|
||
if (btn) btn.disabled = false;
|
||
}
|
||
}
|
||
|
||
async function testBackupRemote() {
|
||
const msg = $('backupRemoteMsg');
|
||
const btn = $('btnTestBackupRemote');
|
||
if (btn) btn.disabled = true;
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||
msg.style.color = 'var(--blue)';
|
||
msg.textContent = t('backup_remote_testing', 'Test de connexion et de transfert en cours…');
|
||
}
|
||
try {
|
||
const res = await apiFetch('/api/backups/remote/test', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ config: getBackupRemotePayload() }),
|
||
timeout: 45000
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Échec du test');
|
||
if (msg) {
|
||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||
msg.style.color = 'var(--green)';
|
||
msg.textContent = '✓ ' + (d.message || t('backup_remote_test_ok', 'Connexion et transfert réussis !'));
|
||
}
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = '❌ ' + tErr(e.message);
|
||
}
|
||
} finally {
|
||
if (btn) btn.disabled = false;
|
||
}
|
||
}
|
||
|
||
async function uploadServerBackupToRemote(filename) {
|
||
if (!$('backupRemoteEnabled') || !$('backupRemoteEnabled').checked) {
|
||
const msg = $('backupActionMsg');
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = '❌ ' + t('backup_remote_disabled_err', 'Le stockage distant n’est pas activé. Veuillez l’activer dans les réglages ci-dessus.');
|
||
}
|
||
return;
|
||
}
|
||
const msg = $('backupActionMsg');
|
||
const prov = $('backupRemoteProvider')?.value || 'ftp';
|
||
const provIcon = (typeof getRemoteProviderIconHtml === 'function') ? getRemoteProviderIconHtml(prov) : '';
|
||
const provNames = {
|
||
gdrive: 'Google Drive',
|
||
dropbox: 'Dropbox',
|
||
sftp: 'SFTP',
|
||
ftp: 'FTP',
|
||
webdav: 'WebDAV',
|
||
s3: 'S3',
|
||
webhook: 'Webhook'
|
||
};
|
||
const pName = provNames[prov] || prov.toUpperCase();
|
||
if (msg) {
|
||
msg.style.display = 'block';
|
||
msg.style.background = 'rgba(56,189,248,0.12)';
|
||
msg.style.color = 'var(--blue)';
|
||
msg.innerHTML = `${provIcon}${escapeHtml(t('backup_remote_uploading', 'Envoi de « {file} » vers le stockage distant…').replace('{file}', filename))} (${escapeHtml(pName)})`;
|
||
}
|
||
try {
|
||
const res = await apiFetch('/api/backups/remote/upload', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ filename }),
|
||
timeout: 120000
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Échec du transfert distant');
|
||
if (d.remote) applyBackupRemoteToUI(d.remote);
|
||
if (Array.isArray(d.backups)) {
|
||
renderServerBackupsTable(d.backups, serverBackupsTotalSize);
|
||
} else {
|
||
await loadBackupsTab(true);
|
||
}
|
||
if (msg) {
|
||
msg.style.background = 'rgba(50,213,131,0.12)';
|
||
msg.style.color = 'var(--green)';
|
||
msg.textContent = '✓ ' + (d.message || t('backup_remote_upload_ok', 'Sauvegarde transférée vers le stockage distant !'));
|
||
setTimeout(() => { if (msg) msg.style.display = 'none'; }, 7000);
|
||
}
|
||
} catch (e) {
|
||
if (msg) {
|
||
msg.style.background = 'rgba(239,68,68,0.12)';
|
||
msg.style.color = 'var(--red)';
|
||
msg.textContent = '❌ ' + tErr(e.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
const EYE_OPEN = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-8 10-8 10 8 10 8-3.5 8-10 8S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>';
|
||
const EYE_OFF = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 4.2A10.7 10.7 0 0 1 12 4c5 0 8.5 4 10 8a16.7 16.7 0 0 1-3.1 4.8M6.6 6.6C4.7 7.8 3.5 9.7 2 12c1.5 4 5 8 10 8 1 0 2-.2 2.9-.5"/></svg>';
|
||
const REGISTERED_PASSWORD_TOGGLES = [];
|
||
|
||
function getPasswordToggleLabels(btnId, isText) {
|
||
const bid = (btnId || '').toLowerCase();
|
||
if (bid === 'toggleauthsettingspassword') {
|
||
return isText
|
||
? t('settings_hide_new_pwd', 'Masquer le nouveau mot de passe')
|
||
: t('settings_show_new_pwd', 'Afficher le nouveau mot de passe');
|
||
}
|
||
if (bid === 'toggleauthsettingspasswordconfirm' || bid === 'togglesetuppasswordconfirm') {
|
||
return isText
|
||
? t('settings_hide_confirm_pwd', 'Masquer la confirmation du mot de passe')
|
||
: t('settings_show_confirm_pwd', 'Afficher la confirmation du mot de passe');
|
||
}
|
||
if (bid === 'togglecurrentpassword' || bid === 'toggletwofacurrentpassword') {
|
||
return isText
|
||
? t('settings_hide_cur_pwd', 'Masquer le mot de passe actuel')
|
||
: t('settings_show_cur_pwd', 'Afficher le mot de passe actuel');
|
||
}
|
||
if (bid.includes('pushoveruser') || bid.includes('secretkey')) {
|
||
return isText
|
||
? t('settings_hide_key', 'Masquer la clé')
|
||
: t('settings_show_key', 'Afficher la clé');
|
||
}
|
||
if (bid.includes('token')) {
|
||
return isText
|
||
? t('settings_hide_token', 'Masquer le jeton')
|
||
: t('settings_show_token', 'Afficher le jeton');
|
||
}
|
||
return isText
|
||
? t('btn_hide_pwd', 'Masquer le mot de passe')
|
||
: t('btn_show_pwd', 'Afficher le mot de passe');
|
||
}
|
||
|
||
function updateAllPasswordToggles() {
|
||
REGISTERED_PASSWORD_TOGGLES.forEach(({ btnId, fieldId }) => {
|
||
const btn = $(btnId), field = $(fieldId);
|
||
if (!btn || !field) return;
|
||
const isText = (field.type === 'text');
|
||
const label = getPasswordToggleLabels(btnId, isText);
|
||
btn.setAttribute('aria-label', label);
|
||
btn.setAttribute('title', label);
|
||
});
|
||
}
|
||
|
||
function bindPasswordToggle(btnId, fieldId) {
|
||
const btn = $(btnId), field = $(fieldId); if (!btn || !field) return;
|
||
REGISTERED_PASSWORD_TOGGLES.push({ btnId, fieldId });
|
||
|
||
const initLabel = getPasswordToggleLabels(btnId, field.type === 'text');
|
||
btn.setAttribute('aria-label', initLabel);
|
||
btn.setAttribute('title', initLabel);
|
||
|
||
btn.onclick = () => {
|
||
const isHidden = field.type === 'password';
|
||
field.type = isHidden ? 'text' : 'password';
|
||
btn.innerHTML = isHidden ? EYE_OFF : EYE_OPEN;
|
||
const label = getPasswordToggleLabels(btnId, isHidden);
|
||
btn.setAttribute('aria-label', label);
|
||
btn.setAttribute('title', label);
|
||
};
|
||
}
|
||
bindPasswordToggle('toggleSetupPassword', 'setupPassword');
|
||
bindPasswordToggle('toggleSetupPasswordConfirm', 'setupPasswordConfirm');
|
||
bindPasswordToggle('toggleSettingsPassword', 'settingsPassword');
|
||
bindPasswordToggle('toggleAuthSettingsPassword', 'authSettingsPassword');
|
||
bindPasswordToggle('toggleAuthSettingsPasswordConfirm', 'authSettingsPasswordConfirm');
|
||
bindPasswordToggle('toggleAuthPassword', 'authPassword');
|
||
bindPasswordToggle('toggleCurrentPassword', 'authCurrentPassword');
|
||
bindPasswordToggle('toggleTwoFaCurrentPassword', 'twoFaCurrentPassword');
|
||
bindPasswordToggle('toggleNotifEmailPass', 'notifEmailPass');
|
||
bindPasswordToggle('toggleNotifGotifyToken', 'notifGotifyToken');
|
||
bindPasswordToggle('toggleNotifNtfyToken', 'notifNtfyToken');
|
||
bindPasswordToggle('toggleNotifPushbulletToken', 'notifPushbulletToken');
|
||
bindPasswordToggle('toggleNotifPushoverUser', 'notifPushoverUser');
|
||
bindPasswordToggle('toggleNotifPushoverToken', 'notifPushoverToken');
|
||
bindPasswordToggle('toggleNotifTelegramToken', 'notifTelegramToken');
|
||
bindPasswordToggle('toggleRemoteFtpPass', 'remoteFtpPass');
|
||
bindPasswordToggle('toggleRemoteSftpPass', 'remoteSftpPass');
|
||
bindPasswordToggle('toggleRemoteGdriveToken', 'remoteGdriveToken');
|
||
bindPasswordToggle('toggleRemoteDropboxToken', 'remoteDropboxToken');
|
||
bindPasswordToggle('toggleRemoteWebdavPass', 'remoteWebdavPass');
|
||
bindPasswordToggle('toggleRemoteS3SecretKey', 'remoteS3SecretKey');
|
||
const authCurrInput = $('authCurrentPassword');
|
||
const twoFaCurrInput = $('twoFaCurrentPassword');
|
||
if (authCurrInput && twoFaCurrInput) {
|
||
authCurrInput.addEventListener('input', () => { twoFaCurrInput.value = authCurrInput.value; });
|
||
twoFaCurrInput.addEventListener('input', () => { authCurrInput.value = twoFaCurrInput.value; });
|
||
}
|
||
|
||
$('apControl').onclick = () => controlAp(status.active ? 'stop' : 'start');
|
||
$('apRestart').onclick = () => controlAp('restart');
|
||
|
||
$('clearAllData').onclick = () => runAction(async () => {
|
||
if (!confirm(t('confirm_delete_all_data', '⚠️ ATTENTION : Voulez-vous vraiment supprimer toutes les données de l’application ?'))) return;
|
||
const message = $('clearDataMessage'); message.textContent = t('loading', 'Suppression…');
|
||
try {
|
||
const response = await apiFetch('/api/data/clear', { method: 'POST' }); const data = await response.json();
|
||
if (!response.ok) throw Error(data.error || 'Suppression refusée');
|
||
message.textContent = tMsg(data.message);
|
||
authToken = '';
|
||
try {
|
||
sessionStorage.removeItem('apAuthToken');
|
||
localStorage.removeItem('apAuthToken');
|
||
sessionStorage.removeItem('apAppStarted');
|
||
localStorage.removeItem('apAppStarted');
|
||
sessionStorage.removeItem('apVisited');
|
||
localStorage.removeItem('apTheme');
|
||
sessionStorage.removeItem('setupExplicitTheme');
|
||
sessionStorage.removeItem('setupExplicitLang');
|
||
clearAuthCookie();
|
||
} catch (_) {}
|
||
await new Promise(resolve => setTimeout(resolve, 600));
|
||
window.location.replace('/setup');
|
||
} catch (e) { message.textContent = tErr(e.message); }
|
||
});
|
||
|
||
document.querySelectorAll('input[name="settingsMode"]').forEach(r => r.addEventListener('change', () => { if ($('settingsBridgeBlock')) $('settingsBridgeBlock').style.display = r.value === 'bridge' ? 'block' : 'none' }));
|
||
|
||
if ($('setupAp')) {
|
||
$('setupAp').onclick = () => runAction(async () => {
|
||
const message = $('setupMessage'); const password = $('setupPassword').value; const confirmation = $('setupPasswordConfirm').value;
|
||
if (password !== confirmation) { message.textContent = 'Erreur : les mots de passe ne correspondent pas'; return }
|
||
message.textContent = 'Configuration…';
|
||
try {
|
||
const sMode = document.querySelector('input[name="setupMode"]:checked')?.value || 'ap';
|
||
const sEth = $('setupBridgeEth')?.value || '';
|
||
const response = await apiFetch('/api/setup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ssid: $('setupSsid').value, password: password, security: $('setupSecurity').value, mode: sMode, bridge_eth: sEth, max_clients: parseInt($('setupMaxClients') ? $('setupMaxClients').value : 0, 10) || 0 }) });
|
||
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Configuration refusée');
|
||
message.textContent = data.message; currentTab = 'dashboard'; sessionStorage.setItem('apDashboardTab', 'dashboard');
|
||
await new Promise(resolve => setTimeout(resolve, 500)); await load();
|
||
} catch (e) { message.textContent = tErr(e.message); }
|
||
});
|
||
}
|
||
|
||
$('refresh').onclick = () => {
|
||
sessionStorage.setItem('apDashboardTab', currentTab);
|
||
sessionStorage.setItem('apAppStarted', '1');
|
||
localStorage.setItem('apAppStarted', '1');
|
||
if ($('loaderBadgeText')) $('loaderBadgeText').textContent = t('loader_refreshing_badge', "Actualisation en cours");
|
||
if ($('loaderBadgeIcon')) $('loaderBadgeIcon').innerHTML = ICON_REFRESH_ARROW;
|
||
if ($('loaderStatusText')) $('loaderStatusText').textContent = t('loader_refreshing', "Actualisation en cours…");
|
||
const topIcon = $('loaderTopIcon');
|
||
if (topIcon) topIcon.innerHTML = '<svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="#38bdf8" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" style="display:block;animation:spin 2s linear infinite"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.9 1 6.7 2.4L21 8"/><polyline points="21 3 21 8 16 8"/></svg>';
|
||
showLoaderScreen();
|
||
location.reload();
|
||
};
|
||
$('showPassword').onclick = () => {
|
||
const field = $('qrPassword'); const button = $('showPassword'); const hidden = field.type === 'password';
|
||
field.type = hidden ? 'text' : 'password'; button.textContent = hidden ? t('hide_password', 'Cacher le mot de passe') : t('show_password', 'Afficher le mot de passe');
|
||
button.setAttribute('aria-label', button.textContent);
|
||
};
|
||
|
||
$('saveSettings').onclick = () => runAction(async () => {
|
||
let m = $('message'); m.textContent = t('loading', 'Enregistrement…');
|
||
try {
|
||
const setMode = document.querySelector('input[name="settingsMode"]:checked')?.value || 'ap';
|
||
const setEth = $('settingsBridgeEth')?.value || '';
|
||
let r = await apiFetch('/api/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ssid: $('settingsSsid').value, password: $('settingsPassword').value, security: $('settingsSecurity').value, mode: setMode, bridge_eth: setEth, max_clients: parseInt($('settingsMaxClients') ? $('settingsMaxClients').value : 0, 10) || 0, autoconnect: $('settingsAutoconnect').checked }) });
|
||
let d = await r.json(); if (!r.ok) throw Error(d.error);
|
||
m.textContent = tMsg(d.message); await new Promise(resolve => setTimeout(resolve, 1000)); await load();
|
||
} catch (e) { m.textContent = tErr(e.message); }
|
||
});
|
||
|
||
$('logout').onclick = logout;
|
||
|
||
// Le thème n'est effectif qu'une fois enregistré dans la base de données
|
||
const themeSelEl = $('themeSelect');
|
||
if (themeSelEl) {
|
||
// En cas de changement de sélection dans la liste, on ne modifie pas le thème de l'application
|
||
// Le thème reste celui en base de données jusqu'au clic sur "Enregistrer la personnalisation"
|
||
}
|
||
|
||
$('saveCustomization').onclick = () => {
|
||
const appName = $('appNameInput').value.trim(); const appShortName = $('appShortNameInput').value.trim();
|
||
const chosenLang = currentLanguage;
|
||
const selectedTheme = $('themeSelect') ? $('themeSelect').value : themePref;
|
||
const m = $('themeMessage');
|
||
if (m) {
|
||
m.style.color = 'var(--blue)';
|
||
m.textContent = t('custom_saving', 'Enregistrement…');
|
||
}
|
||
apiFetch('/api/preferences', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ theme: selectedTheme, language: chosenLang, app_name: appName, app_short_name: appShortName })
|
||
}).then(async r => {
|
||
const d = await r.json();
|
||
if (r.ok) {
|
||
// Le thème devient effectif seulement après confirmation d'enregistrement en base de données
|
||
themePref = selectedTheme;
|
||
try { localStorage.setItem('apTheme', themePref); } catch (_) { }
|
||
applyTheme();
|
||
|
||
try { localStorage.setItem('apLanguage', chosenLang); } catch (_) { }
|
||
setLanguage(chosenLang, false);
|
||
applyProjectTitle(appName, appShortName);
|
||
if (m) {
|
||
m.style.color = 'var(--blue)';
|
||
m.textContent = tMsg(t('custom_saved_msg', 'Personnalisation enregistrée sur le serveur'));
|
||
}
|
||
} else {
|
||
if ($('themeSelect')) $('themeSelect').value = themePref;
|
||
if (m) {
|
||
m.style.color = 'var(--red)';
|
||
m.textContent = t('err_prefix', 'Erreur : ') + tErr(d.error || 'enregistrement refusé');
|
||
}
|
||
}
|
||
}).catch(e => {
|
||
if ($('themeSelect')) $('themeSelect').value = themePref;
|
||
if (m) {
|
||
m.style.color = 'var(--red)';
|
||
m.textContent = t('err_prefix', 'Erreur : ') + tErr(e.message);
|
||
}
|
||
});
|
||
};
|
||
|
||
$('authSubmit').onclick = async () => {
|
||
const message = $('authMessage'); message.textContent = t('auth_processing', 'Traitement…');
|
||
try {
|
||
const path = authSetupMode ? '/api/auth/setup' : '/api/login';
|
||
const devName = localStorage.getItem('apDeviceName') || '';
|
||
const authHeaders = { 'Content-Type': 'application/json' };
|
||
if (devName) authHeaders['X-Device-Name'] = encodeURIComponent(devName);
|
||
const response = await fetch(API_URL + path, { method: 'POST', headers: authHeaders, body: JSON.stringify({ username: $('authUsername').value, password: $('authPassword').value, otp: $('authOtp').value.trim(), device_name: devName }) });
|
||
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Authentification refusée');
|
||
if (authSetupMode) { message.textContent = t('auth_account_created', 'Compte créé. Connexion…'); authSetupMode = false; return $('authSubmit').click() }
|
||
authToken = data.token;
|
||
sessionStorage.setItem('apAuthToken', authToken);
|
||
localStorage.setItem('apAuthToken', authToken);
|
||
saveAuthCookie(authToken);
|
||
currentTab = 'dashboard'; sessionStorage.setItem('apDashboardTab', 'dashboard');
|
||
if ($('rememberUser').checked) { localStorage.setItem('apRememberedUser', $('authUsername').value.trim()); }
|
||
else { localStorage.removeItem('apRememberedUser'); }
|
||
$('authOtp').value = '';
|
||
try {
|
||
await initializeAndShowDashboard(true);
|
||
} catch (_) {
|
||
showApp();
|
||
hideLoaderScreen();
|
||
}
|
||
} catch (e) { message.textContent = tErr(e.message); }
|
||
};
|
||
|
||
$('saveAuth').onclick = () => runAction(async () => {
|
||
const message = $('authSettingsMessage'); const password = $('authSettingsPassword').value; const confirmation = $('authSettingsPasswordConfirm').value;
|
||
if (password !== confirmation) { message.textContent = tErr('Erreur : les mots de passe ne correspondent pas'); return; }
|
||
message.textContent = t('loading', 'Enregistrement…');
|
||
try {
|
||
const response = await apiFetch('/api/auth/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: $('authSettingsUsername').value, current_password: $('authCurrentPassword').value, password }) });
|
||
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Modification refusée');
|
||
message.textContent = tMsg(data.message || t('auth_creds_updated_success', 'Identifiants modifiés avec succès !'));
|
||
$('authCurrentPassword').value = ''; $('authSettingsPassword').value = ''; $('authSettingsPasswordConfirm').value = '';
|
||
if (typeof loadAdminUser === 'function') await loadAdminUser();
|
||
} catch (e) { message.textContent = tErr(e.message); }
|
||
});
|
||
|
||
/* Double identification (2FA) */
|
||
let twoFaPending = false; let currentRecoveryCodes = [];
|
||
function displayRecoveryCodes(codes) {
|
||
currentRecoveryCodes = codes || [];
|
||
const grid = $('twoFaRecoveryGrid'); grid.replaceChildren();
|
||
currentRecoveryCodes.forEach(code => {
|
||
const div = document.createElement('div'); div.className = 'code-chip'; div.textContent = code; grid.appendChild(div);
|
||
});
|
||
$('twoFaRecoveryDisplay').style.display = 'block';
|
||
}
|
||
$('copyRecoveryCodes').onclick = () => {
|
||
if (!currentRecoveryCodes.length) return;
|
||
const text = (t('twofa_recovery_title', "Codes de récupération 2FA AP Wi-Fi") + ":\n") + currentRecoveryCodes.join("\n");
|
||
const alertCopied = t('twofa_codes_copied_alert', "Codes copiés dans le presse-papier !");
|
||
navigator.clipboard.writeText(text).then(() => alert(alertCopied)).catch(() => {
|
||
const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta); alert(alertCopied);
|
||
});
|
||
};
|
||
function downloadRecoveryFile(codes) {
|
||
if (!codes || !codes.length) return;
|
||
const text = "Codes de récupération 2FA - AP Wi-Fi\nConservez ces codes en lieu sûr.\n\n" + codes.join("\n") + "\n";
|
||
const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
|
||
const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'codes-de-recuperation-2fa.txt'; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url);
|
||
}
|
||
$('downloadRecoveryCodes').onclick = () => downloadRecoveryFile(currentRecoveryCodes);
|
||
|
||
let last2faState = { enabled: false, recoveryRemaining: undefined };
|
||
function render2faCurrentState() {
|
||
render2fa(last2faState.enabled, last2faState.recoveryRemaining);
|
||
}
|
||
|
||
function render2fa(enabled, recoveryRemaining) {
|
||
last2faState = { enabled, recoveryRemaining };
|
||
authTwoFactor = enabled;
|
||
if (enabled) {
|
||
const remStr = recoveryRemaining !== undefined ? recoveryRemaining : '?';
|
||
$('twoFaState').textContent = t('twofa_state_enabled', 'Activée : un code TOTP ou un code de secours sera demandé à chaque connexion. (Codes de secours restants : {rem} / 8)').replace('{rem}', remStr);
|
||
$('twoFaCode').style.display = 'block'; $('twoFaHelpText').style.display = 'block';
|
||
$('twoFaDownloadMenuBtn').style.display = ''; $('twoFaRegenRecovery').style.display = '';
|
||
$('twoFaDisable').style.display = ''; $('twoFaEnable').style.display = 'none';
|
||
$('twoFaConfirm').style.display = 'none'; $('twoFaSetup').style.display = 'none';
|
||
} else if (twoFaPending) {
|
||
$('twoFaState').textContent = t('twofa_state_pending', 'Activation en cours : scannez le QR code et saisissez le code à 6 chiffres de votre application.');
|
||
$('twoFaSetup').style.display = 'block'; $('twoFaCode').style.display = 'block';
|
||
$('twoFaConfirm').style.display = ''; $('twoFaHelpText').style.display = 'none';
|
||
$('twoFaEnable').style.display = 'none'; $('twoFaDisable').style.display = 'none';
|
||
$('twoFaDownloadMenuBtn').style.display = 'none'; $('twoFaRegenRecovery').style.display = 'none';
|
||
} else {
|
||
$('twoFaState').textContent = t('twofa_state_disabled', 'Désactivée.');
|
||
$('twoFaSetup').style.display = 'none'; $('twoFaCode').style.display = 'none';
|
||
$('twoFaHelpText').style.display = 'none'; $('twoFaEnable').style.display = '';
|
||
$('twoFaConfirm').style.display = 'none'; $('twoFaDisable').style.display = 'none';
|
||
$('twoFaDownloadMenuBtn').style.display = 'none'; $('twoFaRegenRecovery').style.display = 'none';
|
||
$('twoFaRecoveryDisplay').style.display = 'none';
|
||
}
|
||
}
|
||
|
||
async function loadAdminUser() {
|
||
try {
|
||
const res = await apiFetch('/api/auth/admin');
|
||
if (!res.ok) return;
|
||
const data = await res.json();
|
||
if (data.ok && data.username) {
|
||
const u = data.username;
|
||
if ($('authSettingsUsername')) $('authSettingsUsername').value = u;
|
||
if (localStorage.getItem('apRememberedUser')) localStorage.setItem('apRememberedUser', u);
|
||
}
|
||
} catch (e) { console.error('Erreur chargement utilisateur admin:', e); }
|
||
}
|
||
|
||
async function load2fa() {
|
||
try {
|
||
const response = await apiFetch('/api/auth/2fa/status', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
|
||
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Statut 2FA indisponible');
|
||
render2fa(!!data.enabled, data.recovery_remaining);
|
||
} catch (e) { $('twoFaState').textContent = tErr(e.message); }
|
||
}
|
||
|
||
$('twoFaEnable').onclick = () => runAction(async () => {
|
||
const message = $('twoFaMessage'); message.textContent = '';
|
||
try {
|
||
const currentPwd = ($('twoFaCurrentPassword') && $('twoFaCurrentPassword').value) ? $('twoFaCurrentPassword').value : $('authCurrentPassword').value;
|
||
if (!currentPwd) throw Error(t('err_enter_current_pwd', 'Saisissez votre mot de passe administrateur actuel'));
|
||
if ($('authCurrentPassword')) $('authCurrentPassword').value = currentPwd;
|
||
const response = await apiFetch('/api/auth/2fa/enable', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password: currentPwd }) });
|
||
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Activation refusée');
|
||
const user = encodeURIComponent($('authSettingsUsername').value || 'admin');
|
||
$('twoFaQr').replaceChildren();
|
||
new QRCode($('twoFaQr'), { text: 'otpauth://totp/AP%20Wi-Fi:' + user + '?secret=' + data.secret + '&issuer=AP%20Wi-Fi', width: 190, height: 190 });
|
||
cleanQrBox($('twoFaQr'));
|
||
setTimeout(() => cleanQrBox($('twoFaQr')), 50);
|
||
setTimeout(() => cleanQrBox($('twoFaQr')), 200);
|
||
$('twoFaSecret').textContent = data.secret;
|
||
twoFaPending = true; render2fa(false); message.textContent = tMsg(data.message);
|
||
} catch (e) { message.textContent = tErr(e.message); }
|
||
});
|
||
|
||
$('twoFaConfirm').onclick = () => runAction(async () => {
|
||
const message = $('twoFaMessage');
|
||
try {
|
||
const currentPwd = ($('twoFaCurrentPassword') && $('twoFaCurrentPassword').value) ? $('twoFaCurrentPassword').value : $('authCurrentPassword').value;
|
||
if ($('authCurrentPassword')) $('authCurrentPassword').value = currentPwd;
|
||
const response = await apiFetch('/api/auth/2fa/confirm', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: $('twoFaCode').value.trim(), password: currentPwd }) });
|
||
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Code refusé');
|
||
twoFaPending = false; $('twoFaCode').value = ''; $('twoFaQr').replaceChildren(); $('twoFaSecret').textContent = '';
|
||
if (data.recovery_codes) displayRecoveryCodes(data.recovery_codes);
|
||
await load2fa(); message.textContent = tMsg(data.message || 'Double identification activée avec succès !');
|
||
} catch (e) { message.textContent = tErr(e.message); }
|
||
});
|
||
|
||
$('twoFaDownloadMenuBtn').onclick = () => runAction(async () => {
|
||
const message = $('twoFaMessage');
|
||
if (currentRecoveryCodes.length) { downloadRecoveryFile(currentRecoveryCodes); message.textContent = t('twofa_codes_downloaded', 'Fichier des codes de récupération téléchargé !'); return; }
|
||
message.textContent = t('twofa_codes_generating_dl', 'Génération et téléchargement des codes de secours…');
|
||
try {
|
||
const currentPwd = ($('twoFaCurrentPassword') && $('twoFaCurrentPassword').value) ? $('twoFaCurrentPassword').value : $('authCurrentPassword').value;
|
||
if (!currentPwd) throw Error(t('err_enter_current_pwd', 'Saisissez votre mot de passe administrateur actuel'));
|
||
if ($('authCurrentPassword')) $('authCurrentPassword').value = currentPwd;
|
||
const response = await apiFetch('/api/auth/2fa/recovery', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password: currentPwd, code: $('twoFaCode').value.trim() }) });
|
||
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Génération refusée');
|
||
if (data.recovery_codes) { displayRecoveryCodes(data.recovery_codes); downloadRecoveryFile(data.recovery_codes); }
|
||
$('twoFaCode').value = ''; await load2fa(); message.textContent = tMsg(data.message || 'Nouveaux codes générés et téléchargés avec succès !');
|
||
} catch (e) { message.textContent = tErr(e.message); }
|
||
});
|
||
|
||
$('twoFaRegenRecovery').onclick = () => runAction(async () => {
|
||
const message = $('twoFaMessage'); message.textContent = t('twofa_codes_generating', 'Génération de nouveaux codes…');
|
||
try {
|
||
const currentPwd = ($('twoFaCurrentPassword') && $('twoFaCurrentPassword').value) ? $('twoFaCurrentPassword').value : $('authCurrentPassword').value;
|
||
if (!currentPwd) throw Error(t('err_enter_current_pwd', 'Saisissez votre mot de passe administrateur actuel'));
|
||
if ($('authCurrentPassword')) $('authCurrentPassword').value = currentPwd;
|
||
const response = await apiFetch('/api/auth/2fa/recovery', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password: currentPwd, code: $('twoFaCode').value.trim() }) });
|
||
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Régénération refusée');
|
||
if (data.recovery_codes) displayRecoveryCodes(data.recovery_codes);
|
||
$('twoFaCode').value = ''; await load2fa(); message.textContent = tMsg(data.message || 'Nouveaux codes générés avec succès !');
|
||
} catch (e) { message.textContent = tErr(e.message); }
|
||
});
|
||
|
||
$('twoFaDisable').onclick = () => runAction(async () => {
|
||
const message = $('twoFaMessage');
|
||
try {
|
||
const currentPwd = ($('twoFaCurrentPassword') && $('twoFaCurrentPassword').value) ? $('twoFaCurrentPassword').value : $('authCurrentPassword').value;
|
||
if ($('authCurrentPassword')) $('authCurrentPassword').value = currentPwd;
|
||
const response = await apiFetch('/api/auth/2fa/disable', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: $('twoFaCode').value.trim(), password: currentPwd }) });
|
||
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Désactivation refusée');
|
||
$('twoFaCode').value = ''; twoFaPending = false; $('twoFaRecoveryDisplay').style.display = 'none'; currentRecoveryCodes = [];
|
||
await load2fa(); message.textContent = tMsg(data.message);
|
||
} catch (e) { message.textContent = tErr(e.message); }
|
||
});
|
||
|
||
/* Gestion des sessions connectées au compte administrateur */
|
||
let sessionsDataCache = [];
|
||
|
||
async function loadSessions() {
|
||
const tbody = $('adminSessionsBody'); if (!tbody) return;
|
||
try {
|
||
const response = await apiFetch('/api/auth/sessions', { cache: 'no-store' });
|
||
if (!response.ok) throw Error('HTTP ' + response.status);
|
||
sessionsDataCache = await response.json();
|
||
renderSessionsTable();
|
||
} catch (e) {
|
||
tbody.innerHTML = `<tr><td colspan="6" class="empty">${t('session_load_failed', 'Impossible de charger les sessions')} (${escapeHtml(e.message)})</td></tr>`;
|
||
}
|
||
}
|
||
|
||
function renderSessionsTable() {
|
||
const tbody = $('adminSessionsBody'); if (!tbody) return;
|
||
if (!sessionsDataCache || !sessionsDataCache.length) {
|
||
tbody.innerHTML = `<tr><td colspan="6" class="empty">${t('session_no_active', 'Aucune session active trouvée')}</td></tr>`; return;
|
||
}
|
||
tbody.innerHTML = sessionsDataCache.map(s => {
|
||
const os = s.os_name || t('unknown_m', 'Inconnu');
|
||
const browser = s.browser_name || t('session_browser_default', 'Navigateur Web');
|
||
const isMobile = /ios|iphone|ipad|android/i.test(s.os_name || '');
|
||
const icon = isMobile ? '📱' : '💻';
|
||
const currentBadge = s.is_current
|
||
? `<span class="pill pill-green pill-no-dot" style="font-size:11px;padding:2px 8px;margin-left:6px">${t('session_current_badge', '● Actuelle')}</span>`
|
||
: '';
|
||
const nameRaw = s.device_name || t('session_unknown_machine', 'Machine inconnue');
|
||
const nameEsc = String(nameRaw).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const ipEsc = String(s.ip || '—').replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const osEsc = String(os).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const browserEsc = String(browser).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
const timeEsc = String(s.last_seen || s.created_at || '—').replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
|
||
return `<tr>
|
||
<td>
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<strong>${icon} ${nameEsc}</strong>${currentBadge}
|
||
<button class="secondary" type="button" style="padding:2px 7px;font-size:11px;border-radius:6px;cursor:pointer" onclick="renameSession('${s.token}','${nameEsc}')" title="${t('rename_session_device', 'Renommer cet appareil')}">✏️ ${t('btn_rename', 'Renommer')}</button>
|
||
</div>
|
||
</td>
|
||
<td><code>${ipEsc}</code></td>
|
||
<td>${osEsc}</td>
|
||
<td><span style="color:var(--blue);font-weight:600">${browserEsc}</span></td>
|
||
<td>${timeEsc}</td>
|
||
<td><button class="secondary" type="button" style="color:var(--red);border-color:rgba(255,107,107,.4);padding:6px 12px;font-size:12px" onclick="revokeSession('${s.token}',${s.is_current},'${nameEsc}','${ipEsc}')">${t('btn_disconnect', 'Déconnexion')}</button></td>
|
||
</tr>`;
|
||
}).join('');
|
||
}
|
||
|
||
async function renameSession(token, currentName) {
|
||
const promptMsg = t('session_rename_prompt', "Entrez un nom personnalisé pour cette machine :");
|
||
const newName = prompt(promptMsg, currentName || "");
|
||
if (newName === null) return;
|
||
const trimmed = newName.trim();
|
||
if (!trimmed) return;
|
||
return runAction(async () => {
|
||
const sm = $('sessionsMessage');
|
||
if (sm) sm.textContent = t('session_rename_saving', 'Enregistrement du nom…');
|
||
try {
|
||
const response = await apiFetch('/api/auth/sessions/rename', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ token, name: trimmed })
|
||
});
|
||
const data = await response.json();
|
||
if (!response.ok) throw Error(data.error || 'Impossible de renommer la machine');
|
||
const isCurrent = sessionsDataCache.find(s => s.token === token)?.is_current;
|
||
if (isCurrent) {
|
||
localStorage.setItem('apDeviceName', trimmed);
|
||
}
|
||
if (sm) sm.textContent = t('session_renamed_success', 'Machine renommée avec succès !');
|
||
await loadSessions();
|
||
setTimeout(() => { if (sm && sm.textContent.includes('succès') || sm.textContent.includes('successfully')) sm.textContent = ''; }, 3000);
|
||
} catch (e) {
|
||
if (sm) sm.textContent = tErr(e.message);
|
||
}
|
||
});
|
||
}
|
||
|
||
async function revokeSession(token, isCurrent, deviceName, ip) {
|
||
const msg = isCurrent
|
||
? t('session_revoke_confirm_current', "Déconnecter cette session actuelle ? Vous serez immédiatement redirigé vers la page de connexion.")
|
||
: t('session_revoke_confirm_other', "Forcer la déconnexion de l'appareil « {device} » ({ip}) ?").replace('{device}', deviceName || ip).replace('{ip}', ip);
|
||
if (!confirm(msg)) return;
|
||
return runAction(async () => {
|
||
const sm = $('sessionsMessage');
|
||
if (sm) sm.textContent = t('session_revoke_progress', 'Déconnexion de la session en cours…');
|
||
try {
|
||
const response = await apiFetch('/api/auth/sessions/revoke', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ token })
|
||
});
|
||
const data = await response.json();
|
||
if (!response.ok) throw Error(data.error || 'Impossible de déconnecter la session');
|
||
if (data.is_self || isCurrent) {
|
||
authToken = ''; sessionStorage.removeItem('apAuthToken'); localStorage.removeItem('apAuthToken'); clearAuthCookie(); showAuth(false);
|
||
return;
|
||
}
|
||
if (sm) sm.textContent = t('session_revoked_success', 'Session déconnectée avec succès.');
|
||
await loadSessions();
|
||
setTimeout(() => { if (sm && sm.textContent.includes('succès') || sm.textContent.includes('successfully')) sm.textContent = ''; }, 3500);
|
||
} catch (e) {
|
||
if (sm) sm.textContent = tErr(e.message);
|
||
}
|
||
});
|
||
}
|
||
|
||
const refSessBtn = $('refreshSessionsBtn');
|
||
if (refSessBtn) refSessBtn.onclick = () => runAction(loadSessions);
|
||
|
||
/* ==========================================================================
|
||
Gestion des Passkeys (FIDO2 / WebAuthn - Connexion sans mot de passe ni 2FA)
|
||
========================================================================== */
|
||
function bufferToBase64Url(buf) {
|
||
const bytes = new Uint8Array(buf);
|
||
let str = '';
|
||
for (let i = 0; i < bytes.length; i++) str += String.fromCharCode(bytes[i]);
|
||
return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||
}
|
||
|
||
function base64UrlToBuffer(b64url) {
|
||
let b64 = String(b64url).replace(/-/g, '+').replace(/_/g, '/');
|
||
while (b64.length % 4) b64 += '=';
|
||
const bin = atob(b64);
|
||
const bytes = new Uint8Array(bin.length);
|
||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||
return bytes.buffer;
|
||
}
|
||
|
||
async function loadPasskeysList() {
|
||
const tbody = $('passkeyTableBody');
|
||
const alertEl = $('passkeySupportAlert');
|
||
if (!tbody) return;
|
||
if (!window.PublicKeyCredential) {
|
||
if (alertEl) {
|
||
alertEl.style.display = 'block';
|
||
alertEl.innerHTML = t('passkey_not_supported_alert', '⚠️ Votre navigateur ne supporte pas l’API WebAuthn / Passkeys ou vous êtes en connexion non sécurisée (HTTPS ou localhost requis).');
|
||
}
|
||
tbody.innerHTML = '<tr><td colspan="4" class="empty" style="color:var(--muted)">' + t('passkey_not_supported_row', 'Navigateur ou contexte non compatible avec WebAuthn') + '</td></tr>';
|
||
return;
|
||
}
|
||
if (alertEl) alertEl.style.display = 'none';
|
||
|
||
try {
|
||
const res = await apiFetch('/api/auth/passkey/list', { cache: 'no-store' });
|
||
const data = await res.json();
|
||
if (!res.ok) throw new Error(data.error || 'Erreur chargement');
|
||
const list = data.passkeys || [];
|
||
window.passkeysById = {};
|
||
list.forEach(pk => { window.passkeysById[pk.id] = pk; });
|
||
if (!list.length) {
|
||
tbody.innerHTML = '<tr><td colspan="4" class="empty" style="padding:22px;text-align:center">' + t('passkey_empty', 'Aucune Passkey enregistrée pour le moment. Cliquez sur « ➕ Enregistrer une nouvelle Passkey » ci-dessus pour associer votre empreinte (Touch ID / Windows Hello), Face ID ou clé physique (YubiKey).') + '</td></tr>';
|
||
return;
|
||
}
|
||
tbody.innerHTML = list.map(pk => `
|
||
<tr>
|
||
<td>
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<span style="font-size:20px">🔑</span>
|
||
<div>
|
||
<div style="display:flex;align-items:center;gap:6px">
|
||
<strong style="font-size:14px">${escapeHtml(pk.name || 'Passkey')}</strong>
|
||
<button class="secondary" type="button" title="${t('rename_passkey_tooltip', 'Renommer cette clé de sécurité')}" style="padding:2px 6px;font-size:11px;line-height:1;border-radius:4px;cursor:pointer" onclick="renamePasskey('${escapeHtml(pk.id)}')">✏️</button>
|
||
</div>
|
||
<div class="muted" style="font-size:11px">${t('passkey_biometric_desc', 'Sécurité biométrique / FIDO2')}</div>
|
||
</div>
|
||
</div>
|
||
</td>
|
||
<td><span style="font-size:13px">${escapeHtml(pk.created_at || '—')}</span></td>
|
||
<td><span style="font-size:13px">${escapeHtml(pk.last_used_at || t('passkey_never', 'Jamais'))}</span></td>
|
||
<td style="text-align:right">
|
||
<div style="display:inline-flex;gap:6px;justify-content:flex-end">
|
||
<button class="secondary" type="button" style="padding:4px 9px;font-size:12px;display:inline-flex;align-items:center;gap:4px" onclick="renamePasskey('${escapeHtml(pk.id)}')">✏️ ${t('btn_rename', 'Renommer')}</button>
|
||
<button class="secondary" type="button" style="padding:4px 9px;font-size:12px;color:var(--red);display:inline-flex;align-items:center;gap:4px" onclick="deletePasskey('${escapeHtml(pk.id)}')">🗑️ ${t('btn_delete', 'Supprimer')}</button>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
`).join('');
|
||
} catch (e) {
|
||
tbody.innerHTML = '<tr><td colspan="4" class="empty" style="color:var(--red)">' + t('passkey_load_failed', 'Impossible de charger les Passkeys') + ' (' + escapeHtml(e.message) + ')</td></tr>';
|
||
}
|
||
}
|
||
|
||
async function registerPasskey() {
|
||
const msgEl = $('passkeyMessage');
|
||
if (msgEl) { msgEl.textContent = ''; msgEl.style.color = 'var(--muted)'; }
|
||
if (!window.PublicKeyCredential) {
|
||
alert(t('passkey_https_alert', 'Les Passkeys nécessitent un navigateur moderne et un contexte sécurisé (HTTPS ou localhost).'));
|
||
return;
|
||
}
|
||
const defaultName = 'Passkey ' + (navigator.platform ? navigator.platform.split(' ')[0] : t('device', 'Appareil'));
|
||
const name = prompt(t('passkey_register_prompt', 'Donnez un nom à cette Passkey (ex: MacBook Touch ID, iPhone Face ID, YubiKey 5C) :'), defaultName);
|
||
if (!name || !name.trim()) return;
|
||
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--blue)';
|
||
msgEl.textContent = t('passkey_waiting_validation', 'En attente de votre validation biométrique ou physique sur votre appareil…');
|
||
}
|
||
try {
|
||
const optRes = await apiFetch('/api/auth/passkey/register/options', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
|
||
const optData = await optRes.json();
|
||
if (!optRes.ok) throw new Error(optData.error || 'Erreur options');
|
||
|
||
const cred = await navigator.credentials.create({
|
||
publicKey: {
|
||
...optData,
|
||
challenge: base64UrlToBuffer(optData.challenge),
|
||
user: {
|
||
...optData.user,
|
||
id: base64UrlToBuffer(optData.user.id)
|
||
}
|
||
}
|
||
});
|
||
|
||
const verifyPayload = {
|
||
id: cred.id,
|
||
rawId: bufferToBase64Url(cred.rawId),
|
||
type: cred.type,
|
||
name: name.trim(),
|
||
response: {
|
||
clientDataJSON: bufferToBase64Url(cred.response.clientDataJSON),
|
||
attestationObject: bufferToBase64Url(cred.response.attestationObject)
|
||
}
|
||
};
|
||
|
||
const verRes = await apiFetch('/api/auth/passkey/register/verify', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(verifyPayload)
|
||
});
|
||
const verData = await verRes.json();
|
||
if (!verRes.ok) throw new Error(verData.error || 'Vérification échouée');
|
||
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--green)';
|
||
msgEl.textContent = tMsg(verData.message || 'Passkey enregistrée avec succès !');
|
||
}
|
||
await loadPasskeysList();
|
||
} catch (e) {
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--red)';
|
||
msgEl.textContent = tErr(e.message || 'Erreur d’enregistrement Passkey');
|
||
}
|
||
}
|
||
}
|
||
|
||
async function renamePasskey(id) {
|
||
const pk = (window.passkeysById && window.passkeysById[id]) || {};
|
||
const currentName = pk.name || 'Passkey';
|
||
const newName = prompt(t('passkey_rename_prompt', 'Entrez le nouveau nom de la clé de sécurité :'), currentName);
|
||
if (newName === null) return;
|
||
const trimmed = newName.trim();
|
||
if (!trimmed) {
|
||
alert(t('passkey_rename_empty_alert', 'Le nom de la clé de sécurité ne peut pas être vide.'));
|
||
return;
|
||
}
|
||
if (trimmed === currentName) return;
|
||
const msgEl = $('passkeyMessage');
|
||
if (msgEl) { msgEl.textContent = t('passkey_rename_saving', 'Enregistrement du nouveau nom…'); msgEl.style.color = 'var(--muted)'; }
|
||
try {
|
||
const res = await apiFetch('/api/auth/passkey/rename', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ id, name: trimmed })
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur lors du renommage');
|
||
if (msgEl) {
|
||
msgEl.textContent = '✅ ' + (d.message || t('passkey_renamed_success', 'Clé renommée avec succès !'));
|
||
msgEl.style.color = 'var(--green)';
|
||
setTimeout(() => { if (msgEl && (msgEl.textContent.includes('succès') || msgEl.textContent.includes('successfully'))) msgEl.textContent = ''; }, 3500);
|
||
}
|
||
await loadPasskeysList();
|
||
} catch (e) {
|
||
if (msgEl) {
|
||
msgEl.textContent = '❌ ' + tErr(e.message);
|
||
msgEl.style.color = 'var(--red)';
|
||
} else {
|
||
alert(tErr(e.message));
|
||
}
|
||
}
|
||
}
|
||
|
||
async function deletePasskey(id, fallbackName) {
|
||
const pk = (window.passkeysById && window.passkeysById[id]) || {};
|
||
const name = pk.name || fallbackName || 'Passkey';
|
||
const confirmMsg = t('passkey_delete_confirm', "Êtes-vous sûr de vouloir supprimer la Passkey « {name} » ?").replace('{name}', name);
|
||
if (!confirm(confirmMsg)) return;
|
||
try {
|
||
const res = await apiFetch('/api/auth/passkey/delete', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ id })
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur suppression');
|
||
await loadPasskeysList();
|
||
} catch (e) {
|
||
alert(tErr(e.message));
|
||
}
|
||
}
|
||
|
||
async function loginWithPasskey() {
|
||
const msgEl = $('authMessage');
|
||
if (msgEl) { msgEl.textContent = ''; msgEl.style.color = 'var(--muted)'; }
|
||
if (!window.PublicKeyCredential) {
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--red)';
|
||
msgEl.textContent = t('passkey_https_alert', 'Les Passkeys nécessitent un navigateur moderne et un contexte sécurisé (HTTPS ou localhost).');
|
||
}
|
||
return;
|
||
}
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--blue)';
|
||
msgEl.textContent = t('passkey_waiting_validation', 'Présentez votre empreinte (Touch ID), votre visage (Face ID) ou touchez votre clé…');
|
||
}
|
||
try {
|
||
const optRes = await fetch(API_URL + '/api/auth/passkey/login/options', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: '{}'
|
||
});
|
||
const optData = await optRes.json();
|
||
if (!optRes.ok) throw new Error(optData.error || 'Erreur options');
|
||
|
||
const allowCreds = (optData.allowCredentials || []).map(c => ({
|
||
...c,
|
||
id: base64UrlToBuffer(c.id)
|
||
}));
|
||
|
||
const assertion = await navigator.credentials.get({
|
||
publicKey: {
|
||
challenge: base64UrlToBuffer(optData.challenge),
|
||
rpId: optData.rpId,
|
||
timeout: optData.timeout || 60000,
|
||
userVerification: optData.userVerification || 'preferred',
|
||
allowCredentials: allowCreds.length ? allowCreds : undefined
|
||
}
|
||
});
|
||
|
||
const devName = localStorage.getItem('apDeviceName') || '';
|
||
const verifyPayload = {
|
||
id: assertion.id,
|
||
rawId: bufferToBase64Url(assertion.rawId),
|
||
type: assertion.type,
|
||
device_name: devName,
|
||
response: {
|
||
clientDataJSON: bufferToBase64Url(assertion.response.clientDataJSON),
|
||
authenticatorData: bufferToBase64Url(assertion.response.authenticatorData),
|
||
signature: bufferToBase64Url(assertion.response.signature),
|
||
userHandle: assertion.response.userHandle ? bufferToBase64Url(assertion.response.userHandle) : null
|
||
}
|
||
};
|
||
|
||
const verRes = await fetch(API_URL + '/api/auth/passkey/login/verify', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(verifyPayload)
|
||
});
|
||
const verData = await verRes.json();
|
||
if (!verRes.ok) throw new Error(verData.error || 'Connexion Passkey refusée');
|
||
|
||
// Authentification réussie sans mot de passe et sans double vérification !
|
||
authToken = verData.token;
|
||
sessionStorage.setItem('apAuthToken', authToken);
|
||
localStorage.setItem('apAuthToken', authToken);
|
||
saveAuthCookie(authToken);
|
||
currentTab = 'dashboard'; sessionStorage.setItem('apDashboardTab', 'dashboard');
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--green)';
|
||
msgEl.textContent = verData.message ? tMsg(verData.message) : t('passkey_auth_success', 'Authentification Passkey réussie !');
|
||
}
|
||
try {
|
||
await initializeAndShowDashboard(true);
|
||
} catch (_) {
|
||
showApp();
|
||
hideLoaderScreen();
|
||
}
|
||
} catch (e) {
|
||
if (msgEl) {
|
||
msgEl.style.color = 'var(--red)';
|
||
msgEl.textContent = t('passkey_error_prefix', 'Erreur Passkey : ') + tErr(e.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
if ($('btnAddPasskey')) $('btnAddPasskey').onclick = () => runAction(registerPasskey);
|
||
if ($('btnAuthPasskey')) $('btnAuthPasskey').onclick = loginWithPasskey;
|
||
|
||
/* Système de configuration et test des notifications multi-canaux */
|
||
const NOTIF_EVENT_META = {
|
||
new_device: { defaultTitle: "📱 Nouvel appareil détecté", defaultMsg: "L'appareil « {name} » vient de se connecter pour la première fois au réseau Wi-Fi." },
|
||
device_connected: { defaultTitle: "📶 Appareil connecté", defaultMsg: "L'appareil « {name} » s'est connecté au réseau Wi-Fi." },
|
||
device_disconnected: { defaultTitle: "📴 Appareil déconnecté", defaultMsg: "L'appareil « {name} » s'est déconnecté du réseau Wi-Fi." },
|
||
admin_login: { defaultTitle: "🔒 Connexion au compte administrateur", defaultMsg: "Connexion réussie au compte administrateur « {user} »." },
|
||
admin_login_failed: { defaultTitle: "⚠️ Échec de connexion administrateur", defaultMsg: "Une tentative de connexion au compte administrateur a échoué (mot de passe invalide)." },
|
||
device_blocked: { defaultTitle: "🛑 Équipement Wi-Fi bloqué / débloqué", defaultMsg: "L'appareil « {name} » a été {action} le réseau Wi-Fi." },
|
||
settings_changed: { defaultTitle: "⚙️ Modification réglages Wi-Fi / AP", defaultMsg: "Les réglages du point d'accès Wi-Fi ont été modifiés (SSID : {ssid})." },
|
||
vpn_client_connected: { defaultTitle: "🛡️ Client routé via VPN", defaultMsg: "L'appareil « {name} » ({ip}) est désormais connecté et routé via le VPN « {vpn} »." },
|
||
vpn_client_disconnected: { defaultTitle: "🌐 Client déconnecté du VPN", defaultMsg: "L'appareil « {name} » ({ip}) n'est plus routé via le VPN « {vpn} »." },
|
||
vpn_profile_connected: { defaultTitle: "🛡️ Tunnel VPN connecté", defaultMsg: "Le profil VPN « {name} » ({type}) est désormais connecté avec succès (interface {iface})." },
|
||
vpn_profile_disconnected: { defaultTitle: "⚠️ Tunnel VPN déconnecté", defaultMsg: "Le profil VPN « {name} » ({type}) a été déconnecté (interface {iface})." },
|
||
quota_exceeded: { defaultTitle: "⚠️ Quota de données dépassé", defaultMsg: "L'appareil « {name} » ({ip}) a dépassé son quota de {quota} (consommé : {consumption}). L'accès Internet a été coupé." },
|
||
stats_report: { defaultTitle: "📊 Rapport statistiques & métriques Wi‑Fi", defaultMsg: "📊 Rapport Wi‑Fi ({date}) :\n• {clients_count} appareil(s) connecté(s) (↓ {traffic_down} • ↑ {traffic_up})\n• Aujourd'hui : {today_unique} visiteur(s) unique(s) ({today_total} sessions)\n• Cette semaine : {week_unique} unique(s) | Ce mois : {month_unique} unique(s)\n• VPN : {active_vpns} tunnel(s) actif(s) ({vpn_routed_clients} appareil(s) routé(s))\n• Passerelle WAN : {gateway_status} ({gateway_ip})\n• Top clients (Consommation de données) :\n{top_clients}" },
|
||
backup_success: { defaultTitle: "💾 Sauvegarde créée avec succès", defaultMsg: "La sauvegarde « {filename} » ({size}) a été créée avec succès ({trigger})." },
|
||
backup_remote_success: { defaultTitle: "☁️ Sauvegarde téléversée sur le stockage distant", defaultMsg: "La sauvegarde « {filename} » ({size}) a été téléversée avec succès sur {provider} ({host})." }
|
||
};
|
||
|
||
function insertNotifVariable(ev, varName) {
|
||
const msgEl = $('notifTmplMsg_' + ev);
|
||
if (!msgEl) return;
|
||
const start = msgEl.selectionStart || msgEl.value.length;
|
||
const end = msgEl.selectionEnd || msgEl.value.length;
|
||
const old = msgEl.value;
|
||
msgEl.value = old.substring(0, start) + varName + old.substring(end);
|
||
msgEl.focus();
|
||
const pos = start + varName.length;
|
||
msgEl.setSelectionRange(pos, pos);
|
||
}
|
||
|
||
function resetNotificationTemplate(ev) {
|
||
const meta = NOTIF_EVENT_META[ev];
|
||
if (!meta) return;
|
||
const titleEl = $('notifTmplTitle_' + ev);
|
||
const msgEl = $('notifTmplMsg_' + ev);
|
||
if (titleEl) titleEl.value = meta.defaultTitle;
|
||
if (msgEl) msgEl.value = meta.defaultMsg;
|
||
}
|
||
|
||
let notifTemplatesAllOpen = false;
|
||
function toggleAllNotifTemplates() {
|
||
notifTemplatesAllOpen = !notifTemplatesAllOpen;
|
||
document.querySelectorAll('.notif-tmpl-item').forEach(d => { d.open = notifTemplatesAllOpen; });
|
||
const icon = $('notifTmplToggleIcon');
|
||
const txt = $('notifTmplToggleText');
|
||
if (icon) icon.textContent = notifTemplatesAllOpen ? '▴' : '▾';
|
||
if (txt) txt.textContent = notifTemplatesAllOpen ? 'Tout replier' : 'Tout déplier';
|
||
}
|
||
|
||
function toggleNotifFields(type) {
|
||
const types = ['email', 'gotify', 'discord', 'ntfy', 'pushbullet', 'pushover', 'slack', 'telegram', 'webhook'];
|
||
const target = type ? ([type]) : types;
|
||
target.forEach(t => {
|
||
const cap = t.charAt(0).toUpperCase() + t.slice(1);
|
||
const en = $('notif' + cap + 'Enabled')?.checked;
|
||
const f = $('notif' + cap + 'Fields');
|
||
if (f) f.style.display = en ? 'block' : 'none';
|
||
});
|
||
}
|
||
|
||
function toggleStatsReportSchedule(isEn) {
|
||
const box = $('statsReportScheduleBox');
|
||
if (box) box.style.display = isEn ? 'block' : 'none';
|
||
}
|
||
|
||
function initStatsReportTimeSelects() {
|
||
const hSel = $('statsReportHour');
|
||
const mSel = $('statsReportMinute');
|
||
if (hSel && hSel.options.length <= 1) {
|
||
let hHtml = '<option value="*">Toutes les heures (*)</option>';
|
||
for (let i = 0; i < 24; i++) {
|
||
const v = String(i).padStart(2, '0');
|
||
hHtml += `<option value="${i}">${v}h (${v}:00)</option>`;
|
||
}
|
||
hSel.innerHTML = hHtml;
|
||
}
|
||
if (mSel && mSel.options.length <= 1) {
|
||
let mHtml = '';
|
||
for (let i = 0; i < 60; i++) {
|
||
const v = String(i).padStart(2, '0');
|
||
mHtml += `<option value="${i}">${v} min (:${v})</option>`;
|
||
}
|
||
mSel.innerHTML = mHtml;
|
||
}
|
||
}
|
||
|
||
function updateStatsReportCronFromFields() {
|
||
const d = $('statsReportDay')?.value || '*';
|
||
const h = $('statsReportHour')?.value || '8';
|
||
const m = $('statsReportMinute')?.value || '0';
|
||
const expr = `${m} ${h} * * ${d}`;
|
||
if ($('statsReportCronExpr')) $('statsReportCronExpr').value = expr;
|
||
updateStatsReportHumanSummary(expr);
|
||
}
|
||
|
||
function updateStatsReportFieldsFromCron() {
|
||
const expr = $('statsReportCronExpr')?.value?.trim() || '0 8 * * *';
|
||
const parts = expr.split(/\s+/);
|
||
if (parts.length === 5) {
|
||
const [minPart, hourPart, domPart, monthPart, dowPart] = parts;
|
||
if ($('statsReportMinute') && $('statsReportMinute').querySelector(`option[value="${minPart}"]`)) {
|
||
$('statsReportMinute').value = minPart;
|
||
}
|
||
if ($('statsReportHour') && $('statsReportHour').querySelector(`option[value="${hourPart}"]`)) {
|
||
$('statsReportHour').value = hourPart;
|
||
}
|
||
if ($('statsReportDay') && $('statsReportDay').querySelector(`option[value="${dowPart}"]`)) {
|
||
$('statsReportDay').value = dowPart;
|
||
}
|
||
}
|
||
updateStatsReportHumanSummary(expr);
|
||
}
|
||
|
||
function updateStatsReportHumanSummary(expr) {
|
||
const humanBadge = $('statsReportCronHuman');
|
||
if (!humanBadge) return;
|
||
const parts = expr.trim().split(/\s+/);
|
||
if (parts.length !== 5) {
|
||
humanBadge.textContent = '⚙️ Cron : ' + expr;
|
||
return;
|
||
}
|
||
const [minPart, hourPart, domPart, monthPart, dowPart] = parts;
|
||
const daysMap = {
|
||
'*': t('stats_cron_day_all_short', 'Tous les jours'),
|
||
'1-5': t('stats_cron_day_workdays_short', 'Jours ouvrés (Lun-Ven)'),
|
||
'6,7': t('stats_cron_day_weekend_short', 'Week-end (Sam-Dim)'),
|
||
'1': t('stats_cron_day_mon', 'Chaque Lundi'),
|
||
'2': t('stats_cron_day_tue', 'Chaque Mardi'),
|
||
'3': t('stats_cron_day_wed', 'Chaque Mercredi'),
|
||
'4': t('stats_cron_day_thu', 'Chaque Jeudi'),
|
||
'5': t('stats_cron_day_fri', 'Chaque Vendredi'),
|
||
'6': t('stats_cron_day_sat', 'Chaque Samedi'),
|
||
'0': t('stats_cron_day_sun', 'Chaque Dimanche'),
|
||
'7': t('stats_cron_day_sun', 'Chaque Dimanche')
|
||
};
|
||
const dStr = daysMap[dowPart] || (t('stats_cron_day_prefix', 'Jour ') + dowPart);
|
||
let timeStr = '';
|
||
if (hourPart === '*') {
|
||
timeStr = t('stats_cron_hourly_at', 'toutes les heures à :{min}').replace('{min}', String(minPart).padStart(2, '0'));
|
||
} else {
|
||
timeStr = t('stats_cron_at_time', 'à {time}').replace('{time}', `${String(hourPart).padStart(2, '0')}:${String(minPart).padStart(2, '0')}`);
|
||
}
|
||
humanBadge.textContent = `📅 ${dStr} ${timeStr}`;
|
||
}
|
||
|
||
async function triggerManualStatsReport() {
|
||
const triggerMsg = $('statsReportTriggerMsg');
|
||
if (triggerMsg) {
|
||
triggerMsg.style.display = 'block';
|
||
triggerMsg.textContent = t('stats_report_sending', '⏳ Envoi du rapport statistiques en cours…');
|
||
triggerMsg.style.color = 'var(--blue)';
|
||
}
|
||
try {
|
||
const res = await apiFetch('/api/notifications/stats-report/trigger', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({})
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur lors de l’envoi');
|
||
if (triggerMsg) {
|
||
triggerMsg.textContent = '✅ ' + tMsg(d.message || 'Rapport envoyé avec succès !');
|
||
triggerMsg.style.color = 'var(--green)';
|
||
setTimeout(() => { if (triggerMsg) triggerMsg.style.display = 'none'; }, 5000);
|
||
}
|
||
} catch (e) {
|
||
if (triggerMsg) {
|
||
triggerMsg.textContent = '❌ ' + tErr(e.message);
|
||
triggerMsg.style.color = 'var(--red)';
|
||
}
|
||
}
|
||
}
|
||
|
||
async function loadNotificationSettings() {
|
||
try {
|
||
const res = await apiFetch('/api/notifications/settings');
|
||
if (!res.ok) return;
|
||
const cfg = await res.json();
|
||
|
||
const evts = cfg.events || {};
|
||
if ($('notifEvtNewDevice')) $('notifEvtNewDevice').checked = !!evts.new_device;
|
||
if ($('notifEvtDeviceConnected')) $('notifEvtDeviceConnected').checked = !!evts.device_connected;
|
||
if ($('notifEvtDeviceDisconnected')) $('notifEvtDeviceDisconnected').checked = !!evts.device_disconnected;
|
||
if ($('notifEvtAdminLogin')) $('notifEvtAdminLogin').checked = !!evts.admin_login;
|
||
if ($('notifEvtAdminLoginFailed')) $('notifEvtAdminLoginFailed').checked = !!evts.admin_login_failed;
|
||
if ($('notifEvtDeviceBlocked')) $('notifEvtDeviceBlocked').checked = !!evts.device_blocked;
|
||
if ($('notifEvtSettingsChanged')) $('notifEvtSettingsChanged').checked = !!evts.settings_changed;
|
||
if ($('notifEvtVpnClientConnected')) $('notifEvtVpnClientConnected').checked = !!evts.vpn_client_connected;
|
||
if ($('notifEvtVpnClientDisconnected')) $('notifEvtVpnClientDisconnected').checked = !!evts.vpn_client_disconnected;
|
||
if ($('notifEvtVpnProfileConnected')) $('notifEvtVpnProfileConnected').checked = !!evts.vpn_profile_connected;
|
||
if ($('notifEvtVpnProfileDisconnected')) $('notifEvtVpnProfileDisconnected').checked = !!evts.vpn_profile_disconnected;
|
||
if ($('notifEvtQuotaExceeded')) $('notifEvtQuotaExceeded').checked = evts.quota_exceeded !== undefined ? !!evts.quota_exceeded : true;
|
||
if ($('notifEvtBackupSuccess')) $('notifEvtBackupSuccess').checked = evts.backup_success !== undefined ? !!evts.backup_success : true;
|
||
if ($('notifEvtBackupRemoteSuccess')) $('notifEvtBackupRemoteSuccess').checked = evts.backup_remote_success !== undefined ? !!evts.backup_remote_success : true;
|
||
|
||
const sched = cfg.stats_report_schedule || {};
|
||
const isStatsRep = !!(evts.stats_report || sched.enabled);
|
||
if ($('notifEvtStatsReport')) $('notifEvtStatsReport').checked = isStatsRep;
|
||
initStatsReportTimeSelects();
|
||
toggleStatsReportSchedule(isStatsRep);
|
||
const cronExpr = sched.cron_expr || (sched.minute !== undefined ? `${sched.minute} ${sched.hour} * * ${sched.day || '*'}` : '0 8 * * *');
|
||
if ($('statsReportCronExpr')) $('statsReportCronExpr').value = cronExpr;
|
||
if ($('statsReportTopRange')) $('statsReportTopRange').value = sched.top_range || 'day';
|
||
updateStatsReportFieldsFromCron();
|
||
|
||
const em = cfg.email || {};
|
||
if ($('notifEmailEnabled')) $('notifEmailEnabled').checked = !!em.enabled;
|
||
if ($('notifEmailHost')) $('notifEmailHost').value = em.smtp_host || '';
|
||
if ($('notifEmailPort')) $('notifEmailPort').value = em.smtp_port || 587;
|
||
if ($('notifEmailSecure')) $('notifEmailSecure').value = em.smtp_secure || 'starttls';
|
||
if ($('notifEmailUser')) $('notifEmailUser').value = em.smtp_user || '';
|
||
if ($('notifEmailPass')) {
|
||
$('notifEmailPass').value = '';
|
||
$('notifEmailPass').placeholder = em.smtp_pass_set ? '•••••••• (Mot de passe déjà enregistré)' : 'Mot de passe SMTP';
|
||
}
|
||
if ($('notifEmailFrom')) $('notifEmailFrom').value = em.from_addr || '';
|
||
if ($('notifEmailTo')) $('notifEmailTo').value = em.to_addr || '';
|
||
|
||
const got = cfg.gotify || {};
|
||
if ($('notifGotifyEnabled')) $('notifGotifyEnabled').checked = !!got.enabled;
|
||
if ($('notifGotifyUrl')) $('notifGotifyUrl').value = got.server_url || '';
|
||
if ($('notifGotifyToken')) $('notifGotifyToken').value = got.token || '';
|
||
if ($('notifGotifyPriority')) $('notifGotifyPriority').value = got.priority || 5;
|
||
|
||
const dis = cfg.discord || {};
|
||
if ($('notifDiscordEnabled')) $('notifDiscordEnabled').checked = !!dis.enabled;
|
||
if ($('notifDiscordWebhook')) $('notifDiscordWebhook').value = dis.webhook_url || '';
|
||
if ($('notifDiscordBotName')) $('notifDiscordBotName').value = dis.bot_name || 'AP Manageur';
|
||
|
||
const tmpls = cfg.templates || {};
|
||
for (const [ev, meta] of Object.entries(NOTIF_EVENT_META)) {
|
||
const t = tmpls[ev] || {};
|
||
const titleEl = $('notifTmplTitle_' + ev);
|
||
const msgEl = $('notifTmplMsg_' + ev);
|
||
if (titleEl) titleEl.value = (t.title !== undefined && t.title !== '') ? t.title : meta.defaultTitle;
|
||
if (msgEl) msgEl.value = (t.message !== undefined && t.message !== '') ? t.message : meta.defaultMsg;
|
||
}
|
||
|
||
const ntf = cfg.ntfy || {};
|
||
if ($('notifNtfyEnabled')) $('notifNtfyEnabled').checked = !!ntf.enabled;
|
||
if ($('notifNtfyUrl')) $('notifNtfyUrl').value = ntf.server_url || 'https://ntfy.sh';
|
||
if ($('notifNtfyTopic')) $('notifNtfyTopic').value = ntf.topic || '';
|
||
if ($('notifNtfyToken')) $('notifNtfyToken').value = ntf.token || '';
|
||
if ($('notifNtfyPriority')) $('notifNtfyPriority').value = ntf.priority || 3;
|
||
|
||
const pb = cfg.pushbullet || {};
|
||
if ($('notifPushbulletEnabled')) $('notifPushbulletEnabled').checked = !!pb.enabled;
|
||
if ($('notifPushbulletToken')) $('notifPushbulletToken').value = pb.api_token || '';
|
||
if ($('notifPushbulletDevice')) $('notifPushbulletDevice').value = pb.device_iden || '';
|
||
|
||
const po = cfg.pushover || {};
|
||
if ($('notifPushoverEnabled')) $('notifPushoverEnabled').checked = !!po.enabled;
|
||
if ($('notifPushoverUser')) $('notifPushoverUser').value = po.user_key || '';
|
||
if ($('notifPushoverToken')) $('notifPushoverToken').value = po.api_token || '';
|
||
if ($('notifPushoverPriority')) $('notifPushoverPriority').value = po.priority !== undefined ? po.priority : 0;
|
||
|
||
const sl = cfg.slack || {};
|
||
if ($('notifSlackEnabled')) $('notifSlackEnabled').checked = !!sl.enabled;
|
||
if ($('notifSlackWebhook')) $('notifSlackWebhook').value = sl.webhook_url || '';
|
||
if ($('notifSlackBotName')) $('notifSlackBotName').value = sl.bot_name || 'AP Manageur';
|
||
|
||
const tg = cfg.telegram || {};
|
||
if ($('notifTelegramEnabled')) $('notifTelegramEnabled').checked = !!tg.enabled;
|
||
if ($('notifTelegramToken')) $('notifTelegramToken').value = tg.bot_token || '';
|
||
if ($('notifTelegramChatId')) $('notifTelegramChatId').value = tg.chat_id || '';
|
||
if ($('notifTelegramThreadId')) $('notifTelegramThreadId').value = tg.thread_id || '';
|
||
|
||
const wh = cfg.webhook || {};
|
||
if ($('notifWebhookEnabled')) $('notifWebhookEnabled').checked = !!wh.enabled;
|
||
if ($('notifWebhookUrl')) $('notifWebhookUrl').value = wh.url || '';
|
||
if ($('notifWebhookMethod')) $('notifWebhookMethod').value = wh.method || 'POST';
|
||
if ($('notifWebhookHeaders')) $('notifWebhookHeaders').value = wh.headers || '';
|
||
|
||
toggleNotifFields();
|
||
} catch (e) {
|
||
console.warn('Erreur chargement réglages notifications:', e);
|
||
}
|
||
}
|
||
|
||
function getNotificationFormPayload() {
|
||
return {
|
||
events: {
|
||
new_device: $('notifEvtNewDevice')?.checked || false,
|
||
device_connected: $('notifEvtDeviceConnected')?.checked || false,
|
||
device_disconnected: $('notifEvtDeviceDisconnected')?.checked || false,
|
||
admin_login: $('notifEvtAdminLogin')?.checked || false,
|
||
admin_login_failed: $('notifEvtAdminLoginFailed')?.checked || false,
|
||
device_blocked: $('notifEvtDeviceBlocked')?.checked || false,
|
||
settings_changed: $('notifEvtSettingsChanged')?.checked || false,
|
||
vpn_client_connected: $('notifEvtVpnClientConnected')?.checked || false,
|
||
vpn_client_disconnected: $('notifEvtVpnClientDisconnected')?.checked || false,
|
||
vpn_profile_connected: $('notifEvtVpnProfileConnected')?.checked || false,
|
||
vpn_profile_disconnected: $('notifEvtVpnProfileDisconnected')?.checked || false,
|
||
quota_exceeded: $('notifEvtQuotaExceeded')?.checked ?? true,
|
||
backup_success: $('notifEvtBackupSuccess')?.checked ?? true,
|
||
backup_remote_success: $('notifEvtBackupRemoteSuccess')?.checked ?? true,
|
||
stats_report: $('notifEvtStatsReport')?.checked || false
|
||
},
|
||
stats_report_schedule: {
|
||
enabled: $('notifEvtStatsReport')?.checked || false,
|
||
day: $('statsReportDay')?.value || '*',
|
||
hour: parseInt($('statsReportHour')?.value || '8', 10),
|
||
minute: parseInt($('statsReportMinute')?.value || '0', 10),
|
||
cron_expr: $('statsReportCronExpr')?.value?.trim() || '0 8 * * *',
|
||
top_range: $('statsReportTopRange')?.value || 'day'
|
||
},
|
||
email: {
|
||
enabled: $('notifEmailEnabled')?.checked || false,
|
||
smtp_host: $('notifEmailHost')?.value?.trim() || '',
|
||
smtp_port: parseInt($('notifEmailPort')?.value || '587', 10) || 587,
|
||
smtp_secure: $('notifEmailSecure')?.value || 'starttls',
|
||
smtp_user: $('notifEmailUser')?.value?.trim() || '',
|
||
smtp_pass: $('notifEmailPass')?.value || '',
|
||
from_addr: $('notifEmailFrom')?.value?.trim() || '',
|
||
to_addr: $('notifEmailTo')?.value?.trim() || ''
|
||
},
|
||
gotify: {
|
||
enabled: $('notifGotifyEnabled')?.checked || false,
|
||
server_url: $('notifGotifyUrl')?.value?.trim() || '',
|
||
token: $('notifGotifyToken')?.value?.trim() || '',
|
||
priority: parseInt($('notifGotifyPriority')?.value || '5', 10) || 5
|
||
},
|
||
discord: {
|
||
enabled: $('notifDiscordEnabled')?.checked || false,
|
||
webhook_url: $('notifDiscordWebhook')?.value?.trim() || '',
|
||
bot_name: $('notifDiscordBotName')?.value?.trim() || 'AP Manageur'
|
||
},
|
||
ntfy: {
|
||
enabled: $('notifNtfyEnabled')?.checked || false,
|
||
server_url: $('notifNtfyUrl')?.value?.trim() || 'https://ntfy.sh',
|
||
topic: $('notifNtfyTopic')?.value?.trim() || '',
|
||
token: $('notifNtfyToken')?.value?.trim() || '',
|
||
priority: parseInt($('notifNtfyPriority')?.value || '3', 10) || 3
|
||
},
|
||
pushbullet: {
|
||
enabled: $('notifPushbulletEnabled')?.checked || false,
|
||
api_token: $('notifPushbulletToken')?.value?.trim() || '',
|
||
device_iden: $('notifPushbulletDevice')?.value?.trim() || ''
|
||
},
|
||
pushover: {
|
||
enabled: $('notifPushoverEnabled')?.checked || false,
|
||
user_key: $('notifPushoverUser')?.value?.trim() || '',
|
||
api_token: $('notifPushoverToken')?.value?.trim() || '',
|
||
priority: parseInt($('notifPushoverPriority')?.value || '0', 10) || 0
|
||
},
|
||
slack: {
|
||
enabled: $('notifSlackEnabled')?.checked || false,
|
||
webhook_url: $('notifSlackWebhook')?.value?.trim() || '',
|
||
bot_name: $('notifSlackBotName')?.value?.trim() || 'AP Manageur'
|
||
},
|
||
telegram: {
|
||
enabled: $('notifTelegramEnabled')?.checked || false,
|
||
bot_token: $('notifTelegramToken')?.value?.trim() || '',
|
||
chat_id: $('notifTelegramChatId')?.value?.trim() || '',
|
||
thread_id: $('notifTelegramThreadId')?.value?.trim() || ''
|
||
},
|
||
webhook: {
|
||
enabled: $('notifWebhookEnabled')?.checked || false,
|
||
url: $('notifWebhookUrl')?.value?.trim() || '',
|
||
method: $('notifWebhookMethod')?.value || 'POST',
|
||
headers: $('notifWebhookHeaders')?.value?.trim() || ''
|
||
},
|
||
templates: (function () {
|
||
const t = {};
|
||
for (const ev of Object.keys(NOTIF_EVENT_META)) {
|
||
const titleEl = $('notifTmplTitle_' + ev);
|
||
const msgEl = $('notifTmplMsg_' + ev);
|
||
if (titleEl && msgEl) {
|
||
t[ev] = {
|
||
title: titleEl.value.trim(),
|
||
message: msgEl.value.trim()
|
||
};
|
||
}
|
||
}
|
||
return t;
|
||
})()
|
||
};
|
||
}
|
||
|
||
async function saveNotificationSettings() {
|
||
const msg = $('notifMessage');
|
||
if (msg) { msg.textContent = t('loading', 'Enregistrement en cours…'); msg.style.color = 'var(--muted)'; }
|
||
try {
|
||
const payload = getNotificationFormPayload();
|
||
const res = await apiFetch('/api/notifications/settings', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(payload)
|
||
});
|
||
const data = await res.json();
|
||
if (!res.ok) throw Error(data.error || 'Erreur lors de l’enregistrement');
|
||
if (msg) { msg.textContent = tMsg(data.message || 'Réglages enregistrés avec succès !'); msg.style.color = 'var(--green)'; }
|
||
await loadNotificationSettings();
|
||
setTimeout(() => { if (msg && (msg.textContent.includes('succès') || msg.textContent.includes('successfully'))) msg.textContent = ''; }, 3500);
|
||
} catch (e) {
|
||
if (msg) { msg.textContent = tErr(e.message); msg.style.color = 'var(--red)'; }
|
||
}
|
||
}
|
||
|
||
async function testNotificationChannel(channel) {
|
||
const detailsBox = $('notifTestDetails');
|
||
const msg = $('notifMessage');
|
||
if (detailsBox) detailsBox.innerHTML = `<div style="font-size:13px;color:var(--blue);padding:8px;background:var(--panel);border:1px solid var(--line);border-radius:8px">${t('notif_testing_progress', '⏳ Envoi de la notification de test en cours…')}</div>`;
|
||
if (msg) { msg.textContent = t('notif_testing_btn', 'Test en cours…'); msg.style.color = 'var(--muted)'; }
|
||
try {
|
||
const payload = {
|
||
channel: channel,
|
||
config: getNotificationFormPayload()
|
||
};
|
||
const res = await apiFetch('/api/notifications/test', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(payload)
|
||
});
|
||
const data = await res.json();
|
||
if (!res.ok) throw Error(data.error || 'Erreur lors du test');
|
||
|
||
const results = data.results || {};
|
||
let html = '<div style="display:flex;flex-direction:column;gap:8px;margin-top:6px">';
|
||
let allOk = true;
|
||
const labels = { email: '✉️ Email SMTP', gotify: '🔔 Gotify', discord: '🎮 Discord Webhook', ntfy: '📢 ntfy.sh', pushbullet: '📱 Pushbullet', pushover: '📣 Pushover', slack: '💼 Slack Webhook', telegram: '✈️ Telegram Bot', webhook: '🌐 Webhook personnalisé', general: 'ℹ️ Information' };
|
||
|
||
for (const [ch, info] of Object.entries(results)) {
|
||
const chName = labels[ch] || ch;
|
||
if (info.ok) {
|
||
html += `<div style="font-size:13px;color:var(--green);background:rgba(50,213,131,0.1);border:1px solid rgba(50,213,131,0.3);padding:8px 12px;border-radius:8px;display:flex;align-items:center;gap:8px"><span>✅</span> <strong>${chName} :</strong> ${tMsg(info.message)}</div>`;
|
||
} else {
|
||
allOk = false;
|
||
html += `<div style="font-size:13px;color:var(--red);background:rgba(255,107,107,0.1);border:1px solid rgba(255,107,107,0.3);padding:8px 12px;border-radius:8px;display:flex;align-items:center;gap:8px"><span>❌</span> <strong>${chName} :</strong> ${tErr(info.error)}</div>`;
|
||
}
|
||
}
|
||
html += '</div>';
|
||
if (detailsBox) detailsBox.innerHTML = html;
|
||
if (msg) {
|
||
msg.textContent = allOk ? t('notif_test_success', 'Test réussi !') : t('notif_test_partial_failure', 'Certains tests ont échoué');
|
||
msg.style.color = allOk ? 'var(--green)' : 'var(--red)';
|
||
}
|
||
} catch (e) {
|
||
if (detailsBox) detailsBox.innerHTML = `<div style="font-size:13px;color:var(--red);background:rgba(255,107,107,0.1);border:1px solid rgba(255,107,107,0.3);padding:8px 12px;border-radius:8px">${t('notif_test_err', '❌ Erreur lors du test : ')}${tErr(e.message)}</div>`;
|
||
if (msg) { msg.textContent = tErr(e.message); msg.style.color = 'var(--red)'; }
|
||
}
|
||
}
|
||
|
||
async function loadReverseProxySettings() {
|
||
const btn = $('btnRefreshProxyDiag');
|
||
if (btn) { btn.disabled = true; btn.style.opacity = '0.6'; }
|
||
try {
|
||
const res = await apiFetch('/api/settings/proxy');
|
||
if (!res.ok) throw new Error('Erreur HTTP ' + res.status);
|
||
const data = await res.json();
|
||
if (data.ok) {
|
||
if (data.config) {
|
||
const c = data.config;
|
||
if ($('proxyEnabled')) $('proxyEnabled').checked = (c.enabled !== false && c.enabled !== 0 && c.enabled !== '0');
|
||
if ($('proxyHeaderSelect')) $('proxyHeaderSelect').value = c.header || 'auto';
|
||
if ($('proxyTrustPrivate')) $('proxyTrustPrivate').checked = (c.trust_all_private !== false && c.trust_all_private !== 0 && c.trust_all_private !== '0');
|
||
if ($('proxyTrustedIps')) $('proxyTrustedIps').value = Array.isArray(c.trusted_proxies) ? c.trusted_proxies.join(', ') : (c.trusted_proxies || '');
|
||
}
|
||
if (data.detected) {
|
||
const d = data.detected;
|
||
if ($('proxyDiagRealIp')) $('proxyDiagRealIp').textContent = d.real_ip || '—';
|
||
if ($('proxyDiagRawIp')) $('proxyDiagRawIp').textContent = d.raw_direct_ip || d.socket_ip || '—';
|
||
if ($('proxyDiagXff')) $('proxyDiagXff').textContent = d.x_forwarded_for || '—';
|
||
if ($('proxyDiagXri')) $('proxyDiagXri').textContent = d.x_real_ip || '—';
|
||
if ($('proxyDiagCf')) $('proxyDiagCf').textContent = d.cf_connecting_ip || '—';
|
||
if ($('proxyDiagProto')) $('proxyDiagProto').textContent = d.x_forwarded_proto || '—';
|
||
if ($('proxyDiagHost')) $('proxyDiagHost').textContent = d.host || '—';
|
||
}
|
||
}
|
||
} catch (err) {
|
||
console.error('Erreur chargement proxy:', err);
|
||
if ($('proxySettingsMsg')) {
|
||
$('proxySettingsMsg').textContent = '⚠️ Erreur lors de la lecture des réglages proxy.';
|
||
$('proxySettingsMsg').style.color = 'var(--red)';
|
||
}
|
||
} finally {
|
||
if (btn) { btn.disabled = false; btn.style.opacity = '1'; }
|
||
}
|
||
}
|
||
|
||
async function saveReverseProxySettings() {
|
||
const btn = $('btnSaveProxySettings');
|
||
const msg = $('proxySettingsMsg');
|
||
if (btn) { btn.disabled = true; btn.textContent = t('loading', '⏳ Enregistrement…'); }
|
||
if (msg) { msg.textContent = ''; }
|
||
try {
|
||
const payload = {
|
||
enabled: $('proxyEnabled') ? $('proxyEnabled').checked : true,
|
||
header: $('proxyHeaderSelect') ? $('proxyHeaderSelect').value : 'auto',
|
||
trust_all_private: $('proxyTrustPrivate') ? $('proxyTrustPrivate').checked : true,
|
||
trusted_proxies: $('proxyTrustedIps') ? $('proxyTrustedIps').value : ''
|
||
};
|
||
const res = await apiFetch('/api/settings/proxy', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(payload)
|
||
});
|
||
const data = await res.json();
|
||
if (res.ok && data.ok) {
|
||
if (msg) {
|
||
msg.textContent = '✅ ' + tMsg(data.message || 'Réglages du proxy inversé enregistrés avec succès !');
|
||
msg.style.color = 'var(--green)';
|
||
}
|
||
loadReverseProxySettings();
|
||
setTimeout(() => { if (msg) msg.textContent = ''; }, 4000);
|
||
} else {
|
||
throw new Error(data.error || 'Erreur lors de l’enregistrement');
|
||
}
|
||
} catch (err) {
|
||
if (msg) {
|
||
msg.textContent = '❌ ' + tErr(err.message || 'Erreur');
|
||
msg.style.color = 'var(--red)';
|
||
}
|
||
} finally {
|
||
if (btn) { btn.disabled = false; btn.innerHTML = '💾 ' + t('settings_proxy_save_btn', 'Enregistrer les réglages du proxy'); }
|
||
}
|
||
}
|
||
|
||
|
||
function showLoaderScreen() {
|
||
const l = $('loader');
|
||
if (l) {
|
||
l.classList.remove('hide');
|
||
l.classList.remove('hidden');
|
||
l.style.display = 'flex';
|
||
l.style.visibility = 'visible';
|
||
l.style.pointerEvents = 'auto';
|
||
requestAnimationFrame(() => {
|
||
l.style.opacity = '1';
|
||
});
|
||
}
|
||
}
|
||
|
||
function hideLoaderScreen() {
|
||
const l = $('loader');
|
||
if (l) {
|
||
l.style.opacity = '0';
|
||
l.style.pointerEvents = 'none';
|
||
l.classList.add('hide');
|
||
setTimeout(() => {
|
||
if (l.classList.contains('hide')) {
|
||
l.style.visibility = 'hidden';
|
||
l.style.display = 'none';
|
||
l.classList.add('hidden');
|
||
}
|
||
// Sécurité absolue : vérifier qu'au moins une interface (app ou authView) est visible
|
||
const app = $('app');
|
||
const auth = $('authView');
|
||
const isAppVis = app && app.style.display === 'block';
|
||
const isAuthVis = auth && auth.classList.contains('active');
|
||
if (!isAppVis && !isAuthVis) {
|
||
console.warn("Garde-fou : aucune vue visible après disparition du loader, bascule automatique.");
|
||
if (authToken) {
|
||
showApp();
|
||
} else {
|
||
showAuth(!authConfigured);
|
||
}
|
||
}
|
||
}, 380);
|
||
}
|
||
}
|
||
|
||
let loaderSkipped = false;
|
||
function skipLoaderToDashboard() {
|
||
loaderSkipped = true;
|
||
hideLoaderScreen();
|
||
if (authToken) {
|
||
showApp();
|
||
try { load(); } catch (_) { }
|
||
try { if (typeof loadVpnProfiles === 'function') loadVpnProfiles(); } catch (_) { }
|
||
} else {
|
||
showAuth(!authConfigured);
|
||
}
|
||
}
|
||
|
||
// Bouton passer au tableau de bord actif dès le chargement
|
||
const bInit = $('btnSkipLoader');
|
||
if (bInit) bInit.style.display = 'inline-block';
|
||
|
||
function updateLoaderProgress(percent, title, detail, step) {
|
||
const p = Math.max(0, Math.min(100, Math.round(percent)));
|
||
if ($('loaderPercent')) $('loaderPercent').textContent = p + '%';
|
||
if ($('loaderProgressBar')) $('loaderProgressBar').style.width = p + '%';
|
||
if ($('loaderStatusText')) $('loaderStatusText').textContent = title || t('loader_starting', 'Démarrage en cours…');
|
||
if ($('loaderStepDetails')) $('loaderStepDetails').textContent = detail || '';
|
||
if ($('loaderStepLabel')) $('loaderStepLabel').textContent = t('loader_step_x_of_y', 'Étape {step} / 4').replace('{step}', step || 1);
|
||
|
||
const steps = ['stepCheckApi', 'stepCheckWifi', 'stepCheckVpn', 'stepCheckDashboard'];
|
||
steps.forEach((sId, idx) => {
|
||
const el = $(sId);
|
||
if (!el) return;
|
||
const stateEl = el.querySelector('.step-state');
|
||
if (idx + 1 < step) {
|
||
el.className = 'loader-step done';
|
||
if (stateEl) stateEl.textContent = '✅';
|
||
} else if (idx + 1 === step) {
|
||
if (p === 100) {
|
||
el.className = 'loader-step done';
|
||
if (stateEl) stateEl.textContent = '✅';
|
||
} else {
|
||
el.className = 'loader-step active';
|
||
if (stateEl) stateEl.innerHTML = '<span style="display:inline-block;animation:spin 1.2s linear infinite;font-weight:700">↻</span>';
|
||
}
|
||
} else {
|
||
el.className = 'loader-step';
|
||
if (stateEl) stateEl.textContent = '⏳';
|
||
}
|
||
});
|
||
}
|
||
|
||
async function initializeAndShowDashboard(isStarting = true) {
|
||
loaderSkipped = false;
|
||
const skipBtn = $('btnSkipLoader');
|
||
if (skipBtn) skipBtn.style.display = 'inline-block';
|
||
showLoaderScreen();
|
||
const mainTitle = isStarting ? t('loader_starting', "Démarrage en cours…") : t('loader_refreshing', "Actualisation en cours…");
|
||
if ($('loaderBadgeText')) $('loaderBadgeText').textContent = isStarting ? t('loader_starting_badge', "Démarrage en cours") : t('loader_refreshing_badge', "Actualisation en cours");
|
||
if ($('loaderBadgeIcon')) $('loaderBadgeIcon').innerHTML = isStarting ? ICON_GEAR : ICON_REFRESH_ARROW;
|
||
if ($('loaderStatusText')) $('loaderStatusText').textContent = mainTitle;
|
||
const topIcon = $('loaderTopIcon');
|
||
if (topIcon) {
|
||
topIcon.innerHTML = isStarting ? '📶' : '<svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="#38bdf8" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" style="display:block;animation:spin 2s linear infinite"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.9 1 6.7 2.4L21 8"/><polyline points="21 3 21 8 16 8"/></svg>';
|
||
}
|
||
try {
|
||
// 1. Initialisation de l'API & statut session
|
||
updateLoaderProgress(15, mainTitle, t('loader_step1_conn', "Connexion à l’API et vérification des accès…"), 1);
|
||
let statusData = null;
|
||
try {
|
||
const resStatus = await apiFetch('/api/status');
|
||
if (resStatus.ok) statusData = await resStatus.json();
|
||
} catch (e) {
|
||
console.warn("Statut initial :", e);
|
||
}
|
||
if (!authToken) {
|
||
hideLoaderScreen();
|
||
showAuth(!authConfigured);
|
||
return;
|
||
}
|
||
updateLoaderProgress(28, mainTitle, t('loader_step1_admin', "Droits administrateur confirmés"), 1);
|
||
await new Promise(r => setTimeout(r, 120));
|
||
|
||
// 2. Vérification de l'activation du réseau Wi-Fi
|
||
updateLoaderProgress(35, mainTitle, t('loader_step2_checking', "Vérification de l'état du réseau Wi-Fi…"), 2);
|
||
const maxWifiWaitMs = 6000;
|
||
const wifiStart = Date.now();
|
||
|
||
if (statusData && statusData.configured && !statusData.active && statusData.autoconnect) {
|
||
while (Date.now() - wifiStart < maxWifiWaitMs) {
|
||
if (loaderSkipped) break;
|
||
const elapsed = Date.now() - wifiStart;
|
||
if (skipBtn) skipBtn.style.display = 'inline-block';
|
||
const progressBonus = Math.min(18, Math.round((elapsed / maxWifiWaitMs) * 18));
|
||
const remSec = Math.max(1, Math.round((maxWifiWaitMs - elapsed) / 1000));
|
||
updateLoaderProgress(35 + progressBonus, mainTitle, t('loader_step2_activating', "Activation du réseau Wi-Fi ({s}s)…").replace('{s}', remSec), 2);
|
||
await new Promise(r => setTimeout(r, 450));
|
||
try {
|
||
const res = await apiFetch('/api/status');
|
||
if (res.ok) {
|
||
const s = await res.json();
|
||
statusData = s;
|
||
if (s.active) break;
|
||
}
|
||
} catch (_) { }
|
||
}
|
||
}
|
||
if (!authToken || loaderSkipped) return;
|
||
|
||
const isNetworkActive = statusData && statusData.active;
|
||
const apStatusMsg = isNetworkActive
|
||
? t('loader_step2_ap_up', "Point d'accès opérationnel (SSID : {ssid})").replace('{ssid}', statusData.ssid || 'AP')
|
||
: (statusData && statusData.configured ? t('loader_step2_ap_cfg', "Point d'accès configuré") : t('loader_step2_ap_init', "Configuration initiale"));
|
||
updateLoaderProgress(55, mainTitle, apStatusMsg, 2);
|
||
await new Promise(r => setTimeout(r, 120));
|
||
if (!authToken || loaderSkipped) return;
|
||
|
||
// 3. Connexions et Tests de connectivité VPN
|
||
updateLoaderProgress(60, mainTitle, t('loader_step3_detecting', "Détection et vérification des profils VPN…"), 3);
|
||
let vpnProfiles = [];
|
||
try {
|
||
const resVpn = await apiFetch('/api/vpn/profiles');
|
||
if (resVpn.ok) {
|
||
const vpnData = await resVpn.json();
|
||
vpnProfiles = vpnData.profiles || [];
|
||
}
|
||
} catch (e) {
|
||
console.warn("VPN profiles :", e);
|
||
}
|
||
|
||
let targetProfiles = vpnProfiles.filter(p => p.auto_connect);
|
||
if (targetProfiles.length === 0 && vpnProfiles.length > 0) {
|
||
targetProfiles = vpnProfiles;
|
||
}
|
||
const targetAutoCount = targetProfiles.length;
|
||
|
||
if (targetAutoCount > 0) {
|
||
// Attente stricte tant que les profils VPN ne sont pas actifs et connectés avec IP (sauf si clic sur passer au tableau de bord)
|
||
const vpnStart = Date.now();
|
||
const lastConnectAttempt = {};
|
||
const lastIpAttempt = {};
|
||
let currentProfiles = [];
|
||
|
||
while (!loaderSkipped) {
|
||
if (!authToken) break;
|
||
let connectedCount = 0;
|
||
try {
|
||
const res = await apiFetch('/api/vpn/profiles');
|
||
if (res.ok) {
|
||
const vpnData = await res.json();
|
||
vpnProfiles = vpnData.profiles || [];
|
||
currentProfiles = vpnProfiles.filter(p => targetProfiles.some(tp => tp.id === p.id));
|
||
connectedCount = currentProfiles.filter(p => p.status === 'connected').length;
|
||
|
||
const nowTs = Date.now();
|
||
const elapsedSec = Math.round((nowTs - vpnStart) / 1000);
|
||
|
||
if (skipBtn) skipBtn.style.display = 'inline-block';
|
||
|
||
// Relancer une tentative de connexion si un profil est déconnecté ou en erreur (cooldown 4s)
|
||
for (const p of currentProfiles) {
|
||
if (p.status === 'disconnected' || p.status === 'error') {
|
||
const lastAttempt = lastConnectAttempt[p.id] || 0;
|
||
if (nowTs - lastAttempt >= 4000) {
|
||
lastConnectAttempt[p.id] = nowTs;
|
||
apiFetch('/api/vpn/connect', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ id: p.id })
|
||
}).catch(() => { });
|
||
}
|
||
}
|
||
}
|
||
|
||
// Récupérer l'IP publique en direct pour les tunnels connectés qui ne l'ont pas encore (cooldown 3s)
|
||
for (const p of currentProfiles) {
|
||
if (p.status === 'connected' && !p.public_ip) {
|
||
const lastIp = lastIpAttempt[p.id] || 0;
|
||
if (nowTs - lastIp >= 3000) {
|
||
lastIpAttempt[p.id] = nowTs;
|
||
apiFetch('/api/vpn/check-ip?id=' + encodeURIComponent(p.id) + '&force=0').catch(() => { });
|
||
}
|
||
}
|
||
}
|
||
|
||
// Statut détaillé en direct
|
||
const statusDetails = currentProfiles.map(p => {
|
||
const flag = (p.public_ip_geo && p.public_ip_geo.code) ? `[${p.public_ip_geo.code}] ` : '';
|
||
if (p.status === 'connected' && p.public_ip) {
|
||
return `✅ ${p.name} (${flag}${p.public_ip})`;
|
||
} else if (p.status === 'connected') {
|
||
return `↻ ${p.name} (${t('loader_ip_pending', 'IP en cours…')})`;
|
||
} else if (p.status === 'connecting') {
|
||
return `↻ ${p.name} (${t('loader_connecting', 'connexion…')})`;
|
||
} else {
|
||
return `⏳ ${p.name} (${t('loader_waiting', 'attente…')})`;
|
||
}
|
||
}).join(' • ');
|
||
|
||
const ipCount = currentProfiles.filter(p => p.status === 'connected' && p.public_ip).length;
|
||
const progressVal = 60 + Math.min(28, Math.round(((connectedCount + ipCount) / (targetAutoCount * 2)) * 28));
|
||
updateLoaderProgress(progressVal, mainTitle, t('loader_step3_waiting', "Tunnels VPN ({connected}/{target}) : {details} [{elapsed}s]").replace('{connected}', connectedCount).replace('{target}', targetAutoCount).replace('{details}', statusDetails).replace('{elapsed}', elapsedSec), 3);
|
||
|
||
// Condition d'achèvement stricte :
|
||
// TOUS les profils VPN ciblés doivent être connectés et actifs avec leur IP publique
|
||
if (connectedCount >= targetAutoCount && currentProfiles.every(p => p.status === 'connected' && p.public_ip)) {
|
||
break;
|
||
}
|
||
}
|
||
} catch (_) { }
|
||
await new Promise(r => setTimeout(r, 700));
|
||
}
|
||
if (loaderSkipped) return;
|
||
|
||
// Résumé final de l'étape 3
|
||
const finalConnected = currentProfiles.filter(p => p.status === 'connected');
|
||
const sumStr = finalConnected.map(p => {
|
||
const flag = (p.public_ip_geo && p.public_ip_geo.code) ? `[${p.public_ip_geo.code}] ` : '';
|
||
return `${p.name} (${flag}${p.public_ip || p.iface || 'actif'})`;
|
||
}).join(' • ');
|
||
updateLoaderProgress(88, mainTitle, t('loader_step3_ok', "Tunnels VPN opérationnels ({connected}/{target}) : {details}").replace('{connected}', finalConnected.length).replace('{target}', targetAutoCount).replace('{details}', sumStr), 3);
|
||
await new Promise(r => setTimeout(r, 250));
|
||
} else {
|
||
updateLoaderProgress(88, mainTitle, t('loader_step3_none', "Aucun profil VPN configuré"), 3);
|
||
await new Promise(r => setTimeout(r, 120));
|
||
}
|
||
|
||
if (!authToken || loaderSkipped) return;
|
||
|
||
// 4. Chargement final et synchronisation du tableau de bord
|
||
updateLoaderProgress(90, mainTitle, t('loader_step4_sync', "Synchronisation des équipements, tunnels et métriques…"), 4);
|
||
try {
|
||
await load();
|
||
if (typeof loadVpnProfiles === 'function') await loadVpnProfiles();
|
||
if (typeof loadVpnClients === 'function') await loadVpnClients();
|
||
} catch (e) {
|
||
console.warn("Load error:", e);
|
||
}
|
||
updateLoaderProgress(96, mainTitle, t('loader_step4_inventory', "Inventaire des appareils réseau…"), 4);
|
||
try {
|
||
if (typeof loadDevices === 'function') await loadDevices();
|
||
} catch (e) {
|
||
console.warn("Load devices error:", e);
|
||
}
|
||
|
||
const savedTab = sessionStorage.getItem('apDashboardTab');
|
||
if (savedTab && ['dashboard', 'stats', 'devices', 'advanced', 'settings', 'logs', 'blocked'].includes(savedTab)) {
|
||
try { selectTab(savedTab); } catch (_) { selectTab('dashboard'); }
|
||
} else {
|
||
try { selectTab('dashboard'); } catch (_) { }
|
||
}
|
||
|
||
// 5. Affichage du tableau de bord et disparition fluide du loader
|
||
const endTitle = isStarting ? t('loader_step4_done', "Démarrage terminé !") : t('loader_step4_ready', "Système prêt !");
|
||
if ($('loaderBadgeText')) $('loaderBadgeText').textContent = isStarting ? t('loader_step4_done_badge', "Démarrage terminé") : t('loader_step4_ready_badge', "Système prêt");
|
||
updateLoaderProgress(100, endTitle, t('loader_step4_opening', "Ouverture du tableau de bord d'administration"), 4);
|
||
sessionStorage.setItem('apAppStarted', '1');
|
||
localStorage.setItem('apAppStarted', '1');
|
||
if (statusData && statusData.boot_time) {
|
||
sessionStorage.setItem('apBootTime', String(statusData.boot_time));
|
||
localStorage.setItem('apBootTime', String(statusData.boot_time));
|
||
}
|
||
await new Promise(r => setTimeout(r, 200));
|
||
} catch (err) {
|
||
console.error("Erreur lors de l'initialisation du dashboard :", err);
|
||
} finally {
|
||
if (authToken) {
|
||
showApp();
|
||
} else {
|
||
showAuth(!authConfigured);
|
||
}
|
||
hideLoaderScreen();
|
||
}
|
||
}
|
||
|
||
(async () => {
|
||
applyProjectTitle();
|
||
applyLanguage(currentLanguage, false);
|
||
try {
|
||
let data = null;
|
||
let serverWasDown = false;
|
||
for (let attempt = 1; !data; attempt++) {
|
||
try {
|
||
let controller, timer;
|
||
let fetchOpts = { cache: 'no-store' };
|
||
if (typeof AbortController !== 'undefined') {
|
||
controller = new AbortController();
|
||
timer = setTimeout(() => controller.abort(), 6000);
|
||
fetchOpts.signal = controller.signal;
|
||
}
|
||
const response = await fetch(API_URL + '/api/auth/status', fetchOpts);
|
||
if (timer) clearTimeout(timer);
|
||
if (!response.ok) throw Error('HTTP ' + response.status);
|
||
data = await response.json();
|
||
} catch (e) {
|
||
serverWasDown = true;
|
||
showLoaderScreen();
|
||
if ($('loaderBadgeText')) $('loaderBadgeText').textContent = 'Démarrage en cours';
|
||
if ($('loaderBadgeIcon')) $('loaderBadgeIcon').innerHTML = ICON_GEAR;
|
||
updateLoaderProgress(5, "Démarrage en cours…", `Attente du serveur API (${attempt}/4) dans 1.5s…`, 1);
|
||
if (attempt >= 4) {
|
||
console.warn("API indisponible après 4 tentatives, arrêt du loader et affichage de l'interface");
|
||
hideLoaderScreen();
|
||
showAuth(false);
|
||
return;
|
||
}
|
||
await new Promise(resolve => setTimeout(resolve, 1500));
|
||
}
|
||
}
|
||
authConfigured = !!data.configured; authTwoFactor = !!data.two_factor;
|
||
const isSetupDone = !!(data.setup_completed !== undefined ? data.setup_completed : (data.configured && data.wifi_configured));
|
||
if (!authConfigured || (!isSetupDone && !data.wifi_configured)) {
|
||
hideLoaderScreen();
|
||
window.location.replace('/setup');
|
||
return;
|
||
}
|
||
if (data.language && ['fr', 'en-us', 'en-gb'].includes(data.language)) {
|
||
applyLanguage(data.language, false);
|
||
}
|
||
if (data.username && $('authSettingsUsername')) $('authSettingsUsername').value = data.username;
|
||
if (data.app_name) applyProjectTitle(data.app_name, data.app_short_name);
|
||
|
||
const currentBootTime = Number(data.boot_time || 0);
|
||
const storedBootTime = Number(sessionStorage.getItem('apBootTime') || localStorage.getItem('apBootTime') || 0);
|
||
const serverRebooted = serverWasDown || (currentBootTime > 0 && storedBootTime > 0 && Math.abs(currentBootTime - storedBootTime) > 2);
|
||
const alreadyStarted = (sessionStorage.getItem('apAppStarted') || localStorage.getItem('apAppStarted')) === '1';
|
||
const visited = sessionStorage.getItem('apVisited') === '1';
|
||
|
||
// Si data.is_starting est faux (le serveur a déjà fini son boot), ce n'est PAS un premier démarrage !
|
||
const serverStillStarting = !!data.is_starting;
|
||
let isStarting = serverStillStarting && (!alreadyStarted || serverRebooted) && !visited;
|
||
|
||
sessionStorage.setItem('apVisited', '1');
|
||
if (serverRebooted) {
|
||
sessionStorage.removeItem('apAppStarted');
|
||
localStorage.removeItem('apAppStarted');
|
||
}
|
||
|
||
if (authToken) {
|
||
// Affichage de la page de chargement (Démarrage ou Actualisation)
|
||
await initializeAndShowDashboard(isStarting);
|
||
if (currentBootTime > 0) {
|
||
sessionStorage.setItem('apBootTime', String(currentBootTime));
|
||
localStorage.setItem('apBootTime', String(currentBootTime));
|
||
}
|
||
} else {
|
||
// Utilisateur non connecté : masquer le loader et afficher l'écran de connexion
|
||
hideLoaderScreen();
|
||
showAuth(!authConfigured);
|
||
}
|
||
} catch (err) {
|
||
console.error('Erreur démarrage dashboard:', err);
|
||
if (authToken) {
|
||
showApp();
|
||
} else {
|
||
showAuth(!authConfigured);
|
||
}
|
||
hideLoaderScreen();
|
||
}
|
||
})();
|
||
|
||
setInterval(() => {
|
||
if (authToken && currentTab !== 'settings') {
|
||
load();
|
||
if (currentTab === 'stats') { if (currentStatsSubTab === 'topology') loadTopology(); else loadStats(); }
|
||
}
|
||
}, 2000);
|
||
|
||
/* Actualisation automatique des journaux toutes les minutes */
|
||
setInterval(() => {
|
||
if (authToken) {
|
||
loadLogs();
|
||
}
|
||
}, 60000);
|
||
|
||
// =====================================================================
|
||
// GESTION DES PROFILS VPN & ROUTAGE CLIENTS (WireGuard & OpenVPN)
|
||
// =====================================================================
|
||
let vpnProfilesCache = [];
|
||
let vpnClientsCache = [];
|
||
let currentAdvSubTab = 'vpn';
|
||
let viewingVpnProfile = null;
|
||
|
||
function selectAdvSubTab(subTab) {
|
||
currentAdvSubTab = subTab;
|
||
const btnVpn = $('tabAdvVpnRouting'), btnPcap = $('tabAdvPcap');
|
||
const panelVpn = $('panelAdvVpnRouting'), panelPcap = $('panelAdvPcap');
|
||
if (btnVpn) btnVpn.className = 'settings-nav-btn' + (subTab === 'vpn' ? ' active' : '');
|
||
if (btnPcap) btnPcap.className = 'settings-nav-btn' + (subTab === 'pcap' ? ' active' : '');
|
||
if (panelVpn) panelVpn.style.display = (subTab === 'vpn' ? 'block' : 'none');
|
||
if (panelPcap) panelPcap.style.display = (subTab === 'pcap' ? 'block' : 'none');
|
||
if (subTab === 'vpn') {
|
||
loadVpnClients();
|
||
stopCaptureTimer();
|
||
} else {
|
||
loadCaptureStatus();
|
||
loadCapturePackets(true);
|
||
ensureCapturePolling();
|
||
}
|
||
}
|
||
|
||
function onVpnTypeChange() {
|
||
const isOvpn = $('vpnTypeOvpn') && $('vpnTypeOvpn').checked;
|
||
const authSec = $('vpnOpenvpnAuthSection');
|
||
if (authSec) authSec.style.display = isOvpn ? 'block' : 'none';
|
||
}
|
||
|
||
function handleVpnConfigFile(event) {
|
||
const file = event.target.files && event.target.files[0];
|
||
if (!file) return;
|
||
const nameInput = $('vpnProfileName');
|
||
if (nameInput && !nameInput.value.trim()) {
|
||
let cleanName = file.name.replace(/\.(conf|ovpn|txt)$/i, '').replace(/[-_]/g, ' ');
|
||
nameInput.value = cleanName.charAt(0).toUpperCase() + cleanName.slice(1);
|
||
}
|
||
if (file.name.toLowerCase().endsWith('.ovpn')) {
|
||
if ($('vpnTypeOvpn')) { $('vpnTypeOvpn').checked = true; onVpnTypeChange(); }
|
||
} else if (file.name.toLowerCase().endsWith('.conf')) {
|
||
if ($('vpnTypeWg')) { $('vpnTypeWg').checked = true; onVpnTypeChange(); }
|
||
}
|
||
const reader = new FileReader();
|
||
reader.onload = function (e) {
|
||
if ($('vpnProfileConfig')) $('vpnProfileConfig').value = e.target.result || '';
|
||
};
|
||
reader.readAsText(file);
|
||
}
|
||
|
||
function openVpnModal(profileId) {
|
||
const modal = $('modalVpnProfile');
|
||
const title = $('vpnModalTitle');
|
||
const idEl = $('vpnProfileId');
|
||
const nameEl = $('vpnProfileName');
|
||
const configEl = $('vpnProfileConfig');
|
||
const userEl = $('vpnAuthUser');
|
||
const passEl = $('vpnAuthPass');
|
||
const autoEl = $('vpnAutoConnect');
|
||
const msgEl = $('vpnFormMsg');
|
||
if (!modal) return;
|
||
if (msgEl) msgEl.textContent = '';
|
||
if (profileId) {
|
||
const prof = vpnProfilesCache.find(p => p.id === profileId);
|
||
if (prof) {
|
||
if (title) title.textContent = t('vpn_modal_edit_title', 'Modifier le profil VPN : {name}').replace('{name}', prof.name);
|
||
if (idEl) idEl.value = prof.id;
|
||
if (nameEl) nameEl.value = prof.name;
|
||
if (configEl) configEl.value = prof.config_content;
|
||
if (userEl) userEl.value = prof.auth_user || '';
|
||
if (passEl) passEl.value = '';
|
||
if (autoEl) autoEl.checked = !!prof.auto_connect;
|
||
if (prof.type === 'openvpn') {
|
||
if ($('vpnTypeOvpn')) $('vpnTypeOvpn').checked = true;
|
||
} else {
|
||
if ($('vpnTypeWg')) $('vpnTypeWg').checked = true;
|
||
}
|
||
onVpnTypeChange();
|
||
}
|
||
} else {
|
||
if (title) title.textContent = t('vpn_modal_title', 'Ajouter un profil VPN');
|
||
if (idEl) idEl.value = '';
|
||
if (nameEl) nameEl.value = '';
|
||
if (configEl) configEl.value = '';
|
||
if (userEl) userEl.value = '';
|
||
if (passEl) passEl.value = '';
|
||
if (autoEl) autoEl.checked = false;
|
||
if ($('vpnTypeWg')) $('vpnTypeWg').checked = true;
|
||
onVpnTypeChange();
|
||
}
|
||
modal.classList.add('active');
|
||
modal.style.display = 'flex';
|
||
}
|
||
|
||
function closeVpnModal() {
|
||
const modal = $('modalVpnProfile');
|
||
if (modal) {
|
||
modal.classList.remove('active');
|
||
modal.style.display = 'none';
|
||
}
|
||
}
|
||
|
||
async function saveVpnProfile() {
|
||
const id = $('vpnProfileId') ? $('vpnProfileId').value : '';
|
||
const name = $('vpnProfileName') ? $('vpnProfileName').value.trim() : '';
|
||
const type = ($('vpnTypeOvpn') && $('vpnTypeOvpn').checked) ? 'openvpn' : 'wireguard';
|
||
const config_content = $('vpnProfileConfig') ? $('vpnProfileConfig').value.trim() : '';
|
||
const auth_user = $('vpnAuthUser') ? $('vpnAuthUser').value.trim() : '';
|
||
const auth_pass = $('vpnAuthPass') ? $('vpnAuthPass').value : '';
|
||
const auto_connect = $('vpnAutoConnect') ? $('vpnAutoConnect').checked : false;
|
||
const msgEl = $('vpnFormMsg');
|
||
const btn = $('btnSaveVpnProfile');
|
||
|
||
if (!name) {
|
||
if (msgEl) msgEl.textContent = t('vpn_err_enter_name', 'Veuillez saisir un nom pour ce profil.');
|
||
return;
|
||
}
|
||
if (!config_content) {
|
||
if (msgEl) msgEl.textContent = t('vpn_err_enter_config', 'Veuillez coller ou importer la configuration du VPN.');
|
||
return;
|
||
}
|
||
|
||
if (btn) { btn.disabled = true; btn.textContent = t('vpn_btn_saving', 'Enregistrement...'); }
|
||
try {
|
||
const res = await apiFetch('/api/vpn/profiles', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
id: id ? parseInt(id, 10) : undefined,
|
||
name, type, config_content, auth_user, auth_pass, auto_connect
|
||
})
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur lors de l’enregistrement');
|
||
closeVpnModal();
|
||
loadVpnProfiles();
|
||
loadVpnClients();
|
||
load();
|
||
loadLogs();
|
||
if (typeof loadTopology === 'function') loadTopology();
|
||
} catch (e) {
|
||
if (msgEl) msgEl.textContent = tErr(e.message);
|
||
} finally {
|
||
if (btn) { btn.disabled = false; btn.textContent = t('modal_vpn_save_btn', 'Enregistrer le profil'); }
|
||
}
|
||
}
|
||
|
||
async function deleteVpnProfile(pid) {
|
||
const prof = vpnProfilesCache.find(p => p.id === pid);
|
||
const name = prof ? prof.name : 'ce profil';
|
||
const confirmMsg = t('vpn_delete_confirm', "Êtes-vous sûr de vouloir supprimer le profil VPN « {name} » ?\nToute assignation client associée reviendra sur la connexion directe WAN.").replace('{name}', name);
|
||
if (!confirm(confirmMsg)) return;
|
||
try {
|
||
const res = await apiFetch('/api/vpn/profiles/delete', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ id: pid })
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur');
|
||
loadVpnProfiles();
|
||
loadVpnClients();
|
||
load();
|
||
loadLogs();
|
||
if (typeof loadTopology === 'function') loadTopology();
|
||
} catch (e) {
|
||
alert(tErr(e.message));
|
||
}
|
||
}
|
||
|
||
async function toggleVpnConnect(pid, willConnect) {
|
||
const action = willConnect ? '/api/vpn/connect' : '/api/vpn/disconnect';
|
||
try {
|
||
const res = await apiFetch(action, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ id: pid })
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur');
|
||
loadVpnProfiles();
|
||
loadVpnClients();
|
||
load();
|
||
loadLogs();
|
||
if (typeof loadTopology === 'function') loadTopology();
|
||
} catch (e) {
|
||
alert(tErr(e.message));
|
||
loadVpnProfiles();
|
||
}
|
||
}
|
||
|
||
function viewVpnConfig(pid) {
|
||
const prof = vpnProfilesCache.find(p => p.id === pid);
|
||
if (!prof) return;
|
||
viewingVpnProfile = prof;
|
||
const modal = $('modalVpnView');
|
||
const title = $('vpnViewTitle');
|
||
const content = $('vpnViewContent');
|
||
if (!modal) return;
|
||
if (title) title.textContent = t('vpn_view_modal_title', 'Configuration VPN : {name} ({type})').replace('{name}', prof.name).replace('{type}', prof.type.toUpperCase());
|
||
if (content) content.textContent = prof.config_content;
|
||
modal.classList.add('active');
|
||
modal.style.display = 'flex';
|
||
}
|
||
|
||
function closeVpnViewModal() {
|
||
const modal = $('modalVpnView');
|
||
if (modal) {
|
||
modal.classList.remove('active');
|
||
modal.style.display = 'none';
|
||
}
|
||
viewingVpnProfile = null;
|
||
}
|
||
|
||
function copyVpnConfigText() {
|
||
const content = $('vpnViewContent');
|
||
if (!content) return;
|
||
navigator.clipboard.writeText(content.textContent).then(() => {
|
||
const btn = $('btnCopyVpnConfig');
|
||
if (btn) {
|
||
const prev = btn.textContent;
|
||
btn.textContent = t('vpn_copied_btn', '✓ Copié !');
|
||
setTimeout(() => { btn.textContent = prev; }, 1500);
|
||
}
|
||
});
|
||
}
|
||
|
||
function downloadVpnConfigFile() {
|
||
if (!viewingVpnProfile) return;
|
||
const ext = viewingVpnProfile.type === 'openvpn' ? 'ovpn' : 'conf';
|
||
const filename = (viewingVpnProfile.name.toLowerCase().replace(/[^a-z0-9_-]/g, '_') || 'vpn_profile') + '.' + ext;
|
||
const blob = new Blob([viewingVpnProfile.config_content], { type: 'text/plain;charset=utf-8' });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = filename;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
URL.revokeObjectURL(url);
|
||
}
|
||
|
||
async function loadVpnProfiles() {
|
||
try {
|
||
const res = await apiFetch('/api/vpn/profiles');
|
||
if (!res.ok) return;
|
||
const d = await res.json();
|
||
vpnProfilesCache = d.profiles || [];
|
||
renderVpnProfiles(vpnProfilesCache);
|
||
} catch (e) { }
|
||
}
|
||
|
||
let vpnCheckingSet = new Set();
|
||
async function checkVpnIp(id, btn) {
|
||
if (btn) {
|
||
btn.disabled = true;
|
||
btn.textContent = '⏳ ...';
|
||
}
|
||
try {
|
||
const res = await apiFetch('/api/vpn/check-ip', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ id })
|
||
});
|
||
const d = await res.json();
|
||
if (res.ok && d.ok && d.public_ip) {
|
||
showToast(t('vpn_ip_detected', 'IP publique VPN détectée : {ip}').replace('{ip}', d.public_ip), 'success');
|
||
} else {
|
||
showToast(d.error || t('vpn_ip_error', 'Impossible d’obtenir l’IP publique via ce profil VPN'), 'error');
|
||
}
|
||
await loadVpnProfiles();
|
||
if (typeof loadVpnClients === 'function') await loadVpnClients();
|
||
} catch (e) {
|
||
showToast('Erreur lors du test de l\'IP : ' + e.message, 'error');
|
||
} finally {
|
||
if (btn) {
|
||
btn.disabled = false;
|
||
btn.textContent = t('vpn_test_btn', '🔄 Tester');
|
||
}
|
||
}
|
||
}
|
||
|
||
function formatHandshake(p) {
|
||
if (!p) return '';
|
||
let sec = p.handshake_age_seconds;
|
||
if (sec === undefined || sec === null) {
|
||
const s = String(p.handshake || '');
|
||
if (!s) return '';
|
||
if (s.includes('En attente') || s.toLowerCase().includes('waiting')) return t('vpn_handshake_waiting', 'En attente du handshake (non reçu)');
|
||
const mSec = s.match(/(?:il y a|\()\s*(\d+)\s*s/i) || s.match(/(\d+)\s*s\s*ago/i);
|
||
if (mSec) sec = parseInt(mSec[1], 10);
|
||
const mMin = s.match(/(?:il y a|\()\s*(\d+)\s*min/i) || s.match(/(\d+)\s*min\s*ago/i);
|
||
if (mMin) sec = parseInt(mMin[1], 10) * 60;
|
||
const mH = s.match(/(?:il y a|\()\s*(\d+)\s*h/i) || s.match(/(\d+)\s*h\s*ago/i);
|
||
if (mH) sec = parseInt(mH[1], 10) * 3600;
|
||
}
|
||
if (sec === undefined || sec === null) return escapeHtml(p.handshake || '');
|
||
if (sec < 0) return t('vpn_handshake_waiting', 'En attente du handshake (non reçu)');
|
||
if (sec < 120) {
|
||
return t('vpn_handshake_active', 'Handshake actif (il y a {sec}s)').replace('{sec}', sec);
|
||
} else if (sec < 3600) {
|
||
return t('vpn_handshake_recent', 'Dernier handshake il y a {min} min').replace('{min}', Math.floor(sec / 60));
|
||
} else {
|
||
return t('vpn_handshake_older', 'Dernier handshake il y a {h} h').replace('{h}', Math.floor(sec / 3600));
|
||
}
|
||
}
|
||
|
||
function renderVpnProfiles(profiles) {
|
||
const container = $('vpnProfilesList');
|
||
const empty = $('vpnProfilesEmpty');
|
||
if (!container) return;
|
||
if (!profiles || profiles.length === 0) {
|
||
container.innerHTML = '';
|
||
if (empty) empty.style.display = 'block';
|
||
return;
|
||
}
|
||
if (empty) empty.style.display = 'none';
|
||
|
||
let html = '';
|
||
profiles.forEach(p => {
|
||
const isConn = p.status === 'connected';
|
||
const isErr = p.status === 'error';
|
||
const isConnecting = p.status === 'connecting';
|
||
const vpnBadgeHtml = getVpnTypeBadgeHtml(p.type, true);
|
||
|
||
let statusPill = '';
|
||
if (isConn) {
|
||
statusPill = `<span class="pill pill-green pill-no-dot" style="font-size:11px">🟢 ${t('status_connected', 'Connecté')}</span>`;
|
||
} else if (isConnecting) {
|
||
statusPill = `<span class="pill" style="background:rgba(246,173,85,.15);color:#f6ad55;border:1px solid rgba(246,173,85,.3);font-size:11px">🟡 ${t('status_connecting', 'Connexion...')}</span>`;
|
||
} else if (isErr) {
|
||
statusPill = `<span class="pill" style="background:rgba(255,107,107,.15);color:var(--red);border:1px solid rgba(255,107,107,.3);font-size:11px" title="${escapeHtml(p.last_error)}">⚠️ ${t('status_error', 'Erreur')}</span>`;
|
||
} else {
|
||
statusPill = `<span class="pill" style="background:var(--panel2);color:var(--muted);font-size:11px">🔴 ${t('status_disconnected', 'Déconnecté')}</span>`;
|
||
}
|
||
|
||
const connectBtn = isConn
|
||
? `<button type="button" class="secondary" onclick="toggleVpnConnect(${p.id}, false)" style="background:rgba(255,107,107,.12);color:var(--red);border:1px solid rgba(255,107,107,.3);padding:6px 12px;font-size:12px;border-radius:6px">⏹ ${t('btn_disconnect', 'Déconnecter')}</button>`
|
||
: `<button type="button" onclick="toggleVpnConnect(${p.id}, true)" style="background:rgba(50,213,131,.2);color:var(--green);border:1px solid rgba(50,213,131,.4);padding:6px 12px;font-size:12px;border-radius:6px">▶ ${t('btn_connect', 'Connecter')}</button>`;
|
||
|
||
const vpnIpBadge = p.public_ip ? formatIpWithGeo(p.public_ip, p.public_ip_geo) : `<strong style="color:#f6ad55;font-size:12px">${t('vpn_pending_test', '⚠️ En attente de test')}</strong>`;
|
||
|
||
html += `
|
||
<div class="card" style="display:flex;flex-direction:column;justify-content:space-between;border:1px solid ${isConn ? 'rgba(50,213,131,.4)' : 'var(--line)'};padding:14px;background:var(--panel)">
|
||
<div>
|
||
<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px">
|
||
${vpnBadgeHtml}
|
||
${statusPill}
|
||
</div>
|
||
<div style="font-size:16px;font-weight:700;margin-bottom:6px">${escapeHtml(p.name)}</div>
|
||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px;font-size:12px;margin:10px 0;background:var(--panel2);padding:10px;border-radius:8px">
|
||
<div><span class="muted">${t('vpn_card_interface', 'Interface :')}</span> <strong>${escapeHtml(p.iface)}</strong></div>
|
||
<div><span class="muted">${t('vpn_card_table_pbr', 'Table PBR :')}</span> <code>${p.table_id}</code></div>
|
||
<div><span class="muted">${t('vpn_card_transfer', 'Transfert :')}</span> ↓ ${p.rx_formatted} • ↑ ${p.tx_formatted}</div>
|
||
<div><span class="muted">${t('th_clients', 'Clients :')}</span> <strong>${p.clients_count}</strong> ${t('devices_count_suffix', 'appareil(s)')}</div>
|
||
</div>
|
||
${isConn ? `
|
||
<div style="margin:8px 0 10px 0;padding:8px 10px;background:${p.public_ip ? 'rgba(50,213,131,.1)' : 'rgba(246,173,85,.1)'};border:1px solid ${p.public_ip ? 'rgba(50,213,131,.3)' : 'rgba(246,173,85,.3)'};border-radius:8px;font-size:12px;display:flex;align-items:center;justify-content:space-between;gap:8px">
|
||
<div style="min-width:0;flex:1">
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<span class="muted">${t('vpn_public_ip_label', 'IP publique VPN :')}</span>
|
||
<div style="display:inline-flex;align-items:center;gap:6px">
|
||
${vpnIpBadge}
|
||
</div>
|
||
${p.last_tested ? `<span class="muted" style="font-size:11px" title="${t('vpn_auto_test_5min', 'Test automatique effectué toutes les 5 min')}">(${t('vpn_last_test', 'Dernier test :')} ${escapeHtml(p.last_tested)})</span>` : ''}
|
||
</div>
|
||
${p.handshake ? `<div style="font-size:11px;color:var(--muted);margin-top:3px">🤝 ${formatHandshake(p)}</div>` : ''}
|
||
</div>
|
||
<button type="button" class="secondary" onclick="checkVpnIp(${p.id}, this)" title="${t('vpn_test_tooltip', 'Tester la connexion et rafraîchir l\'IP publique')}" style="padding:4px 8px;font-size:11px;border-radius:6px;white-space:nowrap">
|
||
${t('vpn_test_btn', '🔄 Tester')}
|
||
</button>
|
||
</div>` : ''}
|
||
${isErr && p.last_error ? `<div class="muted" style="color:var(--red);font-size:11px;margin-bottom:8px;word-break:break-all">${t('vpn_error_prefix', 'Erreur :')} ${escapeHtml(p.last_error)}</div>` : ''}
|
||
${p.auto_connect ? `<div class="muted" style="font-size:11px;margin-bottom:6px">${t('vpn_autoconnect_badge', '⚡ Démarrage automatique actif')}</div>` : ''}
|
||
</div>
|
||
<div style="display:flex;align-items:center;justify-content:space-between;gap:6px;margin-top:10px;padding-top:10px;border-top:1px solid var(--line);flex-wrap:wrap">
|
||
<div style="display:flex;gap:6px">
|
||
${connectBtn}
|
||
<button type="button" class="secondary" onclick="viewVpnConfig(${p.id})" title="${t('vpn_view_config', 'Voir la configuration')}" style="padding:6px 10px;font-size:12px">👁️</button>
|
||
</div>
|
||
<div style="display:flex;gap:6px">
|
||
<button type="button" class="secondary" onclick="openVpnModal(${p.id})" title="${t('btn_edit', 'Modifier')}" style="padding:6px 10px;font-size:12px">✏️</button>
|
||
<button type="button" class="secondary" onclick="deleteVpnProfile(${p.id})" title="${t('btn_delete', 'Supprimer')}" style="color:var(--red);padding:6px 10px;font-size:12px">🗑️</button>
|
||
</div>
|
||
</div>
|
||
</div>`;
|
||
});
|
||
container.innerHTML = html;
|
||
}
|
||
|
||
async function loadVpnClients() {
|
||
try {
|
||
const [resClients, resProfs] = await Promise.all([
|
||
apiFetch('/api/vpn/clients'),
|
||
apiFetch('/api/vpn/profiles')
|
||
]);
|
||
if (resProfs.ok) {
|
||
const dp = await resProfs.json();
|
||
vpnProfilesCache = dp.profiles || [];
|
||
}
|
||
if (resClients.ok) {
|
||
const dc = await resClients.json();
|
||
vpnClientsCache = dc.clients || [];
|
||
renderVpnClients(vpnClientsCache, vpnProfilesCache);
|
||
}
|
||
} catch (e) { }
|
||
}
|
||
|
||
let vpnClientsSearchQuery = '';
|
||
let vpnClientsFilter = 'all';
|
||
let vpnClientsPage = 1;
|
||
|
||
window.onVpnClientsSearch = (q) => {
|
||
vpnClientsSearchQuery = (q || '').trim().toLowerCase();
|
||
vpnClientsPage = 1;
|
||
renderVpnClients(vpnClientsCache, vpnProfilesCache);
|
||
};
|
||
|
||
window.setVpnClientsFilter = (f) => {
|
||
vpnClientsFilter = f;
|
||
vpnClientsPage = 1;
|
||
['all', 'routed', 'online', 'offline'].forEach(type => {
|
||
const btn = $('btnFilterVpn' + type.charAt(0).toUpperCase() + type.slice(1));
|
||
if (btn) btn.classList.toggle('active', f === type);
|
||
});
|
||
renderVpnClients(vpnClientsCache, vpnProfilesCache);
|
||
};
|
||
|
||
window.changeVpnClientsPage = (p) => {
|
||
vpnClientsPage = p;
|
||
renderVpnClients(vpnClientsCache, vpnProfilesCache);
|
||
};
|
||
|
||
function renderVpnClients(clients, profiles) {
|
||
const tbody = $('vpnClientsTableBody');
|
||
const empty = $('vpnClientsEmpty');
|
||
if (!tbody) return;
|
||
|
||
const activeProfs = profiles.filter(p => p.status === 'connected').length;
|
||
|
||
let totalRouted = 0, totalDirect = 0, totalKs = 0, totalOnline = 0, totalOffline = 0;
|
||
(clients || []).forEach(c => {
|
||
if (c.profile_id > 0) totalRouted++;
|
||
else totalDirect++;
|
||
if (c.kill_switch) totalKs++;
|
||
if (c.online) totalOnline++;
|
||
else totalOffline++;
|
||
});
|
||
|
||
if ($('metricVpnProfilesCount')) $('metricVpnProfilesCount').textContent = profiles.length;
|
||
if ($('metricVpnActiveCount')) $('metricVpnActiveCount').textContent = `${activeProfs} ${t('vpn_connected_suffix', 'connecté(s)')}`;
|
||
if ($('metricVpnRoutedClients')) $('metricVpnRoutedClients').textContent = totalRouted;
|
||
if ($('metricVpnDirectClients')) $('metricVpnDirectClients').textContent = totalDirect;
|
||
if ($('metricVpnKillswitchCount')) $('metricVpnKillswitchCount').textContent = totalKs;
|
||
|
||
if ($('filterCountVpnAll')) $('filterCountVpnAll').textContent = (clients || []).length;
|
||
if ($('filterCountVpnRouted')) $('filterCountVpnRouted').textContent = totalRouted;
|
||
if ($('filterCountVpnOnline')) $('filterCountVpnOnline').textContent = totalOnline;
|
||
if ($('filterCountVpnOffline')) $('filterCountVpnOffline').textContent = totalOffline;
|
||
|
||
if (!clients || clients.length === 0) {
|
||
tbody.innerHTML = '';
|
||
if (empty) empty.style.display = 'block';
|
||
renderPagination('vpnClientsPagination', 1, 0, 'changeVpnClientsPage', 10);
|
||
return;
|
||
}
|
||
|
||
let filtered = clients.filter(c => {
|
||
if (vpnClientsFilter === 'routed' && !(c.profile_id > 0)) return false;
|
||
if (vpnClientsFilter === 'online' && !c.online) return false;
|
||
if (vpnClientsFilter === 'offline' && c.online) return false;
|
||
if (vpnClientsSearchQuery) {
|
||
const q = vpnClientsSearchQuery;
|
||
const m = (c.name || '').toLowerCase().includes(q) ||
|
||
(c.mac || '').toLowerCase().includes(q) ||
|
||
(c.ip || '').toLowerCase().includes(q) ||
|
||
(c.profile_name || '').toLowerCase().includes(q);
|
||
if (!m) return false;
|
||
}
|
||
return true;
|
||
});
|
||
|
||
if (!filtered.length) {
|
||
tbody.innerHTML = `<tr><td colspan="5" class="empty" style="text-align:center;padding:30px;color:var(--muted)">${t('no_devices_found', 'Aucun équipement correspondant aux critères de recherche')}</td></tr>`;
|
||
if (empty) empty.style.display = 'none';
|
||
renderPagination('vpnClientsPagination', 1, 0, 'changeVpnClientsPage', 10);
|
||
return;
|
||
}
|
||
if (empty) empty.style.display = 'none';
|
||
|
||
const totalPages = Math.max(1, Math.ceil(filtered.length / 10));
|
||
if (vpnClientsPage > totalPages) vpnClientsPage = totalPages;
|
||
if (vpnClientsPage < 1) vpnClientsPage = 1;
|
||
const paged = filtered.slice((vpnClientsPage - 1) * 10, vpnClientsPage * 10);
|
||
|
||
let html = '';
|
||
paged.forEach(c => {
|
||
const devIcon = getDeviceTypeIcon(c.device_type);
|
||
const devLabel = getDeviceTypeLabel(c.device_type);
|
||
|
||
let effPill = '';
|
||
if (c.online) {
|
||
if (c.routing_status === 'routed') {
|
||
const prof = profiles.find(pr => pr.id === c.profile_id);
|
||
const vLogo = prof ? getVpnTypeBadgeHtml(prof.type, false) : '';
|
||
const ipGeoHtml = (prof && prof.public_ip) ? formatIpWithGeo(prof.public_ip, prof.public_ip_geo) : '';
|
||
effPill = `<div style="display:inline-flex;align-items:center;gap:6px;flex-wrap:wrap">` +
|
||
`<span class="pill pill-green pill-no-dot" style="font-size:11px" title="${t('vpn_routed_tooltip', 'Routé via VPN')}">🟢 ${t('vpn_routed_via', 'Routé via')} <strong>${escapeHtml(c.profile_name)}</strong></span>` +
|
||
`<span class="pill" style="background:rgba(56,189,248,0.12);color:var(--blue);border:1px solid rgba(56,189,248,0.3);font-size:10px" title="${t('vpn_lan_isolated_tooltip', 'Réseau local inaccessible (Isolation LAN active)')}">${t('vpn_lan_isolated', '🔒 Isolé LAN')}</span>` +
|
||
(vLogo ? `<span>${vLogo}</span>` : '') +
|
||
(ipGeoHtml ? `<span>${ipGeoHtml}</span>` : '') +
|
||
`</div>`;
|
||
} else if (c.routing_status === 'blocked') {
|
||
effPill = `<span class="pill" style="background:rgba(255,107,107,.15);color:var(--red);border:1px solid rgba(255,107,107,.3);font-size:11px">${t('vpn_killswitch_blocked', '⚠️ Bloqué (Kill-Switch)')}</span>`;
|
||
} else if (c.routing_status === 'direct_fallback') {
|
||
effPill = `<span class="pill" style="background:rgba(246,173,85,.15);color:#f6ad55;border:1px solid rgba(246,173,85,.3);font-size:11px">${t('vpn_wan_direct_down', '⚠️ WAN Direct (VPN inactif)')}</span>`;
|
||
} else {
|
||
effPill = `<span class="pill" style="background:var(--panel2);color:var(--text);font-size:11px">${t('vpn_wan_direct', '🌐 WAN Direct')}</span>`;
|
||
}
|
||
} else {
|
||
if (c.profile_id > 0) {
|
||
const prof = profiles.find(pr => pr.id === c.profile_id);
|
||
const vLogo = prof ? getVpnTypeBadgeHtml(prof.type, false) : '';
|
||
effPill = `<span class="pill" style="background:rgba(56,189,248,0.08);color:var(--blue);font-size:11px">${t('vpn_assigned_offline', '🛡️ Assigné à')} <strong>${escapeHtml(c.profile_name)}</strong> (${t('status_offline', 'Hors ligne')})</span>` + (vLogo ? ` ${vLogo}` : '');
|
||
} else {
|
||
effPill = `<span class="pill" style="background:var(--panel2);color:var(--muted);font-size:11px">${t('vpn_offline_wan', '⚪ Hors ligne (WAN direct)')}</span>`;
|
||
}
|
||
}
|
||
|
||
let optionsHtml = `<option value="0">${t('vpn_direct', '🌐 Connexion directe WAN (Sans VPN)')}</option>`;
|
||
profiles.forEach(p => {
|
||
const isSel = p.id === c.profile_id;
|
||
const pStatus = p.status === 'connected' ? `🟢 ${t('status_connected', 'Connecté')}` : `🔴 ${t('status_disconnected', 'Déconnecté')}`;
|
||
const pType = p.type === 'wireguard' ? 'WireGuard' : 'OpenVPN';
|
||
const flagStr = (p.public_ip_geo && p.public_ip_geo.code) ? `[${p.public_ip_geo.code}] ` : '';
|
||
const ipTag = p.public_ip ? ` [IP: ${flagStr}${p.public_ip}]` : '';
|
||
optionsHtml += `<option value="${p.id}" ${isSel ? 'selected' : ''}>[${pType}] ${escapeHtml(p.name)}${escapeHtml(ipTag)} (${pStatus})</option>`;
|
||
});
|
||
|
||
const onlineBadge = c.online
|
||
? `<span class="pill pill-green pill-no-dot" style="font-size:10px;padding:1px 6px">🟢 ${t('status_online', 'En ligne')}</span>`
|
||
: `<span class="pill" style="background:var(--panel2);color:var(--muted);font-size:10px;padding:1px 6px">⚪ ${t('status_offline', 'Hors ligne')}</span>`;
|
||
|
||
html += `
|
||
<tr style="border-bottom:1px solid var(--line)">
|
||
<td style="padding:10px 8px">
|
||
<div style="display:flex;align-items:center;gap:10px">
|
||
<div class="avatar" style="font-size:16px">${devIcon}</div>
|
||
<div>
|
||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
|
||
<strong style="font-size:14px">${escapeHtml(c.name)}</strong>
|
||
${onlineBadge}
|
||
</div>
|
||
<div class="muted" style="font-size:11px;margin-top:2px">${escapeHtml(devLabel)}</div>
|
||
</div>
|
||
</div>
|
||
</td>
|
||
<td style="padding:10px 8px">
|
||
<div>${c.ip && c.ip !== 'Non attribuée' ? `<code>${escapeHtml(c.ip)}</code>` : `<span class="muted">${t('not_assigned', 'Non attribuée')}</span>`}</div>
|
||
<div class="muted" style="font-size:11px"><code>${escapeHtml(c.mac)}</code></div>
|
||
</td>
|
||
<td style="padding:10px 8px">
|
||
<select style="margin:0;padding:6px 10px;font-size:13px;border-radius:6px;width:100%" onchange="changeClientVpn('${c.mac}', this.value)">
|
||
${optionsHtml}
|
||
</select>
|
||
</td>
|
||
<td style="padding:10px 8px;text-align:center">
|
||
<label style="display:inline-flex;align-items:center;gap:6px;cursor:pointer;font-size:12px">
|
||
<input type="checkbox" style="width:auto;margin:0" ${c.kill_switch ? 'checked' : ''} onchange="toggleClientKillSwitch('${c.mac}', this.checked)">
|
||
<span>${t('vpn_block_if_down', 'Bloquer si coupé')}</span>
|
||
</label>
|
||
</td>
|
||
<td style="padding:10px 8px">
|
||
${effPill}
|
||
</td>
|
||
</tr>`;
|
||
});
|
||
tbody.innerHTML = html;
|
||
renderPagination('vpnClientsPagination', vpnClientsPage, filtered.length, 'changeVpnClientsPage', 10);
|
||
}
|
||
|
||
async function changeClientVpn(mac, profileId) {
|
||
const client = vpnClientsCache.find(c => c.mac.toUpperCase() === mac.toUpperCase());
|
||
const ks = client ? client.kill_switch : 0;
|
||
try {
|
||
const res = await apiFetch('/api/vpn/clients/assign', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
mac, profile_id: parseInt(profileId, 10), kill_switch: ks
|
||
})
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur');
|
||
loadVpnClients();
|
||
if (typeof loadVpnProfiles === 'function') loadVpnProfiles();
|
||
load();
|
||
loadLogs();
|
||
if (typeof loadTopology === 'function') loadTopology();
|
||
} catch (e) {
|
||
alert(tErr(e.message));
|
||
}
|
||
}
|
||
|
||
async function toggleClientKillSwitch(mac, isEnabled) {
|
||
const client = vpnClientsCache.find(c => c.mac.toUpperCase() === mac.toUpperCase());
|
||
const pid = client ? client.profile_id : 0;
|
||
try {
|
||
const res = await apiFetch('/api/vpn/clients/assign', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({
|
||
mac, profile_id: pid, kill_switch: isEnabled ? 1 : 0
|
||
})
|
||
});
|
||
const d = await res.json();
|
||
if (!res.ok) throw new Error(d.error || 'Erreur');
|
||
loadVpnClients();
|
||
if (typeof loadVpnProfiles === 'function') loadVpnProfiles();
|
||
load();
|
||
loadLogs();
|
||
if (typeof loadTopology === 'function') loadTopology();
|
||
} catch (e) {
|
||
alert(tErr(e.message));
|
||
}
|
||
}
|
||
|
||
|
||
|
||
|
||
</script>
|
||
</body>
|
||
|
||
</html>
|