88 lines
2.9 KiB
Python
88 lines
2.9 KiB
Python
"""
|
|
Database models and initialization.
|
|
"""
|
|
from flask_sqlalchemy import SQLAlchemy
|
|
from werkzeug.security import generate_password_hash, check_password_hash
|
|
|
|
db = SQLAlchemy()
|
|
|
|
|
|
class User(db.Model):
|
|
"""User model for authentication."""
|
|
__tablename__ = 'users'
|
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
username = db.Column(db.String(80), unique=True, nullable=False)
|
|
password_hash = db.Column(db.String(256), nullable=False)
|
|
created_at = db.Column(db.DateTime, nullable=True)
|
|
|
|
def __init__(self, username, password=None):
|
|
self.username = username
|
|
if password:
|
|
self.password_hash = generate_password_hash(password)
|
|
self.created_at = db.func.datetime('now')
|
|
|
|
def check_password(self, password):
|
|
"""Verify password against stored hash."""
|
|
return check_password_hash(self.password_hash, password)
|
|
|
|
def __repr__(self):
|
|
return f'<User {self.username}>'
|
|
|
|
|
|
class Service(db.Model):
|
|
"""Service model for navigation entries."""
|
|
__tablename__ = 'services'
|
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
name = db.Column(db.String(120), nullable=False)
|
|
description = db.Column(db.Text, nullable=True)
|
|
port = db.Column(db.Integer, nullable=False)
|
|
protocol = db.Column(db.String(10), nullable=False, default='http')
|
|
enabled = db.Column(db.Boolean, nullable=False, default=True)
|
|
icon = db.Column(db.String(100), nullable=True) # 支持 emoji 或图片文件名
|
|
path = db.Column(db.String(255), nullable=True) # 服务路径
|
|
|
|
def get_icon_html(self):
|
|
"""返回图标的 HTML,支持 emoji 和图片"""
|
|
if not self.icon:
|
|
return '<div class="service-icon">🚀</div>'
|
|
# 如果是图片文件(有扩展名)
|
|
if '.' in self.icon:
|
|
from flask import url_for
|
|
return '<img src="{}" class="service-icon-img">'.format(url_for('serve_icon', filename=self.icon))
|
|
# 否则是 emoji
|
|
return '<div class="service-icon">{}</div>'.format(self.icon)
|
|
|
|
def __init__(self, name, description=None, port=None, protocol='http',
|
|
enabled=True, icon=None, path=None):
|
|
self.name = name
|
|
self.description = description
|
|
self.port = port
|
|
self.protocol = protocol
|
|
self.enabled = enabled
|
|
self.icon = icon
|
|
self.path = path
|
|
|
|
def get_url(self):
|
|
"""Generate the full URL for this service."""
|
|
from app import get_host_from_request
|
|
host = get_host_from_request()
|
|
url = f"{self.protocol}://{host}:{self.port}"
|
|
if self.path:
|
|
# 确保path以/开头
|
|
if not self.path.startswith('/'):
|
|
url += '/' + self.path
|
|
else:
|
|
url += self.path
|
|
return url
|
|
|
|
def __repr__(self):
|
|
return f'<Service {self.name}>'
|
|
|
|
|
|
def init_app(app):
|
|
"""Flask application factory pattern for database initialization."""
|
|
db.init_app(app)
|
|
return db
|