Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d62758716 | ||
|
|
d26843a0d1 |
+10
-3
@@ -2,11 +2,18 @@
|
||||
APP_PORT=5000
|
||||
SECRET_KEY=change-me-to-a-long-random-string
|
||||
|
||||
# PostgreSQL (used by docker-compose)
|
||||
# PostgreSQL (docker-compose — same password for db + panel via DATABASE_URL)
|
||||
POSTGRES_USER=amnezia
|
||||
POSTGRES_PASSWORD=amnezia
|
||||
POSTGRES_PASSWORD=change-me-strong-password
|
||||
POSTGRES_DB=amnezia_panel
|
||||
POSTGRES_PORT=5432
|
||||
|
||||
# Set once before first deploy. Changing POSTGRES_PASSWORD later requires resetting
|
||||
# the amnezia_pgdata volume or the panel cannot connect (Postgres keeps the old password).
|
||||
|
||||
# Full DSN (override if panel runs outside compose)
|
||||
# DATABASE_URL=postgresql://amnezia:amnezia@db:5432/amnezia_panel
|
||||
# DATABASE_URL=postgresql://amnezia:change-me-strong-password@db:5432/amnezia_panel
|
||||
|
||||
# Dokploy / reverse proxy (optional — set in compose for Docker)
|
||||
# PANEL_IN_DOCKER=1
|
||||
# PANEL_BEHIND_PROXY=1
|
||||
|
||||
@@ -194,38 +194,53 @@ docker compose up -d --build
|
||||
|
||||
Panel: `http://localhost:5000` (or `APP_PORT` from `.env`).
|
||||
|
||||
### Dokploy
|
||||
### Dokploy (recommended)
|
||||
|
||||
The compose file connects the panel to Dokploy's Traefik network (`dokploy-network`) and exposes the app on **container port 5000** (not 80).
|
||||
|
||||
1. Deploy as **Docker Compose** from this repo (Dokploy creates `dokploy-network` automatically).
|
||||
2. In Dokploy → your app → **Domains**:
|
||||
2. In Dokploy → your app → **Environment** (set **before first deploy**):
|
||||
- `SECRET_KEY` — long random string
|
||||
- `POSTGRES_PASSWORD` — strong password (same value is used for `db` and `amnezia_panel`)
|
||||
3. In Dokploy → **Domains**:
|
||||
- **Service**: `amnezia_panel` (not `db`)
|
||||
- **Container port**: `5000`
|
||||
- **Path**: `/`
|
||||
3. Set env vars in Dokploy: `SECRET_KEY` (long random string), strong `POSTGRES_PASSWORD`.
|
||||
4. Redeploy after changing domains or env.
|
||||
4. **Deploy / Rebuild** (not Restart) after code or env changes.
|
||||
|
||||
**Postgres `password authentication failed`:** the database volume keeps the password from the **first** deploy. If you later change `POSTGRES_PASSWORD` in Dokploy, Postgres ignores the new value but the panel uses it in `DATABASE_URL`. Fix: either restore the original password in Dokploy env, or reset the DB volume (wipes panel DB data):
|
||||
**Verify on the server** (replace `PROJECT` and path with yours):
|
||||
|
||||
```bash
|
||||
docker compose -p home-vpn-g6rfpd down
|
||||
docker volume rm home-vpn-g6rfpd_amnezia_pgdata
|
||||
docker compose -p home-vpn-g6rfpd up -d --build
|
||||
```
|
||||
COMPOSE_DIR=/etc/dokploy/compose/home-vpn-g6rfpd/code
|
||||
PROJECT=home-vpn-g6rfpd
|
||||
|
||||
If the domain shows **404 page not found** (plain text, Go-style), Traefik has no route to a healthy backend. After redeploying **v2.5.8+**, on the server run:
|
||||
docker compose -p $PROJECT -f $COMPOSE_DIR/docker-compose.yml exec amnezia_panel \
|
||||
curl -fsS http://127.0.0.1:5000/health
|
||||
# → {"status":"ok","version":"v2.6.0"}
|
||||
|
||||
```bash
|
||||
# 1) Panel must answer HTTP inside the container
|
||||
docker compose -p home-vpn-g6rfpd exec amnezia_panel curl -fsS http://127.0.0.1:5000/health
|
||||
|
||||
# 2) Panel container must be on dokploy-network (required for Traefik)
|
||||
docker inspect "$(docker compose -p home-vpn-g6rfpd ps -q amnezia_panel)" \
|
||||
docker inspect ${PROJECT}-amnezia_panel-1 \
|
||||
--format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}'
|
||||
# must include: dokploy-network
|
||||
```
|
||||
|
||||
You should see `dokploy-network` in the network list. If it is missing, Dokploy cannot route the domain — redeploy with the latest `docker-compose.yml` or run `docker network connect dokploy-network <container>` and redeploy Traefik.
|
||||
**Full redeploy after git update:**
|
||||
|
||||
```bash
|
||||
cd $COMPOSE_DIR && git pull origin main
|
||||
docker compose -p $PROJECT -f $COMPOSE_DIR/docker-compose.yml down
|
||||
docker compose -p $PROJECT -f $COMPOSE_DIR/docker-compose.yml build --no-cache amnezia_panel
|
||||
docker compose -p $PROJECT -f $COMPOSE_DIR/docker-compose.yml up -d --force-recreate
|
||||
```
|
||||
|
||||
**Postgres `password authentication failed`:** the volume keeps the password from the **first** deploy. If you change `POSTGRES_PASSWORD` in Dokploy later, reset the DB volume (wipes panel DB data):
|
||||
|
||||
```bash
|
||||
docker compose -p $PROJECT -f $COMPOSE_DIR/docker-compose.yml down
|
||||
docker volume rm ${PROJECT}_amnezia_pgdata
|
||||
docker compose -p $PROJECT -f $COMPOSE_DIR/docker-compose.yml up -d --build
|
||||
```
|
||||
|
||||
**Domain shows `404 page not found` (plain text):** Traefik has no route to the panel — check Domains (service `amnezia_panel`, port `5000`) and that the container is on `dokploy-network` (see verify commands above).
|
||||
|
||||
| File | Purpose |
|
||||
| --- | --- |
|
||||
@@ -262,12 +277,21 @@ GitHub Actions workflows in `.github/workflows/`:
|
||||
|
||||
## 📋 Fix / changelog (this fork)
|
||||
|
||||
### v2.6.1
|
||||
* **Move connections between servers** — restored: select configs on a server page and move to another server (recreates peers, keeps user links). `ToggleConnectionRequest` kept intact.
|
||||
|
||||
### v2.6.0 — stable Dokploy / Docker release
|
||||
* **Dokploy-ready compose** — `dokploy-network`, Traefik labels, port **5000**, no fixed `container_name`.
|
||||
* **Docker startup** — `uvicorn` with proxy headers; SSL inside container disabled when `PANEL_IN_DOCKER` / `PANEL_BEHIND_PROXY`.
|
||||
* **Postgres healthcheck** — verifies password (catches `POSTGRES_PASSWORD` vs volume mismatch).
|
||||
* **Rollback move-connections** — removed server-to-server config move (v2.5.4); restored `ToggleConnectionRequest` (fixes crash loop on deploy).
|
||||
* **Docs** — full Dokploy deploy/redeploy/password-reset guide in README.
|
||||
|
||||
### v2.5.11
|
||||
* **Postgres healthcheck** — verifies DB password (surfaces `POSTGRES_PASSWORD` / volume mismatch before panel starts).
|
||||
|
||||
### v2.5.10
|
||||
* **Docker startup** — run `uvicorn` directly in `CMD` (no shell entrypoint); rebuild required after deploy.
|
||||
* **Postgres healthcheck** — verifies password, not only `pg_isready` (catches `POSTGRES_PASSWORD` mismatch with existing volume).
|
||||
|
||||
### v2.5.9
|
||||
* **Remove move connections between servers** — feature rolled back; fixes startup crash (`ToggleConnectionRequest` was missing after v2.5.4).
|
||||
|
||||
@@ -103,7 +103,7 @@ else:
|
||||
application_path = os.path.dirname(__file__)
|
||||
|
||||
DATA_FILE = os.path.join(application_path, 'data.json') # legacy JSON; used only for one-shot import / export
|
||||
CURRENT_VERSION = "v2.5.11"
|
||||
CURRENT_VERSION = "v2.6.1"
|
||||
RELEASES_REPO_URL = repo_url()
|
||||
RELEASES_API_LATEST = api_latest_url()
|
||||
BIN_DIR = os.environ.get('TUNNEL_BIN_DIR', os.path.join(application_path, 'bin'))
|
||||
@@ -1396,6 +1396,186 @@ async def perform_toggle_user(data: dict, user_id: str, enable: bool) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def resolve_protocol_on_server(server: dict, protocol: str) -> Optional[str]:
|
||||
"""Pick an installed protocol key on server matching the requested protocol/base."""
|
||||
protocols = server.get('protocols') or {}
|
||||
if protocol in protocols and protocols[protocol].get('installed'):
|
||||
return protocol
|
||||
base = protocol_base(protocol)
|
||||
candidates = [
|
||||
key for key, info in protocols.items()
|
||||
if protocol_base(key) == base and info.get('installed')
|
||||
]
|
||||
if not candidates:
|
||||
return None
|
||||
return sorted(candidates, key=protocol_instance)[0]
|
||||
|
||||
|
||||
def _client_display_name(client: dict) -> str:
|
||||
user_data = client.get('userData') or {}
|
||||
return (
|
||||
user_data.get('clientName')
|
||||
or client.get('clientName')
|
||||
or client.get('clientId')
|
||||
or 'Connection'
|
||||
)
|
||||
|
||||
|
||||
def _create_remote_client(manager, protocol: str, server: dict, name: str, source_client: Optional[dict] = None):
|
||||
proto_info = server.get('protocols', {}).get(protocol, {})
|
||||
port = proto_info.get('port', '55424')
|
||||
base = protocol_base(protocol)
|
||||
if base == 'telemt':
|
||||
user_data = (source_client or {}).get('userData') or {}
|
||||
return manager.add_client(
|
||||
protocol, name, server['host'], port,
|
||||
telemt_quota=user_data.get('quota'),
|
||||
telemt_expiry=user_data.get('expiry'),
|
||||
secret=user_data.get('token'),
|
||||
user_ad_tag=user_data.get('user_ad_tag'),
|
||||
max_tcp_conns=user_data.get('max_tcp_conns'),
|
||||
)
|
||||
if base == 'wireguard':
|
||||
return manager.add_client(name, server['host'])
|
||||
return manager.add_client(protocol, name, server['host'], port)
|
||||
|
||||
|
||||
def _move_connections_sync(
|
||||
source_server_id: int,
|
||||
target_server_id: int,
|
||||
protocol: str,
|
||||
client_ids: List[str],
|
||||
target_protocol: Optional[str] = None,
|
||||
delete_source: bool = True,
|
||||
) -> dict:
|
||||
data = load_data()
|
||||
if source_server_id >= len(data['servers']) or target_server_id >= len(data['servers']):
|
||||
raise ValueError('Server not found')
|
||||
if source_server_id == target_server_id:
|
||||
raise ValueError('Source and target server must be different')
|
||||
if protocol_base(protocol) == 'xui':
|
||||
raise ValueError('Moving 3x-ui connections between servers is not supported')
|
||||
|
||||
source_server = data['servers'][source_server_id]
|
||||
target_server = data['servers'][target_server_id]
|
||||
resolved_target_protocol = target_protocol or resolve_protocol_on_server(target_server, protocol)
|
||||
if not resolved_target_protocol:
|
||||
raise ValueError(
|
||||
f'Target server does not have {protocol_display_name(protocol)} installed'
|
||||
)
|
||||
|
||||
source_ssh = get_ssh(source_server)
|
||||
target_ssh = get_ssh(target_server)
|
||||
source_ssh.connect()
|
||||
target_ssh.connect()
|
||||
|
||||
source_manager = get_protocol_manager(source_ssh, protocol)
|
||||
source_clients = _manager_call(source_manager, 'get_clients', protocol) or []
|
||||
clients_map = {c.get('clientId'): c for c in source_clients if c.get('clientId')}
|
||||
|
||||
target_manager = get_protocol_manager(target_ssh, resolved_target_protocol)
|
||||
moved = []
|
||||
failed = []
|
||||
|
||||
try:
|
||||
for client_id in client_ids:
|
||||
client = clients_map.get(client_id)
|
||||
if not client:
|
||||
failed.append({'client_id': client_id, 'error': 'Client not found on source server'})
|
||||
continue
|
||||
|
||||
user_data = client.get('userData') or {}
|
||||
base = protocol_base(protocol)
|
||||
if user_data.get('externalClient') and not user_data.get('clientPrivateKey') and base in (
|
||||
'awg', 'awg2', 'awg_legacy', 'wireguard',
|
||||
):
|
||||
failed.append({
|
||||
'client_id': client_id,
|
||||
'error': 'External/native client cannot be moved (no private key)',
|
||||
})
|
||||
continue
|
||||
|
||||
name = _client_display_name(client)
|
||||
enabled = client.get('enabled', True)
|
||||
if user_data.get('enabled') is False:
|
||||
enabled = False
|
||||
|
||||
try:
|
||||
created = _create_remote_client(
|
||||
target_manager, resolved_target_protocol, target_server, name, client,
|
||||
)
|
||||
new_client_id = created.get('client_id')
|
||||
if not new_client_id:
|
||||
failed.append({'client_id': client_id, 'error': 'Failed to create client on target server'})
|
||||
continue
|
||||
|
||||
if not enabled:
|
||||
_manager_call(
|
||||
target_manager, 'toggle_client',
|
||||
resolved_target_protocol, new_client_id, False,
|
||||
)
|
||||
|
||||
user_conn = next(
|
||||
(
|
||||
uc for uc in data.get('user_connections', [])
|
||||
if uc.get('client_id') == client_id
|
||||
and uc.get('server_id') == source_server_id
|
||||
and uc.get('protocol') == protocol
|
||||
),
|
||||
None,
|
||||
)
|
||||
if user_conn:
|
||||
user_conn['server_id'] = target_server_id
|
||||
user_conn['client_id'] = new_client_id
|
||||
user_conn['protocol'] = resolved_target_protocol
|
||||
user_conn['name'] = name
|
||||
elif client.get('assigned_user_id'):
|
||||
data.setdefault('user_connections', []).append({
|
||||
'id': str(uuid.uuid4()),
|
||||
'user_id': client['assigned_user_id'],
|
||||
'server_id': target_server_id,
|
||||
'protocol': resolved_target_protocol,
|
||||
'client_id': new_client_id,
|
||||
'name': name,
|
||||
'created_at': datetime.now().isoformat(),
|
||||
})
|
||||
|
||||
if delete_source:
|
||||
_manager_call(source_manager, 'remove_client', protocol, client_id)
|
||||
data['user_connections'] = [
|
||||
uc for uc in data.get('user_connections', [])
|
||||
if not (
|
||||
uc.get('client_id') == client_id
|
||||
and uc.get('server_id') == source_server_id
|
||||
and uc.get('protocol') == protocol
|
||||
)
|
||||
]
|
||||
|
||||
moved.append({
|
||||
'client_id': client_id,
|
||||
'new_client_id': new_client_id,
|
||||
'name': name,
|
||||
})
|
||||
except Exception as exc:
|
||||
logger.exception('Failed to move client %s', client_id)
|
||||
failed.append({'client_id': client_id, 'error': str(exc)})
|
||||
finally:
|
||||
source_ssh.disconnect()
|
||||
target_ssh.disconnect()
|
||||
|
||||
if moved:
|
||||
save_data(data)
|
||||
|
||||
return {
|
||||
'status': 'success' if moved else 'error',
|
||||
'moved': moved,
|
||||
'failed': failed,
|
||||
'target_server_id': target_server_id,
|
||||
'target_protocol': resolved_target_protocol,
|
||||
'message': f'Moved {len(moved)} connection(s)' + (f', {len(failed)} failed' if failed else ''),
|
||||
}
|
||||
|
||||
|
||||
async def perform_mass_operations(delete_uids: List[str] = None, toggle_uids: List[tuple] = None, create_conns: List[dict] = None):
|
||||
"""
|
||||
Executes multiple SSH operations efficiently.
|
||||
@@ -2020,6 +2200,14 @@ class ToggleConnectionRequest(BaseModel):
|
||||
enable: bool = True
|
||||
|
||||
|
||||
class MoveConnectionsRequest(BaseModel):
|
||||
protocol: str = 'awg'
|
||||
target_server_id: int
|
||||
client_ids: List[str]
|
||||
target_protocol: Optional[str] = None
|
||||
delete_source: bool = True
|
||||
|
||||
|
||||
class AddUserRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
@@ -2560,12 +2748,21 @@ async def server_detail(request: Request, server_id: int):
|
||||
return RedirectResponse(url='/')
|
||||
server = data['servers'][server_id]
|
||||
users_list = data.get('users', [])
|
||||
servers_for_move = [
|
||||
{
|
||||
'id': idx,
|
||||
'name': srv.get('name') or srv.get('host') or f'Server {idx + 1}',
|
||||
'host': srv.get('host') or '',
|
||||
}
|
||||
for idx, srv in enumerate(data['servers'])
|
||||
]
|
||||
return tpl(
|
||||
request,
|
||||
'server.html',
|
||||
server=server,
|
||||
server_id=server_id,
|
||||
users=users_list,
|
||||
servers_for_move=servers_for_move,
|
||||
)
|
||||
|
||||
|
||||
@@ -4381,6 +4578,35 @@ async def api_get_connection_config(request: Request, server_id: int, req: Conne
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
|
||||
|
||||
@app.post('/api/servers/{server_id}/connections/move', tags=["Connections"])
|
||||
async def api_move_connections(request: Request, server_id: int, req: MoveConnectionsRequest):
|
||||
if not _check_admin(request):
|
||||
return JSONResponse({'error': 'Forbidden'}, status_code=403)
|
||||
if not req.client_ids:
|
||||
return JSONResponse({'error': 'No connections selected'}, status_code=400)
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
_move_connections_sync,
|
||||
server_id,
|
||||
req.target_server_id,
|
||||
req.protocol,
|
||||
req.client_ids,
|
||||
req.target_protocol,
|
||||
bool(req.delete_source),
|
||||
)
|
||||
if not result.get('moved'):
|
||||
return JSONResponse(
|
||||
{'error': result.get('message') or 'Move failed', **result},
|
||||
status_code=400,
|
||||
)
|
||||
return result
|
||||
except ValueError as e:
|
||||
return JSONResponse({'error': str(e)}, status_code=400)
|
||||
except Exception as e:
|
||||
logger.exception('Error moving connections')
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
|
||||
|
||||
@app.post('/api/servers/{server_id}/connections/toggle', tags=["Connections"])
|
||||
async def api_toggle_connection(request: Request, server_id: int, req: ToggleConnectionRequest):
|
||||
if not _check_admin(request):
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
PORT="${PORT:-${APP_PORT:-5000}}"
|
||||
|
||||
echo "Waiting for PostgreSQL at ${DATABASE_URL%%@*}@…"
|
||||
python3 - <<'PY'
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
url = os.environ.get("DATABASE_URL", "").strip()
|
||||
if not url:
|
||||
print("DATABASE_URL is not set", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
import psycopg
|
||||
|
||||
deadline = time.time() + 120
|
||||
last_err = None
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with psycopg.connect(url, connect_timeout=5):
|
||||
break
|
||||
except Exception as exc:
|
||||
last_err = exc
|
||||
time.sleep(2)
|
||||
else:
|
||||
print(f"PostgreSQL not ready: {last_err}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
PY
|
||||
|
||||
echo "Starting Amnezia Web Panel on 0.0.0.0:${PORT}"
|
||||
exec uvicorn app:app \
|
||||
--host 0.0.0.0 \
|
||||
--port "${PORT}" \
|
||||
--proxy-headers \
|
||||
--forwarded-allow-ips='*'
|
||||
@@ -1295,6 +1295,45 @@ a:hover {
|
||||
background: var(--bg-card-hover);
|
||||
}
|
||||
|
||||
.conn-select-wrap {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.conn-select {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.connections-bulk-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-md);
|
||||
margin-bottom: var(--space-sm);
|
||||
padding: var(--space-sm) var(--space-md);
|
||||
border: 1px dashed var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-secondary);
|
||||
}
|
||||
|
||||
.connections-select-all {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.connections-selected-count {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.client-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -544,12 +544,23 @@
|
||||
<option value="telemt">Telemt</option>
|
||||
<option value="wireguard">WireGuard</option>
|
||||
</select>
|
||||
<button type="button" class="btn btn-secondary btn-sm hidden" id="moveConnectionsBtn" onclick="openMoveConnectionsModal()">
|
||||
<span>{{ icon('share') }}</span> {{ _('move_connections') }}
|
||||
</button>
|
||||
<button class="btn btn-primary btn-sm" onclick="openAddConnectionModal()">
|
||||
<span>{{ icon('plus') }}</span> {{ _('add') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="connectionsBulkBar" class="connections-bulk-bar hidden">
|
||||
<label class="connections-select-all">
|
||||
<input type="checkbox" id="connSelectAll" onchange="toggleSelectAllConnections(this.checked)">
|
||||
<span>{{ _('select_all') }}</span>
|
||||
</label>
|
||||
<span class="connections-selected-count" id="connSelectedCount">0</span>
|
||||
</div>
|
||||
|
||||
<div id="connectionsList">
|
||||
<div class="loading-overlay" id="connectionsLoading" style="display:none;">
|
||||
<div class="loading-spinner"></div>
|
||||
@@ -969,6 +980,35 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== Move Connections Modal ===== -->
|
||||
<div class="modal-backdrop" id="moveConnectionsModal">
|
||||
<div class="modal" style="max-width: 520px;">
|
||||
<div class="modal-header">
|
||||
<h2 class="modal-title">{{ _('move_connections_title') }}</h2>
|
||||
<button class="modal-close" onclick="closeModal('moveConnectionsModal')">×</button>
|
||||
</div>
|
||||
<p class="form-hint">{{ _('move_connections_hint') }}</p>
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="moveTargetServer">{{ _('move_connections_target') }}</label>
|
||||
<select class="form-select" id="moveTargetServer"></select>
|
||||
</div>
|
||||
<label class="form-check" style="display:flex; align-items:center; gap:var(--space-sm); margin-bottom: var(--space-md);">
|
||||
<input type="checkbox" id="moveDeleteSource" checked>
|
||||
<span>{{ _('move_connections_delete_source') }}</span>
|
||||
</label>
|
||||
<div class="form-hint" style="border-left: 3px solid var(--warning); padding-left: var(--space-sm);">
|
||||
{{ _('move_connections_warning') }}
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" onclick="closeModal('moveConnectionsModal')">{{ _('cancel') }}</button>
|
||||
<button type="button" class="btn btn-primary" onclick="moveSelectedConnections()" id="moveConnectionsSubmitBtn">
|
||||
<span id="moveConnectionsSubmitText">{{ _('move_connections') }}</span>
|
||||
<div class="spinner hidden" id="moveConnectionsSpinner" style="width:14px; height:14px;"></div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== Connection Config Modal (with Tabs) ===== -->
|
||||
<div class="modal-backdrop" id="configModal">
|
||||
<div class="modal" style="max-width: 600px;">
|
||||
@@ -1090,6 +1130,7 @@
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/htmlmixed/htmlmixed.min.js"></script>
|
||||
<script>
|
||||
const SERVER_ID = {{ server_id }};
|
||||
const ALL_SERVERS = {{ servers_for_move | tojson }};
|
||||
const SERVER_HOST = "{{ server.host }}";
|
||||
const SERVER_SSL_DOMAIN = {{ ((server.server_info or {}).get('ssl_domain') or '') | tojson }};
|
||||
const SERVER_SSL_EMAIL = {{ ((server.server_info or {}).get('ssl_email') or '') | tojson }};
|
||||
@@ -2608,6 +2649,95 @@
|
||||
document.getElementById('connectionsSection').scrollIntoView({ behavior: 'smooth' });
|
||||
}
|
||||
|
||||
const selectedConnectionIds = new Set();
|
||||
|
||||
function updateMoveSelection() {
|
||||
selectedConnectionIds.clear();
|
||||
document.querySelectorAll('.conn-select:checked').forEach((el) => {
|
||||
if (el.dataset.clientId) selectedConnectionIds.add(el.dataset.clientId);
|
||||
});
|
||||
const count = selectedConnectionIds.size;
|
||||
const bulkBar = document.getElementById('connectionsBulkBar');
|
||||
const moveBtn = document.getElementById('moveConnectionsBtn');
|
||||
const countEl = document.getElementById('connSelectedCount');
|
||||
const selectAll = document.getElementById('connSelectAll');
|
||||
const boxes = document.querySelectorAll('.conn-select');
|
||||
if (bulkBar) bulkBar.classList.toggle('hidden', boxes.length === 0);
|
||||
if (moveBtn) moveBtn.classList.toggle('hidden', boxes.length === 0);
|
||||
if (countEl) countEl.textContent = _('connections_selected_count').replace('{}', String(count));
|
||||
if (selectAll) {
|
||||
selectAll.indeterminate = count > 0 && count < boxes.length;
|
||||
selectAll.checked = boxes.length > 0 && count === boxes.length;
|
||||
}
|
||||
}
|
||||
|
||||
function toggleSelectAllConnections(checked) {
|
||||
document.querySelectorAll('.conn-select').forEach((el) => { el.checked = checked; });
|
||||
updateMoveSelection();
|
||||
}
|
||||
|
||||
function openMoveConnectionsModal() {
|
||||
if (!selectedConnectionIds.size) {
|
||||
showToast(_('move_connections_none_selected'), 'error');
|
||||
return;
|
||||
}
|
||||
const select = document.getElementById('moveTargetServer');
|
||||
select.innerHTML = '';
|
||||
(ALL_SERVERS || []).forEach((srv) => {
|
||||
if (srv.id === SERVER_ID) return;
|
||||
const opt = document.createElement('option');
|
||||
opt.value = String(srv.id);
|
||||
opt.textContent = `${srv.name} (${srv.host})`;
|
||||
select.appendChild(opt);
|
||||
});
|
||||
if (!select.options.length) {
|
||||
showToast(_('move_connections_no_targets'), 'error');
|
||||
return;
|
||||
}
|
||||
openModal('moveConnectionsModal');
|
||||
}
|
||||
|
||||
async function moveSelectedConnections() {
|
||||
const targetServerId = parseInt(document.getElementById('moveTargetServer').value, 10);
|
||||
const deleteSource = document.getElementById('moveDeleteSource').checked;
|
||||
const proto = document.getElementById('connProtoSelect').value;
|
||||
const clientIds = Array.from(selectedConnectionIds);
|
||||
if (!clientIds.length || Number.isNaN(targetServerId)) {
|
||||
showToast(_('move_connections_none_selected'), 'error');
|
||||
return;
|
||||
}
|
||||
if (!confirm(_('move_connections_confirm').replace('{}', String(clientIds.length)))) return;
|
||||
|
||||
const btn = document.getElementById('moveConnectionsSubmitBtn');
|
||||
const text = document.getElementById('moveConnectionsSubmitText');
|
||||
const spinner = document.getElementById('moveConnectionsSpinner');
|
||||
btn.disabled = true;
|
||||
spinner.classList.remove('hidden');
|
||||
text.textContent = _('loading');
|
||||
try {
|
||||
const data = await apiCall(`/api/servers/${SERVER_ID}/connections/move`, 'POST', {
|
||||
protocol: proto,
|
||||
target_server_id: targetServerId,
|
||||
client_ids: clientIds,
|
||||
delete_source: deleteSource,
|
||||
});
|
||||
const moved = (data.moved || []).length;
|
||||
const failed = (data.failed || []).length;
|
||||
let msg = _('move_connections_success').replace('{}', String(moved));
|
||||
if (failed) msg += '. ' + _('move_connections_partial_fail').replace('{}', String(failed));
|
||||
showToast(msg, failed && !moved ? 'error' : 'success');
|
||||
closeModal('moveConnectionsModal');
|
||||
selectedConnectionIds.clear();
|
||||
loadConnections();
|
||||
} catch (err) {
|
||||
showToast(_('error') + ': ' + err.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
spinner.classList.add('hidden');
|
||||
text.textContent = _('move_connections');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadConnections() {
|
||||
const proto = document.getElementById('connProtoSelect').value;
|
||||
const loading = document.getElementById('connectionsLoading');
|
||||
@@ -2622,11 +2752,14 @@
|
||||
loading.style.display = '';
|
||||
emptyEl.classList.add('hidden');
|
||||
listEl.innerHTML = '';
|
||||
selectedConnectionIds.clear();
|
||||
updateMoveSelection();
|
||||
try {
|
||||
const data = await apiCall(`/api/servers/${SERVER_ID}/connections?protocol=${proto}`);
|
||||
loading.style.display = 'none';
|
||||
if (!data.clients || data.clients.length === 0) {
|
||||
emptyEl.classList.remove('hidden');
|
||||
updateMoveSelection();
|
||||
return;
|
||||
}
|
||||
window.connectionsStore = {};
|
||||
@@ -2670,6 +2803,9 @@
|
||||
|
||||
listEl.innerHTML += `
|
||||
<div class="client-item" style="${disabledStyle}">
|
||||
<label class="conn-select-wrap">
|
||||
<input type="checkbox" class="conn-select" data-client-id="${escapeJs(client.clientId)}" onchange="updateMoveSelection()">
|
||||
</label>
|
||||
<div class="client-info">
|
||||
<div class="client-avatar">${initial}</div>
|
||||
<div>
|
||||
@@ -2686,6 +2822,7 @@
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
updateMoveSelection();
|
||||
} catch (err) {
|
||||
loading.style.display = 'none';
|
||||
showToast(_('connections_load_error') + ': ' + err.message, 'error');
|
||||
|
||||
@@ -101,6 +101,19 @@
|
||||
"connection_created": "Connection \"{}\" created",
|
||||
"delete_connection_confirm": "Delete this connection? The configuration will stop working.",
|
||||
"connection_deleted": "Connection deleted",
|
||||
"select_all": "Select all",
|
||||
"connections_selected_count": "{} selected",
|
||||
"move_connections": "Move",
|
||||
"move_connections_title": "Move connections to another server",
|
||||
"move_connections_target": "Target server",
|
||||
"move_connections_confirm": "Move {} connection(s) to the selected server? Users will need new configs.",
|
||||
"move_connections_hint": "Recreates selected connections on the target server and updates user assignments.",
|
||||
"move_connections_warning": "Clients get new keys and IPs. Old configs stop working after move.",
|
||||
"move_connections_delete_source": "Remove from current server after move",
|
||||
"move_connections_success": "Moved {} connection(s)",
|
||||
"move_connections_partial_fail": "{} could not be moved",
|
||||
"move_connections_none_selected": "Select at least one connection",
|
||||
"move_connections_no_targets": "No other servers available",
|
||||
"config_tab": "📄 Config",
|
||||
"vpn_key_tab": "🔑 VPN-key",
|
||||
"qr_code_tab": "📱 QR-code",
|
||||
|
||||
@@ -100,6 +100,19 @@
|
||||
"connection_created": "اتصال \"{}\" ایجاد شد",
|
||||
"delete_connection_confirm": "این اتصال حذف شود؟ پیکربندی دیگر کار نخواهد کرد.",
|
||||
"connection_deleted": "اتصال حذف شد",
|
||||
"select_all": "انتخاب همه",
|
||||
"connections_selected_count": "{} انتخاب شده",
|
||||
"move_connections": "انتقال",
|
||||
"move_connections_title": "انتقال اتصالها به سرور دیگر",
|
||||
"move_connections_target": "سرور مقصد",
|
||||
"move_connections_confirm": "{} اتصال به سرور انتخابشده منتقل شود؟ کاربران به پیکربندی جدید نیاز دارند.",
|
||||
"move_connections_hint": "اتصالهای انتخابشده روی سرور مقصد دوباره ساخته میشوند و پیوند کاربران حفظ میشود.",
|
||||
"move_connections_warning": "کلیدها و IP جدید صادر میشود. پیکربندیهای قدیمی کار نمیکنند.",
|
||||
"move_connections_delete_source": "پس از انتقال از سرور فعلی حذف شود",
|
||||
"move_connections_success": "{} اتصال منتقل شد",
|
||||
"move_connections_partial_fail": "{} منتقل نشد",
|
||||
"move_connections_none_selected": "حداقل یک اتصال انتخاب کنید",
|
||||
"move_connections_no_targets": "سرور دیگری برای انتقال وجود ندارد",
|
||||
"config_tab": "📄 فایل",
|
||||
"vpn_key_tab": "🔑 کلید-VPN",
|
||||
"qr_code_tab": "📱 کد-QR",
|
||||
|
||||
@@ -100,6 +100,19 @@
|
||||
"connection_created": "Connexion \"{}\" créée",
|
||||
"delete_connection_confirm": "Supprimer cette connexion ? Elle cessera de fonctionner.",
|
||||
"connection_deleted": "Connexion supprimée",
|
||||
"select_all": "Tout sélectionner",
|
||||
"connections_selected_count": "{} sélectionné(s)",
|
||||
"move_connections": "Déplacer",
|
||||
"move_connections_title": "Déplacer les connexions vers un autre serveur",
|
||||
"move_connections_target": "Serveur cible",
|
||||
"move_connections_confirm": "Déplacer {} connexion(s) vers le serveur sélectionné ? Les utilisateurs auront besoin de nouveaux configs.",
|
||||
"move_connections_hint": "Recrée les connexions sur le serveur cible et conserve les affectations utilisateur.",
|
||||
"move_connections_warning": "Les clients reçoivent de nouvelles clés et IP. Les anciens configs cessent de fonctionner.",
|
||||
"move_connections_delete_source": "Supprimer du serveur actuel après le déplacement",
|
||||
"move_connections_success": "{} connexion(s) déplacée(s)",
|
||||
"move_connections_partial_fail": "{} n'ont pas pu être déplacées",
|
||||
"move_connections_none_selected": "Sélectionnez au moins une connexion",
|
||||
"move_connections_no_targets": "Aucun autre serveur disponible",
|
||||
"config_tab": "📄 Config",
|
||||
"vpn_key_tab": "🔑 Clé-VPN",
|
||||
"qr_code_tab": "📱 Code-QR",
|
||||
|
||||
@@ -101,6 +101,19 @@
|
||||
"connection_created": "Подключение \"{}\" создано",
|
||||
"delete_connection_confirm": "Удалить это подключение? Конфигурация перестанет работать.",
|
||||
"connection_deleted": "Подключение удалено",
|
||||
"select_all": "Выбрать все",
|
||||
"connections_selected_count": "Выбрано: {}",
|
||||
"move_connections": "Перенести",
|
||||
"move_connections_title": "Перенос подключений на другой сервер",
|
||||
"move_connections_target": "Целевой сервер",
|
||||
"move_connections_confirm": "Перенести {} подключение(й) на выбранный сервер? Пользователям понадобятся новые конфиги.",
|
||||
"move_connections_hint": "Подключения будут созданы заново на целевом сервере, привязки к пользователям сохранятся.",
|
||||
"move_connections_warning": "У клиентов будут новые ключи и IP. Старые конфиги перестанут работать.",
|
||||
"move_connections_delete_source": "Удалить с текущего сервера после переноса",
|
||||
"move_connections_success": "Перенесено подключений: {}",
|
||||
"move_connections_partial_fail": "Не удалось перенести: {}",
|
||||
"move_connections_none_selected": "Выберите хотя бы одно подключение",
|
||||
"move_connections_no_targets": "Нет других серверов для переноса",
|
||||
"config_tab": "📄 Конфиг",
|
||||
"vpn_key_tab": "🔑 VPN-ключ",
|
||||
"qr_code_tab": "📱 QR-код",
|
||||
|
||||
@@ -100,6 +100,19 @@
|
||||
"connection_created": "连接 \"{}\" 已创建",
|
||||
"delete_connection_confirm": "确定删除此连接?配置将失效。",
|
||||
"connection_deleted": "连接已删除",
|
||||
"select_all": "全选",
|
||||
"connections_selected_count": "已选 {}",
|
||||
"move_connections": "迁移",
|
||||
"move_connections_title": "将连接迁移到另一台服务器",
|
||||
"move_connections_target": "目标服务器",
|
||||
"move_connections_confirm": "将 {} 个连接迁移到所选服务器?用户需要新的配置。",
|
||||
"move_connections_hint": "在目标服务器上重新创建所选连接,并保留用户绑定。",
|
||||
"move_connections_warning": "客户端将获得新密钥和 IP,旧配置将失效。",
|
||||
"move_connections_delete_source": "迁移后从当前服务器删除",
|
||||
"move_connections_success": "已迁移 {} 个连接",
|
||||
"move_connections_partial_fail": "{} 个无法迁移",
|
||||
"move_connections_none_selected": "请至少选择一个连接",
|
||||
"move_connections_no_targets": "没有其他可用服务器",
|
||||
"config_tab": "📄 配置文件",
|
||||
"vpn_key_tab": "🔑 VPN 密钥",
|
||||
"qr_code_tab": "📱 二维码",
|
||||
|
||||
Reference in New Issue
Block a user