wip
This commit is contained in:
parent
0a31714a93
commit
66fe31eabe
3 changed files with 419 additions and 206 deletions
|
@ -19,6 +19,7 @@ import markdown
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from flask import flash
|
from flask import flash
|
||||||
from app.utils.app_utils import is_port_in_use, validate_port_data
|
from app.utils.app_utils import is_port_in_use, validate_port_data
|
||||||
|
from difflib import SequenceMatcher
|
||||||
|
|
||||||
bp = Blueprint("api", __name__, url_prefix="/api")
|
bp = Blueprint("api", __name__, url_prefix="/api")
|
||||||
csrf = CSRFProtect()
|
csrf = CSRFProtect()
|
||||||
|
@ -424,7 +425,7 @@ def get_free_port(server_id):
|
||||||
@bp.route("/validate/app-name", methods=["GET"])
|
@bp.route("/validate/app-name", methods=["GET"])
|
||||||
@login_required
|
@login_required
|
||||||
def validate_app_name():
|
def validate_app_name():
|
||||||
"""API endpoint to validate application name in real-time"""
|
"""API endpoint to validate application name in real-time with fuzzy matching"""
|
||||||
name = request.args.get("name", "").strip()
|
name = request.args.get("name", "").strip()
|
||||||
server_id = request.args.get("server_id")
|
server_id = request.args.get("server_id")
|
||||||
app_id = request.args.get("app_id")
|
app_id = request.args.get("app_id")
|
||||||
|
@ -448,18 +449,41 @@ def validate_app_name():
|
||||||
"edit_url": url_for('dashboard.app_edit', app_id=existing_app.id)
|
"edit_url": url_for('dashboard.app_edit', app_id=existing_app.id)
|
||||||
})
|
})
|
||||||
|
|
||||||
# Check for similar names
|
# Get all apps on this server for similarity check
|
||||||
similar_apps = App.query.filter(
|
server_apps = App.query.filter(App.server_id == server_id).all()
|
||||||
App.name.ilike(f"%{name}%"),
|
|
||||||
App.server_id == server_id
|
|
||||||
).limit(3).all()
|
|
||||||
|
|
||||||
if similar_apps and (not app_id or not any(str(app.id) == app_id for app in similar_apps)):
|
# Filter out the current app if we're editing
|
||||||
similar_names = [{"name": app.name, "id": app.id} for app in similar_apps]
|
if app_id:
|
||||||
|
server_apps = [app for app in server_apps if str(app.id) != app_id]
|
||||||
|
|
||||||
|
# Find similar apps using fuzzy matching
|
||||||
|
similar_apps = []
|
||||||
|
|
||||||
|
for app in server_apps:
|
||||||
|
# Calculate similarity ratio using SequenceMatcher
|
||||||
|
similarity = SequenceMatcher(None, name.lower(), app.name.lower()).ratio()
|
||||||
|
|
||||||
|
# Consider similar if:
|
||||||
|
# 1. One is a substring of the other OR
|
||||||
|
# 2. They have high similarity ratio (over 0.7)
|
||||||
|
is_substring = name.lower() in app.name.lower() or app.name.lower() in name.lower()
|
||||||
|
is_similar = similarity > 0.7
|
||||||
|
|
||||||
|
if (is_substring or is_similar) and len(name) >= 3:
|
||||||
|
similar_apps.append({
|
||||||
|
"name": app.name,
|
||||||
|
"id": app.id,
|
||||||
|
"similarity": similarity
|
||||||
|
})
|
||||||
|
|
||||||
|
# Sort by similarity (highest first) and limit to top 3
|
||||||
|
similar_apps = sorted(similar_apps, key=lambda x: x["similarity"], reverse=True)[:3]
|
||||||
|
|
||||||
|
if similar_apps:
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"valid": True,
|
"valid": True,
|
||||||
"warning": "Similar application names found",
|
"warning": "Similar application names found",
|
||||||
"similar_apps": similar_names
|
"similar_apps": similar_apps
|
||||||
})
|
})
|
||||||
|
|
||||||
return jsonify({"valid": True})
|
return jsonify({"valid": True})
|
||||||
|
|
|
@ -234,6 +234,27 @@ def app_new(server_id=None):
|
||||||
documentation = request.form.get("documentation", "")
|
documentation = request.form.get("documentation", "")
|
||||||
url = request.form.get("url", "")
|
url = request.form.get("url", "")
|
||||||
|
|
||||||
|
# Validate application name
|
||||||
|
if not name:
|
||||||
|
flash("Application name is required", "danger")
|
||||||
|
return render_template(
|
||||||
|
"dashboard/app_form.html",
|
||||||
|
edit_mode=False,
|
||||||
|
servers=servers,
|
||||||
|
selected_server_id=server_id
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check for duplicate application names on the same server
|
||||||
|
existing_app = App.query.filter_by(name=name, server_id=server_id).first()
|
||||||
|
if existing_app:
|
||||||
|
flash(f"An application with the name '{name}' already exists on this server", "danger")
|
||||||
|
return render_template(
|
||||||
|
"dashboard/app_form.html",
|
||||||
|
edit_mode=False,
|
||||||
|
servers=servers,
|
||||||
|
selected_server_id=server_id
|
||||||
|
)
|
||||||
|
|
||||||
# Process port data from form
|
# Process port data from form
|
||||||
port_data = []
|
port_data = []
|
||||||
port_numbers = request.form.getlist("port_numbers[]")
|
port_numbers = request.form.getlist("port_numbers[]")
|
||||||
|
@ -245,36 +266,75 @@ def app_new(server_id=None):
|
||||||
protocol = protocols[i] if i < len(protocols) else "TCP"
|
protocol = protocols[i] if i < len(protocols) else "TCP"
|
||||||
description = descriptions[i] if i < len(descriptions) else ""
|
description = descriptions[i] if i < len(descriptions) else ""
|
||||||
port_data.append((port_numbers[i], protocol, description))
|
port_data.append((port_numbers[i], protocol, description))
|
||||||
|
|
||||||
|
# Check for port conflicts proactively
|
||||||
|
conflicts = []
|
||||||
|
seen_ports = set() # To track ports already seen in this submission
|
||||||
|
|
||||||
|
for i, (port_number, protocol, _) in enumerate(port_data):
|
||||||
|
try:
|
||||||
|
clean_port = int(port_number)
|
||||||
|
# Check if this port has already been seen in this submission
|
||||||
|
port_key = f"{clean_port}/{protocol}"
|
||||||
|
if port_key in seen_ports:
|
||||||
|
conflicts.append((clean_port, protocol, "Duplicate port in submission"))
|
||||||
|
continue
|
||||||
|
seen_ports.add(port_key)
|
||||||
|
|
||||||
# Server-side validation
|
# Check if the port is in use by another application
|
||||||
from app.utils.app_utils import save_app
|
in_use, conflicting_app_name = is_port_in_use(
|
||||||
|
clean_port, protocol, server_id
|
||||||
|
)
|
||||||
|
|
||||||
|
if in_use:
|
||||||
|
conflicts.append((clean_port, protocol, f"Port {clean_port}/{protocol} is already in use by application '{conflicting_app_name}'"))
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
continue
|
||||||
|
|
||||||
success, app, error = save_app(name, server_id, documentation, port_data, url=url)
|
if conflicts:
|
||||||
|
for conflict in conflicts:
|
||||||
|
flash(f"Conflict: {conflict[0]}/{conflict[1]} - {conflict[2]}", "danger")
|
||||||
|
return render_template(
|
||||||
|
"dashboard/app_form.html",
|
||||||
|
edit_mode=False,
|
||||||
|
servers=servers,
|
||||||
|
selected_server_id=server_id
|
||||||
|
)
|
||||||
|
|
||||||
if success:
|
# Create the application
|
||||||
flash(f"Application '{name}' created successfully", "success")
|
try:
|
||||||
return redirect(url_for("dashboard.app_view", app_id=app.id))
|
new_app = App(
|
||||||
else:
|
name=name,
|
||||||
flash(error, "danger")
|
server_id=server_id,
|
||||||
|
documentation=documentation,
|
||||||
|
url=url
|
||||||
|
)
|
||||||
|
db.session.add(new_app)
|
||||||
|
db.session.flush() # Get the app ID without committing
|
||||||
|
|
||||||
# Check if it's a port conflict and provide direct link
|
# Add ports
|
||||||
if "already in use by application" in error:
|
for port_number, protocol, description in port_data:
|
||||||
try:
|
new_port = Port(
|
||||||
app_name = error.split("'")[1] # Extract app name from error
|
app_id=new_app.id,
|
||||||
conflict_app = App.query.filter_by(name=app_name, server_id=server_id).first()
|
port_number=int(port_number),
|
||||||
if conflict_app:
|
protocol=protocol,
|
||||||
edit_url = url_for('dashboard.app_edit', app_id=conflict_app.id)
|
description=description
|
||||||
flash(f'<a href="{edit_url}" class="alert-link">Edit conflicting application</a>', "info")
|
)
|
||||||
except:
|
db.session.add(new_port)
|
||||||
pass
|
|
||||||
|
db.session.commit()
|
||||||
|
flash(f"Application '{name}' created successfully", "success")
|
||||||
|
return redirect(url_for("dashboard.app_view", app_id=new_app.id))
|
||||||
|
except Exception as e:
|
||||||
|
db.session.rollback()
|
||||||
|
flash(f"Error creating application: {str(e)}", "danger")
|
||||||
|
|
||||||
# GET request or validation failed - render the form
|
# GET request or validation failed - render the form
|
||||||
return render_template(
|
return render_template(
|
||||||
"dashboard/app_form.html",
|
"dashboard/app_form.html",
|
||||||
title="New Application",
|
|
||||||
edit_mode=False,
|
edit_mode=False,
|
||||||
servers=servers,
|
servers=servers,
|
||||||
selected_server_id=server_id,
|
selected_server_id=server_id
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@ -308,6 +368,32 @@ def app_edit(app_id):
|
||||||
documentation = request.form.get("documentation", "")
|
documentation = request.form.get("documentation", "")
|
||||||
url = request.form.get("url", "") # Get the URL
|
url = request.form.get("url", "") # Get the URL
|
||||||
|
|
||||||
|
# Validate application name
|
||||||
|
if not name:
|
||||||
|
flash("Application name is required", "danger")
|
||||||
|
return render_template(
|
||||||
|
"dashboard/app_form.html",
|
||||||
|
edit_mode=True,
|
||||||
|
app=app,
|
||||||
|
servers=servers
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check for duplicate application names on the same server (excluding this app)
|
||||||
|
existing_app = App.query.filter(
|
||||||
|
App.name == name,
|
||||||
|
App.server_id == server_id,
|
||||||
|
App.id != app_id
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if existing_app:
|
||||||
|
flash(f"An application with the name '{name}' already exists on this server", "danger")
|
||||||
|
return render_template(
|
||||||
|
"dashboard/app_form.html",
|
||||||
|
edit_mode=True,
|
||||||
|
app=app,
|
||||||
|
servers=servers
|
||||||
|
)
|
||||||
|
|
||||||
# Process port data from form
|
# Process port data from form
|
||||||
port_data = []
|
port_data = []
|
||||||
port_numbers = request.form.getlist("port_numbers[]")
|
port_numbers = request.form.getlist("port_numbers[]")
|
||||||
|
@ -347,7 +433,12 @@ def app_edit(app_id):
|
||||||
if conflicts:
|
if conflicts:
|
||||||
for conflict in conflicts:
|
for conflict in conflicts:
|
||||||
flash(f"Conflict: {conflict[0]}/{conflict[1]} - {conflict[2]}", "danger")
|
flash(f"Conflict: {conflict[0]}/{conflict[1]} - {conflict[2]}", "danger")
|
||||||
return render_template("dashboard/app_edit.html", app=app, servers=servers)
|
return render_template(
|
||||||
|
"dashboard/app_form.html",
|
||||||
|
edit_mode=True,
|
||||||
|
app=app,
|
||||||
|
servers=servers
|
||||||
|
)
|
||||||
|
|
||||||
# Update application details
|
# Update application details
|
||||||
app.name = name
|
app.name = name
|
||||||
|
@ -372,7 +463,12 @@ def app_edit(app_id):
|
||||||
flash("Application updated successfully", "success")
|
flash("Application updated successfully", "success")
|
||||||
return redirect(url_for("dashboard.app_view", app_id=app_id))
|
return redirect(url_for("dashboard.app_view", app_id=app_id))
|
||||||
|
|
||||||
return render_template("dashboard/app_edit.html", app=app, servers=servers)
|
return render_template(
|
||||||
|
"dashboard/app_form.html",
|
||||||
|
edit_mode=True,
|
||||||
|
app=app,
|
||||||
|
servers=servers
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/app/<int:app_id>/delete", methods=["POST"])
|
@bp.route("/app/<int:app_id>/delete", methods=["POST"])
|
||||||
|
|
|
@ -6,25 +6,8 @@
|
||||||
<div class="row align-items-center">
|
<div class="row align-items-center">
|
||||||
<div class="col">
|
<div class="col">
|
||||||
<h2 class="page-title">
|
<h2 class="page-title">
|
||||||
{{ title }}
|
{% if edit_mode %}Edit Application: {{ app.name }}{% else %}New Application{% endif %}
|
||||||
</h2>
|
</h2>
|
||||||
<div class="text-muted mt-1">
|
|
||||||
{% if edit_mode %}Edit{% else %}Create{% endif %} application details and configure ports
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="col-auto ms-auto">
|
|
||||||
<div class="btn-list">
|
|
||||||
<a href="{{ dashboard_link }}" class="btn btn-outline-primary">
|
|
||||||
<span class="ti ti-dashboard"></span>
|
|
||||||
Dashboard
|
|
||||||
</a>
|
|
||||||
{% if edit_mode %}
|
|
||||||
<a href="{{ url_for('dashboard.app_view', app_id=app.id) }}" class="btn btn-outline-secondary">
|
|
||||||
<span class="ti ti-eye"></span>
|
|
||||||
View Application
|
|
||||||
</a>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -35,7 +18,7 @@
|
||||||
{% if messages %}
|
{% if messages %}
|
||||||
{% for category, message in messages %}
|
{% for category, message in messages %}
|
||||||
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
|
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
|
||||||
{{ message }}
|
{{ message|safe }}
|
||||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
||||||
</div>
|
</div>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
@ -43,77 +26,55 @@
|
||||||
{% endwith %}
|
{% endwith %}
|
||||||
|
|
||||||
<form method="POST"
|
<form method="POST"
|
||||||
action="{% if edit_mode %}{{ url_for('dashboard.app_edit', app_id=app.id) }}{% else %}{{ url_for('dashboard.app_new') }}{% endif %}">
|
action="{{ url_for('dashboard.app_edit', app_id=app.id) if edit_mode else url_for('dashboard.app_new', server_id=selected_server_id) }}">
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
{% if app %}
|
|
||||||
<input type="hidden" id="app-id" name="app_id" value="{{ app.id }}">
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="app-name" class="form-label required">Application Name</label>
|
<label class="form-label required">Application Name</label>
|
||||||
<input type="text" class="form-control" id="app-name" name="name" required
|
<input type="text" class="form-control" name="name" value="{{ app.name if edit_mode else '' }}" required>
|
||||||
value="{% if app %}{{ app.name }}{% endif %}">
|
|
||||||
<div id="name-feedback"></div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label class="form-label">Application URL (Optional)</label>
|
<label class="form-label">URL</label>
|
||||||
<div class="input-group">
|
<input type="url" class="form-control" name="url" value="{{ app.url if edit_mode else '' }}"
|
||||||
<span class="input-group-text">
|
placeholder="https://example.com">
|
||||||
<span class="ti ti-link"></span>
|
<small class="form-hint">Optional URL for accessing the application</small>
|
||||||
</span>
|
|
||||||
<input type="url" class="form-control" name="url" id="url" value="{{ app.url if app else '' }}"
|
|
||||||
placeholder="https://example.com">
|
|
||||||
</div>
|
|
||||||
<small class="form-hint">
|
|
||||||
If provided, the application name will be clickable and link to this URL.
|
|
||||||
</small>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="server-id" class="form-label required">Server</label>
|
<label class="form-label required">Server</label>
|
||||||
<select class="form-select" id="server-id" name="server_id" required>
|
<select class="form-select" name="server_id" required id="server-select">
|
||||||
<option value="">Select Server</option>
|
<option value="">Select a server</option>
|
||||||
{% for server in servers %}
|
{% for server in servers %}
|
||||||
<option value="{{ server.id }}" {% if (app and app.server_id==server.id) or (selected_server_id and
|
<option value="{{ server.id }}" {% if (edit_mode and server.id==app.server_id) or (not edit_mode and
|
||||||
selected_server_id|int==server.id|int) %}selected{% endif %}>
|
server.id==selected_server_id) %}selected{% endif %}>
|
||||||
{{ server.hostname }} ({{ server.ip_address }})
|
{{ server.hostname }} ({{ server.ip_address }})
|
||||||
</option>
|
</option>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">Documentation</label>
|
||||||
|
<textarea class="form-control" name="documentation" rows="5"
|
||||||
|
placeholder="Add documentation about this application">{{ app.documentation if edit_mode else '' }}</textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<div class="d-flex justify-content-between align-items-center mb-2">
|
<label class="form-label">Ports</label>
|
||||||
<label class="form-label mb-0">Application Ports</label>
|
|
||||||
<div class="btn-group">
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-primary" id="add-port-btn">
|
|
||||||
<span class="ti ti-plus"></span> Add Port
|
|
||||||
</button>
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-secondary" id="random-port-btn"
|
|
||||||
title="Generate random available port">
|
|
||||||
<span class="ti ti-dice"></span> Random Port
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="table-responsive">
|
<div class="table-responsive">
|
||||||
<table class="table table-vcenter card-table" id="ports-table">
|
<table class="table table-vcenter card-table" id="ports-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Port</th>
|
<th>Port Number</th>
|
||||||
<th>Protocol</th>
|
<th>Protocol</th>
|
||||||
<th>Description</th>
|
<th>Description</th>
|
||||||
<th width="40"></th>
|
<th width="50"></th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% if app and app.ports %}
|
{% if edit_mode and app.ports %}
|
||||||
{% for port in app.ports %}
|
{% for port in app.ports %}
|
||||||
<tr>
|
<tr>
|
||||||
<td>
|
<td>
|
||||||
<input type="number" name="port_numbers[]" class="form-control" min="1" max="65535"
|
<input type="number" name="port_numbers[]" class="form-control" min="1" max="65535"
|
||||||
value="{{ port.port_number }}" required>
|
value="{{ port.port_number }}">
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<select name="protocols[]" class="form-select">
|
<select name="protocols[]" class="form-select">
|
||||||
|
@ -133,14 +94,14 @@
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% else %}
|
{% else %}
|
||||||
<!-- Always show at least one empty port row if no ports exist -->
|
|
||||||
<tr>
|
<tr>
|
||||||
<td>
|
<td>
|
||||||
<input type="number" name="port_numbers[]" class="form-control" min="1" max="65535" required>
|
<input type="number" name="port_numbers[]" class="form-control" min="1" max="65535"
|
||||||
|
placeholder="Port number">
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<select name="protocols[]" class="form-select">
|
<select name="protocols[]" class="form-select">
|
||||||
<option value="TCP" selected>TCP</option>
|
<option value="TCP">TCP</option>
|
||||||
<option value="UDP">UDP</option>
|
<option value="UDP">UDP</option>
|
||||||
</select>
|
</select>
|
||||||
</td>
|
</td>
|
||||||
|
@ -157,94 +118,26 @@
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<small class="form-hint">Configure the network ports used by this application</small>
|
<div class="mt-3">
|
||||||
</div>
|
<button type="button" class="btn btn-sm btn-outline-primary" onclick="addPortRow()">
|
||||||
|
<span class="ti ti-plus me-1"></span> Add Port
|
||||||
<div class="mb-3">
|
</button>
|
||||||
<label class="form-label">Documentation</label>
|
|
||||||
<textarea class="form-control" name="documentation" id="documentation" rows="10"
|
|
||||||
placeholder="Enter documentation in Markdown format">{{ app.documentation if app else '' }}</textarea>
|
|
||||||
<small class="form-hint">
|
|
||||||
Use <a href="https://www.markdownguide.org/basic-syntax/" target="_blank">Markdown syntax</a>
|
|
||||||
to format your documentation. You can use GitHub-style alerts:
|
|
||||||
</small>
|
|
||||||
<div class="mt-2 d-flex gap-2 flex-wrap">
|
|
||||||
<code>> [!NOTE] This is a note</code>
|
|
||||||
<code>> [!TIP] This is a tip</code>
|
|
||||||
<code>> [!IMPORTANT] Important info</code>
|
|
||||||
<code>> [!WARNING] Warning message</code>
|
|
||||||
<code>> [!CAUTION] Critical caution</code>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="form-footer">
|
<div class="form-footer">
|
||||||
<button type="submit" class="btn btn-primary">Save Application</button>
|
<div class="d-flex">
|
||||||
{% if edit_mode %}
|
<a href="{{ url_for('dashboard.app_view', app_id=app.id) if edit_mode else url_for('dashboard.app_new') }}"
|
||||||
<a href="{{ url_for('dashboard.app_view', app_id=app.id) }}" class="btn btn-outline-secondary ms-2">Cancel</a>
|
class="btn btn-link">Cancel</a>
|
||||||
{% else %}
|
<button type="submit" class="btn btn-primary ms-auto">
|
||||||
<a href="{{ dashboard_link }}" class="btn btn-outline-secondary ms-2">Cancel</a>
|
{% if edit_mode %}Save Changes{% else %}Create Application{% endif %}
|
||||||
{% endif %}
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block extra_js %}
|
|
||||||
<script>
|
|
||||||
{% if app and app.id %}
|
|
||||||
const appId = {{ app.id | tojson }};
|
|
||||||
{% else %}
|
|
||||||
const appId = null;
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
// Initialize everything once the DOM is loaded
|
|
||||||
document.addEventListener('DOMContentLoaded', function () {
|
|
||||||
// Connect port management buttons
|
|
||||||
const addPortBtn = document.getElementById('add-port-btn');
|
|
||||||
const randomPortBtn = document.getElementById('random-port-btn');
|
|
||||||
|
|
||||||
if (addPortBtn) {
|
|
||||||
addPortBtn.addEventListener('click', function () {
|
|
||||||
addPortRow();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (randomPortBtn) {
|
|
||||||
randomPortBtn.addEventListener('click', function () {
|
|
||||||
generateRandomPort();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Show notifications
|
|
||||||
function showNotification(message, type = 'info') {
|
|
||||||
const alertDiv = document.createElement('div');
|
|
||||||
alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
|
|
||||||
alertDiv.innerHTML = `
|
|
||||||
${message}
|
|
||||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
|
||||||
`;
|
|
||||||
|
|
||||||
const container = document.querySelector('.card-body');
|
|
||||||
if (container) {
|
|
||||||
container.insertBefore(alertDiv, container.firstChild);
|
|
||||||
|
|
||||||
// Auto-dismiss after 5 seconds
|
|
||||||
setTimeout(() => {
|
|
||||||
alertDiv.classList.remove('show');
|
|
||||||
setTimeout(() => alertDiv.remove(), 150);
|
|
||||||
}, 5000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
document.body.addEventListener('htmx:configRequest', (event) => {
|
|
||||||
event.detail.headers['X-CSRFToken'] = "{{ csrf_token() }}";
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
// Make sure removePortRow is in the global scope
|
// Make sure removePortRow is in the global scope
|
||||||
|
@ -270,16 +163,12 @@
|
||||||
|
|
||||||
// Add a visual indicator that this row is empty
|
// Add a visual indicator that this row is empty
|
||||||
row.classList.add('table-secondary', 'opacity-50');
|
row.classList.add('table-secondary', 'opacity-50');
|
||||||
|
|
||||||
// Show a helping message
|
|
||||||
showNotification('Application saved with no ports. Use "Add Port" to add ports.', 'info');
|
|
||||||
} else {
|
} else {
|
||||||
// Remove the row if there are other rows
|
// Remove the row if there are other rows
|
||||||
row.remove();
|
row.remove();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Port management functions
|
|
||||||
function addPortRow(portNumber = '', protocol = 'TCP', description = '') {
|
function addPortRow(portNumber = '', protocol = 'TCP', description = '') {
|
||||||
const tbody = document.querySelector('#ports-table tbody');
|
const tbody = document.querySelector('#ports-table tbody');
|
||||||
|
|
||||||
|
@ -293,7 +182,7 @@
|
||||||
newRow.innerHTML = `
|
newRow.innerHTML = `
|
||||||
<td class="position-relative">
|
<td class="position-relative">
|
||||||
<input type="number" name="port_numbers[]" class="form-control"
|
<input type="number" name="port_numbers[]" class="form-control"
|
||||||
min="1" max="65535" value="${portNumber}" required>
|
min="1" max="65535" value="${portNumber}" placeholder="Port number">
|
||||||
<div class="feedback"></div>
|
<div class="feedback"></div>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
|
@ -313,36 +202,240 @@
|
||||||
</td>
|
</td>
|
||||||
`;
|
`;
|
||||||
tbody.appendChild(newRow);
|
tbody.appendChild(newRow);
|
||||||
|
|
||||||
// Set up validation for the new row
|
|
||||||
setTimeout(setupPortValidation, 50);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function generateRandomPort() {
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
try {
|
// Get form elements
|
||||||
const serverId = document.querySelector('select[name="server_id"]').value;
|
const nameField = document.querySelector('input[name="name"]');
|
||||||
if (!serverId) {
|
const serverSelect = document.getElementById('server-select');
|
||||||
showNotification('Please select a server first', 'warning');
|
const submitButton = document.querySelector('button[type="submit"]');
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch(`/api/server/${serverId}/free-port`);
|
// Set up name validation
|
||||||
const data = await response.json();
|
if (nameField && serverSelect) {
|
||||||
|
// Validate on typing (with debounce)
|
||||||
|
nameField.addEventListener('input', function () {
|
||||||
|
validateAppName(nameField, serverSelect, 300);
|
||||||
|
});
|
||||||
|
|
||||||
if (data.success && data.port) {
|
// Also validate on blur for completeness
|
||||||
addPortRow(data.port);
|
nameField.addEventListener('blur', function () {
|
||||||
} else {
|
validateAppName(nameField, serverSelect, 0);
|
||||||
showNotification(data.error || 'No available ports found', 'warning');
|
});
|
||||||
}
|
|
||||||
} catch (error) {
|
serverSelect.addEventListener('change', function () {
|
||||||
console.error('Error generating random port:', error);
|
if (nameField.value.trim()) {
|
||||||
showNotification('Failed to generate random port', 'danger');
|
validateAppName(nameField, serverSelect, 0);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Set up port validation for all port inputs
|
||||||
|
function setupPortValidation() {
|
||||||
|
const portInputs = document.querySelectorAll('input[name="port_numbers[]"]');
|
||||||
|
const protocolSelects = document.querySelectorAll('select[name="protocols[]"]');
|
||||||
|
|
||||||
|
portInputs.forEach((input, index) => {
|
||||||
|
const protocolSelect = protocolSelects[index];
|
||||||
|
|
||||||
|
// Validate on typing (with debounce)
|
||||||
|
input.addEventListener('input', function () {
|
||||||
|
validatePort(input, protocolSelect, 300);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Also validate on blur for completeness
|
||||||
|
input.addEventListener('blur', function () {
|
||||||
|
validatePort(input, protocolSelect, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (protocolSelect) {
|
||||||
|
protocolSelect.addEventListener('change', function () {
|
||||||
|
if (input.value.trim()) {
|
||||||
|
validatePort(input, protocolSelect, 0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initial setup
|
||||||
|
setupPortValidation();
|
||||||
|
|
||||||
|
// Re-setup validation after adding a new port row
|
||||||
|
const originalAddPortRow = window.addPortRow;
|
||||||
|
window.addPortRow = function (portNumber = '', protocol = 'TCP', description = '') {
|
||||||
|
originalAddPortRow(portNumber, protocol, description);
|
||||||
|
setupPortValidation();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Validate application name
|
||||||
|
function validateAppName(nameField, serverSelect, debounceTime = 300) {
|
||||||
|
// Create feedback element if it doesn't exist
|
||||||
|
if (!nameField.nextElementSibling || !nameField.nextElementSibling.classList.contains('feedback')) {
|
||||||
|
const feedback = document.createElement('div');
|
||||||
|
feedback.className = 'feedback';
|
||||||
|
nameField.parentNode.insertBefore(feedback, nameField.nextSibling);
|
||||||
|
}
|
||||||
|
|
||||||
|
const feedbackElement = nameField.nextElementSibling;
|
||||||
|
|
||||||
|
const name = nameField.value.trim();
|
||||||
|
const serverId = serverSelect.value;
|
||||||
|
const appId = {% if edit_mode %} { { app.id } } {% else %} null{% endif %};
|
||||||
|
|
||||||
|
if (!name || !serverId) {
|
||||||
|
clearFeedback(feedbackElement);
|
||||||
|
nameField.classList.remove('is-invalid');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show loading indicator for better UX
|
||||||
|
if (debounceTime > 0) {
|
||||||
|
showLoading(feedbackElement, 'Checking...');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debounce to avoid too many requests
|
||||||
|
clearTimeout(nameField.timer);
|
||||||
|
nameField.timer = setTimeout(() => {
|
||||||
|
fetch(`/api/validate/app-name?name=${encodeURIComponent(name)}&server_id=${serverId}${appId ? '&app_id=' + appId : ''}`)
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
clearFeedback(feedbackElement);
|
||||||
|
if (!data.valid) {
|
||||||
|
nameField.classList.add('is-invalid');
|
||||||
|
showError(feedbackElement, data.message);
|
||||||
|
if (data.edit_url) {
|
||||||
|
feedbackElement.innerHTML += ` <a href="${data.edit_url}" class="alert-link">View existing app</a>`;
|
||||||
|
}
|
||||||
|
} else if (data.warning) {
|
||||||
|
nameField.classList.remove('is-invalid');
|
||||||
|
nameField.classList.add('is-warning');
|
||||||
|
showWarning(feedbackElement, data.warning);
|
||||||
|
|
||||||
|
if (data.similar_apps && data.similar_apps.length > 0) {
|
||||||
|
const similarList = document.createElement('ul');
|
||||||
|
similarList.className = 'mt-1';
|
||||||
|
|
||||||
|
data.similar_apps.forEach(app => {
|
||||||
|
const li = document.createElement('li');
|
||||||
|
li.innerHTML = `<a href="/dashboard/app/${app.id}" class="alert-link">${app.name}</a>`;
|
||||||
|
similarList.appendChild(li);
|
||||||
|
});
|
||||||
|
|
||||||
|
feedbackElement.appendChild(similarList);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
nameField.classList.remove('is-invalid');
|
||||||
|
nameField.classList.add('is-valid');
|
||||||
|
showSuccess(feedbackElement, 'Application name available');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Validation error:', error);
|
||||||
|
clearFeedback(feedbackElement);
|
||||||
|
nameField.classList.remove('is-invalid');
|
||||||
|
nameField.classList.remove('is-valid');
|
||||||
|
});
|
||||||
|
}, debounceTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate port
|
||||||
|
function validatePort(portField, protocolField, debounceTime = 300) {
|
||||||
|
// Create feedback element if it doesn't exist
|
||||||
|
if (!portField.nextElementSibling || !portField.nextElementSibling.classList.contains('feedback')) {
|
||||||
|
const feedback = document.createElement('div');
|
||||||
|
feedback.className = 'feedback';
|
||||||
|
portField.parentNode.insertBefore(feedback, portField.nextSibling);
|
||||||
|
}
|
||||||
|
|
||||||
|
const feedbackElement = portField.nextElementSibling;
|
||||||
|
|
||||||
|
const port = portField.value.trim();
|
||||||
|
const protocol = protocolField.value;
|
||||||
|
const serverId = serverSelect.value;
|
||||||
|
const appId = {% if edit_mode %}{{ app.id }}{% else %}null{% endif %};
|
||||||
|
|
||||||
|
if (!port || !serverId) {
|
||||||
|
clearFeedback(feedbackElement);
|
||||||
|
portField.classList.remove('is-invalid');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for duplicate ports within the form first
|
||||||
|
const allPortFields = document.querySelectorAll('input[name="port_numbers[]"]');
|
||||||
|
const allProtocolFields = document.querySelectorAll('select[name="protocols[]"]');
|
||||||
|
let duplicateFound = false;
|
||||||
|
|
||||||
|
allPortFields.forEach((field, index) => {
|
||||||
|
if (field !== portField && field.value === port && allProtocolFields[index].value === protocol) {
|
||||||
|
duplicateFound = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (duplicateFound) {
|
||||||
|
portField.classList.add('is-invalid');
|
||||||
|
clearFeedback(feedbackElement);
|
||||||
|
showError(feedbackElement, `Duplicate port ${port}/${protocol} in your form`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show loading indicator for better UX
|
||||||
|
if (debounceTime > 0) {
|
||||||
|
showLoading(feedbackElement, 'Checking...');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debounce to avoid too many requests
|
||||||
|
clearTimeout(portField.timer);
|
||||||
|
portField.timer = setTimeout(() => {
|
||||||
|
fetch(`/api/validate/app-port?port_number=${encodeURIComponent(port)}&protocol=${protocol}&server_id=${serverId}${appId ? '&app_id=' + appId : ''}`)
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
clearFeedback(feedbackElement);
|
||||||
|
if (!data.valid) {
|
||||||
|
portField.classList.add('is-invalid');
|
||||||
|
showError(feedbackElement, data.message);
|
||||||
|
if (data.edit_url) {
|
||||||
|
feedbackElement.innerHTML += ` <a href="${data.edit_url}" class="alert-link">Edit conflicting app</a>`;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
portField.classList.remove('is-invalid');
|
||||||
|
portField.classList.add('is-valid');
|
||||||
|
showSuccess(feedbackElement, 'Port available');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Validation error:', error);
|
||||||
|
clearFeedback(feedbackElement);
|
||||||
|
portField.classList.remove('is-invalid');
|
||||||
|
portField.classList.remove('is-valid');
|
||||||
|
});
|
||||||
|
}, debounceTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper functions for feedback
|
||||||
|
function clearFeedback(element) {
|
||||||
|
element.innerHTML = '';
|
||||||
|
element.className = 'feedback';
|
||||||
|
}
|
||||||
|
|
||||||
|
function showError(element, message) {
|
||||||
|
element.innerHTML = message;
|
||||||
|
element.className = 'feedback invalid-feedback d-block';
|
||||||
|
}
|
||||||
|
|
||||||
|
function showWarning(element, message) {
|
||||||
|
element.innerHTML = message;
|
||||||
|
element.className = 'feedback text-warning d-block';
|
||||||
|
}
|
||||||
|
|
||||||
|
function showSuccess(element, message) {
|
||||||
|
element.innerHTML = message;
|
||||||
|
element.className = 'feedback valid-feedback d-block';
|
||||||
|
}
|
||||||
|
|
||||||
|
function showLoading(element, message) {
|
||||||
|
element.innerHTML = `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> ${message}`;
|
||||||
|
element.className = 'feedback text-muted d-block';
|
||||||
|
}
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}
|
|
||||||
{{ super() }}
|
|
||||||
<script src="{{ url_for('static', filename='js/validation.js') }}"></script>
|
|
||||||
{% endblock %}
|
|
Loading…
Add table
Add a link
Reference in a new issue