1053 lines
49 KiB
Python
1053 lines
49 KiB
Python
|
|
import hashlib
|
|||
|
|
import calendar
|
|||
|
|
import secrets
|
|||
|
|
import uuid
|
|||
|
|
from datetime import timedelta
|
|||
|
|
from decimal import Decimal
|
|||
|
|
|
|||
|
|
from django.conf import settings
|
|||
|
|
from django.contrib.auth import get_user_model
|
|||
|
|
from django.core import signing
|
|||
|
|
from django.core.exceptions import ValidationError
|
|||
|
|
from django.db import models, transaction
|
|||
|
|
from django.utils import timezone
|
|||
|
|
|
|||
|
|
|
|||
|
|
class PlanCatalogDraft(models.Model):
|
|||
|
|
"""Commercial proposals only. Never used for applications or provisioning.
|
|||
|
|
|
|||
|
|
In particular, a team proposal must not become a per-user subscription
|
|||
|
|
with a misleading shared-quota name. Prices may remain genuinely unknown.
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
class Scope(models.TextChoices):
|
|||
|
|
PERSONAL = "personal", "个人"
|
|||
|
|
TEAM = "team", "团队共享(待接入)"
|
|||
|
|
|
|||
|
|
name = models.CharField("套餐名称", max_length=100)
|
|||
|
|
slug = models.SlugField("草稿标识", max_length=80, unique=True)
|
|||
|
|
scope = models.CharField("套餐类型", max_length=20, choices=Scope.choices)
|
|||
|
|
traffic_limit_gb = models.PositiveIntegerField("月代理流量(GB)", help_text="0 表示不限代理流量,不代表无限带宽、人数或设备。")
|
|||
|
|
price_cny = models.DecimalField("拟定月价(元)", max_digits=10, decimal_places=2, null=True, blank=True,
|
|||
|
|
help_text="留空表示待定价,不是0元免费;填写也不会自动上架。")
|
|||
|
|
member_limit = models.PositiveIntegerField("成员上限", null=True, blank=True, help_text="个人为1;团队留空表示待确认。")
|
|||
|
|
device_limit = models.PositiveIntegerField("总设备上限", null=True, blank=True, help_text="团队为全部成员总数;留空表示待确认,不是无限。")
|
|||
|
|
concurrent_limit = models.PositiveIntegerField("同时在线上限", null=True, blank=True, help_text="留空表示待确认,不是无限。")
|
|||
|
|
description = models.TextField("草案说明", blank=True)
|
|||
|
|
sort_order = models.PositiveSmallIntegerField("排序", default=10)
|
|||
|
|
created_at = models.DateTimeField("创建时间", auto_now_add=True)
|
|||
|
|
updated_at = models.DateTimeField("更新时间", auto_now=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "套餐草稿(未上架)"
|
|||
|
|
verbose_name_plural = "套餐草稿(未上架)"
|
|||
|
|
ordering = ["sort_order", "pk"]
|
|||
|
|
constraints = [
|
|||
|
|
models.CheckConstraint(condition=models.Q(price_cny__isnull=True) | models.Q(price_cny__gte=0), name="catalog_draft_price_nonnegative"),
|
|||
|
|
models.CheckConstraint(condition=models.Q(member_limit__isnull=True) | models.Q(member_limit__gt=0), name="catalog_draft_members_positive"),
|
|||
|
|
models.CheckConstraint(condition=models.Q(device_limit__isnull=True) | models.Q(device_limit__gt=0), name="catalog_draft_devices_positive"),
|
|||
|
|
models.CheckConstraint(condition=models.Q(concurrent_limit__isnull=True) | models.Q(concurrent_limit__gt=0), name="catalog_draft_concurrent_positive"),
|
|||
|
|
]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return self.name
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def quota_label(self):
|
|||
|
|
if self.traffic_limit_gb == 0:
|
|||
|
|
return "无限代理流量"
|
|||
|
|
if self.traffic_limit_gb % 1024 == 0:
|
|||
|
|
return f"{self.traffic_limit_gb // 1024} TB/月"
|
|||
|
|
return f"{self.traffic_limit_gb} GB/月"
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def price_label(self):
|
|||
|
|
return "待定价" if self.price_cny is None else f"{self.price_cny:.2f} 元/月(草稿)"
|
|||
|
|
|
|||
|
|
def clean(self):
|
|||
|
|
errors = {}
|
|||
|
|
if self.price_cny is not None and self.price_cny < 0:
|
|||
|
|
errors["price_cny"] = "月价不能为负数;未定价请留空。"
|
|||
|
|
for field in ("member_limit", "device_limit", "concurrent_limit"):
|
|||
|
|
value = getattr(self, field)
|
|||
|
|
if value is not None and value < 1:
|
|||
|
|
errors[field] = "必须大于0;待确认请留空。"
|
|||
|
|
if self.scope == self.Scope.PERSONAL and self.member_limit != 1:
|
|||
|
|
errors["member_limit"] = "个人套餐固定为1名使用者。"
|
|||
|
|
if self.concurrent_limit and self.device_limit and self.concurrent_limit > self.device_limit:
|
|||
|
|
errors["concurrent_limit"] = "同时在线上限不能超过总设备上限。"
|
|||
|
|
if errors:
|
|||
|
|
raise ValidationError(errors)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class Plan(models.Model):
|
|||
|
|
class Audience(models.TextChoices):
|
|||
|
|
EMPLOYEE = "employee", "内部员工"
|
|||
|
|
EXTERNAL = "external", "外部联系人"
|
|||
|
|
ALL = "all", "全部用户"
|
|||
|
|
|
|||
|
|
name = models.CharField("套餐名称", max_length=100)
|
|||
|
|
slug = models.SlugField("标识", max_length=80, unique=True)
|
|||
|
|
audience = models.CharField("适用人群", max_length=20, choices=Audience.choices, default=Audience.ALL)
|
|||
|
|
employee_benefit = models.BooleanField("员工福利", default=False)
|
|||
|
|
price_cny = models.DecimalField("价格(元)", max_digits=10, decimal_places=2, default=Decimal("0.00"))
|
|||
|
|
traffic_limit_gb = models.PositiveIntegerField("流量额度(GB)", default=0, help_text="0 表示不限流量")
|
|||
|
|
duration_days = models.PositiveIntegerField("有效天数", default=30, help_text="0 表示不自动到期")
|
|||
|
|
billing_months = models.PositiveSmallIntegerField("按月周期", default=0, help_text="大于0时从开通日起按自然月计算,覆盖有效天数;到期不自动扣款。")
|
|||
|
|
online_payment_required = models.BooleanField("要求在线收款", default=False, help_text="可展示并接受申请;收款接入验收前不接受付款、不开放付费权限,不得人工改付款状态绕过。内部员工仍免费。")
|
|||
|
|
device_limit = models.PositiveSmallIntegerField("设备数", default=3)
|
|||
|
|
active = models.BooleanField("启用", default=True)
|
|||
|
|
description = models.TextField("说明", blank=True)
|
|||
|
|
sort_order = models.PositiveSmallIntegerField("排序", default=10)
|
|||
|
|
created_at = models.DateTimeField("创建时间", auto_now_add=True)
|
|||
|
|
updated_at = models.DateTimeField("更新时间", auto_now=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "套餐"
|
|||
|
|
verbose_name_plural = "套餐"
|
|||
|
|
ordering = ["sort_order", "price_cny", "name"]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return self.name
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def traffic_limit_bytes(self):
|
|||
|
|
return self.traffic_limit_gb * 1024 * 1024 * 1024
|
|||
|
|
|
|||
|
|
def price_for_user(self, user):
|
|||
|
|
# The identity field is admin-managed; never infer it from is_staff, email or QR binding.
|
|||
|
|
return Decimal("0.00") if getattr(user, "identity_type", None) == "employee" else self.price_cny
|
|||
|
|
|
|||
|
|
def application_label(self, user=None):
|
|||
|
|
amount = self.price_for_user(user)
|
|||
|
|
if amount == 0:
|
|||
|
|
price = "内部员工免费" if getattr(user, "identity_type", None) == "employee" else "免费"
|
|||
|
|
else:
|
|||
|
|
period = ("月" if self.billing_months == 1 else f"{self.billing_months}个月") if self.billing_months else (f"{self.duration_days}天" if self.duration_days else "次")
|
|||
|
|
price = f"{amount:.2f}元/{period}"
|
|||
|
|
quota = f"{self.traffic_limit_gb}G" if self.traffic_limit_gb else "不限流量"
|
|||
|
|
waiting = " · 暂未开放付款" if self.online_payment_required and amount > 0 else ""
|
|||
|
|
return f"{self.name} · {quota} · {price}{waiting}"
|
|||
|
|
|
|||
|
|
def period_end(self, start):
|
|||
|
|
if self.billing_months:
|
|||
|
|
local = timezone.localtime(start)
|
|||
|
|
index = local.year * 12 + local.month - 1 + self.billing_months
|
|||
|
|
year, month = divmod(index, 12)
|
|||
|
|
month += 1
|
|||
|
|
return local.replace(year=year, month=month,
|
|||
|
|
day=min(local.day, calendar.monthrange(year, month)[1]))
|
|||
|
|
return start + timedelta(days=self.duration_days) if self.duration_days else None
|
|||
|
|
|
|||
|
|
def clean(self):
|
|||
|
|
if self.price_cny < 0:
|
|||
|
|
raise ValidationError({"price_cny": "套餐价格不能为负数。"})
|
|||
|
|
if self.billing_months > 12:
|
|||
|
|
raise ValidationError({"billing_months": "周期最多为12个月。"})
|
|||
|
|
|
|||
|
|
|
|||
|
|
class RoutingPolicy(models.Model):
|
|||
|
|
name = models.CharField("策略名称", max_length=100)
|
|||
|
|
is_global = models.BooleanField("全局默认", default=False, db_index=True)
|
|||
|
|
active = models.BooleanField("启用", default=True)
|
|||
|
|
rules = models.JSONField(
|
|||
|
|
"Mihomo 路由规则",
|
|||
|
|
default=list,
|
|||
|
|
help_text="按顺序填写规则,例如 DOMAIN-SUFFIX,cn,DIRECT。未填写 MATCH 时系统自动补充。",
|
|||
|
|
)
|
|||
|
|
description = models.TextField("说明", blank=True)
|
|||
|
|
created_at = models.DateTimeField("创建时间", auto_now_add=True)
|
|||
|
|
updated_at = models.DateTimeField("更新时间", auto_now=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "路由策略"
|
|||
|
|
verbose_name_plural = "路由策略"
|
|||
|
|
ordering = ["-is_global", "name"]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return f"{self.name}{'(全局)' if self.is_global else ''}"
|
|||
|
|
|
|||
|
|
def clean(self):
|
|||
|
|
if not isinstance(self.rules, list) or any(not isinstance(rule, str) for rule in self.rules):
|
|||
|
|
raise ValidationError({"rules": "路由规则必须是字符串数组。"})
|
|||
|
|
|
|||
|
|
def save(self, *args, **kwargs):
|
|||
|
|
with transaction.atomic():
|
|||
|
|
if self.is_global:
|
|||
|
|
RoutingPolicy.objects.exclude(pk=self.pk).filter(is_global=True).update(is_global=False)
|
|||
|
|
return super().save(*args, **kwargs)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class Node(models.Model):
|
|||
|
|
class Protocol(models.TextChoices):
|
|||
|
|
VLESS_REALITY = "vless_reality", "VLESS Reality"
|
|||
|
|
TROJAN_TLS = "trojan_tls", "Trojan TLS"
|
|||
|
|
HYSTERIA2 = "hysteria2", "Hysteria2"
|
|||
|
|
|
|||
|
|
class Status(models.TextChoices):
|
|||
|
|
PREPARING = "preparing", "准备中"
|
|||
|
|
ONLINE = "online", "在线"
|
|||
|
|
MAINTENANCE = "maintenance", "维护"
|
|||
|
|
OFFLINE = "offline", "离线"
|
|||
|
|
|
|||
|
|
class OfficeAccessScope(models.TextChoices):
|
|||
|
|
COMPANY_NETWORK = "company_network", "公司网络内的在职内部账号"
|
|||
|
|
EXPLICIT_USERS = "explicit_users", "保留原人工白名单"
|
|||
|
|
|
|||
|
|
name = models.CharField("节点名称", max_length=100)
|
|||
|
|
slug = models.SlugField("节点标识", max_length=80, unique=True)
|
|||
|
|
region = models.CharField("地区", max_length=100)
|
|||
|
|
server = models.CharField("服务器地址", max_length=255)
|
|||
|
|
port = models.PositiveIntegerField("端口")
|
|||
|
|
protocol = models.CharField("协议", max_length=30, choices=Protocol.choices)
|
|||
|
|
status = models.CharField("状态", max_length=20, choices=Status.choices, default=Status.PREPARING, db_index=True)
|
|||
|
|
active = models.BooleanField("启用", default=True)
|
|||
|
|
subscription_enabled = models.BooleanField("加入订阅", default=False)
|
|||
|
|
sort_order = models.PositiveSmallIntegerField("排序", default=10)
|
|||
|
|
fallback_only = models.BooleanField("仅最终备用", default=False, help_text="不参与日常负载分配,主节点不可用时才使用。")
|
|||
|
|
office_only = models.BooleanField("仅办公室内网", default=False, db_default=False)
|
|||
|
|
office_access_scope = models.CharField(
|
|||
|
|
"办公室候选范围", max_length=24, choices=OfficeAccessScope.choices,
|
|||
|
|
default=OfficeAccessScope.COMPANY_NETWORK, db_default="company_network",
|
|||
|
|
help_text="公司网络模式不按员工所属办公室筛人。这里只生成网络验证候选,仍需通过登记站点的加密验证;公网IP、GPS、网关品牌都不能直接放行。",
|
|||
|
|
)
|
|||
|
|
office_users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="authorized_office_nodes", verbose_name="办公室授权员工")
|
|||
|
|
sni = models.CharField("SNI/域名", max_length=255, blank=True)
|
|||
|
|
reality_public_key = models.CharField("Reality 公钥", max_length=255, blank=True)
|
|||
|
|
reality_short_id = models.CharField("Reality Short ID", max_length=64, blank=True)
|
|||
|
|
flow = models.CharField("Flow", max_length=80, blank=True, default="xtls-rprx-vision")
|
|||
|
|
transport = models.CharField("传输层", max_length=30, default="tcp")
|
|||
|
|
client_fingerprint = models.CharField("客户端指纹", max_length=30, default="chrome")
|
|||
|
|
skip_cert_verify = models.BooleanField("跳过证书校验", default=False)
|
|||
|
|
last_seen_at = models.DateTimeField("最后上报", null=True, blank=True)
|
|||
|
|
agent_version = models.CharField("节点代理版本", max_length=64, blank=True)
|
|||
|
|
agent_token_digest = models.CharField("节点令牌摘要", max_length=64, blank=True, editable=False)
|
|||
|
|
total_upload_bytes = models.PositiveBigIntegerField("累计上传", default=0)
|
|||
|
|
total_download_bytes = models.PositiveBigIntegerField("累计下载", default=0)
|
|||
|
|
created_at = models.DateTimeField("创建时间", auto_now_add=True)
|
|||
|
|
updated_at = models.DateTimeField("更新时间", auto_now=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "节点"
|
|||
|
|
verbose_name_plural = "节点"
|
|||
|
|
ordering = ["sort_order", "region", "name"]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return f"{self.name} · {self.region}"
|
|||
|
|
|
|||
|
|
def clean(self):
|
|||
|
|
if not 1 <= self.port <= 65535:
|
|||
|
|
raise ValidationError({"port": "端口必须在 1 到 65535 之间。"})
|
|||
|
|
if self.protocol == self.Protocol.VLESS_REALITY:
|
|||
|
|
missing = [name for name in ("sni", "reality_public_key", "reality_short_id") if not getattr(self, name)]
|
|||
|
|
if missing:
|
|||
|
|
raise ValidationError("VLESS Reality 节点必须填写 SNI、公钥和 Short ID。")
|
|||
|
|
|
|||
|
|
def set_agent_token(self, token):
|
|||
|
|
self.agent_token_digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
|||
|
|
|
|||
|
|
def check_agent_token(self, token):
|
|||
|
|
if not token or not self.agent_token_digest:
|
|||
|
|
return False
|
|||
|
|
supplied = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
|||
|
|
return secrets.compare_digest(self.agent_token_digest, supplied)
|
|||
|
|
|
|||
|
|
def to_mihomo_proxy(self, subscription):
|
|||
|
|
common = {
|
|||
|
|
"name": self.name,
|
|||
|
|
"server": self.server,
|
|||
|
|
"port": self.port,
|
|||
|
|
"udp": True,
|
|||
|
|
}
|
|||
|
|
credential = str(subscription.credential_uuid)
|
|||
|
|
if self.protocol == self.Protocol.VLESS_REALITY:
|
|||
|
|
return {
|
|||
|
|
**common,
|
|||
|
|
"type": "vless",
|
|||
|
|
"uuid": credential,
|
|||
|
|
"network": self.transport,
|
|||
|
|
"tls": True,
|
|||
|
|
"servername": self.sni,
|
|||
|
|
"flow": self.flow,
|
|||
|
|
"client-fingerprint": self.client_fingerprint,
|
|||
|
|
"reality-opts": {
|
|||
|
|
"public-key": self.reality_public_key,
|
|||
|
|
"short-id": self.reality_short_id,
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
if self.protocol == self.Protocol.TROJAN_TLS:
|
|||
|
|
return {
|
|||
|
|
**common,
|
|||
|
|
"type": "trojan",
|
|||
|
|
"password": credential,
|
|||
|
|
"sni": self.sni,
|
|||
|
|
"skip-cert-verify": self.skip_cert_verify,
|
|||
|
|
}
|
|||
|
|
if self.protocol == self.Protocol.HYSTERIA2:
|
|||
|
|
return {
|
|||
|
|
**common,
|
|||
|
|
"type": "hysteria2",
|
|||
|
|
"password": credential,
|
|||
|
|
"sni": self.sni,
|
|||
|
|
"skip-cert-verify": self.skip_cert_verify,
|
|||
|
|
}
|
|||
|
|
raise ValidationError(f"节点协议 {self.protocol} 暂不支持生成订阅。")
|
|||
|
|
|
|||
|
|
|
|||
|
|
class Subscription(models.Model):
|
|||
|
|
class Status(models.TextChoices):
|
|||
|
|
PENDING = "pending", "待开通"
|
|||
|
|
ACTIVE = "active", "使用中"
|
|||
|
|
SUSPENDED = "suspended", "已暂停"
|
|||
|
|
EXPIRED = "expired", "已到期"
|
|||
|
|
CANCELLED = "cancelled", "已取消"
|
|||
|
|
|
|||
|
|
class RouteMode(models.TextChoices):
|
|||
|
|
GLOBAL = "global", "使用全局策略"
|
|||
|
|
CUSTOM = "custom", "使用专用策略"
|
|||
|
|
DEDICATED = "dedicated", "指定节点"
|
|||
|
|
|
|||
|
|
class ProvisioningState(models.TextChoices):
|
|||
|
|
PENDING = "pending", "等待下发"
|
|||
|
|
ACTIVE = "active", "已下发"
|
|||
|
|
FAILED = "failed", "下发失败"
|
|||
|
|
REVOKE_PENDING = "revoke_pending", "等待撤销"
|
|||
|
|
REVOKED = "revoked", "已撤销"
|
|||
|
|
|
|||
|
|
user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="用户", on_delete=models.PROTECT, related_name="subscriptions")
|
|||
|
|
plan = models.ForeignKey(Plan, verbose_name="套餐", on_delete=models.PROTECT, related_name="subscriptions")
|
|||
|
|
status = models.CharField("状态", max_length=20, choices=Status.choices, default=Status.PENDING, db_index=True)
|
|||
|
|
starts_at = models.DateTimeField("开始时间", null=True, blank=True)
|
|||
|
|
expires_at = models.DateTimeField("到期时间", null=True, blank=True, db_index=True)
|
|||
|
|
traffic_limit_bytes = models.PositiveBigIntegerField("流量额度(字节)", default=0)
|
|||
|
|
upload_bytes = models.PositiveBigIntegerField("已用上传", default=0)
|
|||
|
|
download_bytes = models.PositiveBigIntegerField("已用下载", default=0)
|
|||
|
|
device_limit = models.PositiveSmallIntegerField("设备数", default=3)
|
|||
|
|
route_mode = models.CharField("路由模式", max_length=20, choices=RouteMode.choices, default=RouteMode.GLOBAL)
|
|||
|
|
routing_policy = models.ForeignKey(
|
|||
|
|
RoutingPolicy,
|
|||
|
|
verbose_name="专用路由策略",
|
|||
|
|
null=True,
|
|||
|
|
blank=True,
|
|||
|
|
on_delete=models.SET_NULL,
|
|||
|
|
related_name="subscriptions",
|
|||
|
|
)
|
|||
|
|
allowed_nodes = models.ManyToManyField(Node, verbose_name="指定节点", blank=True, related_name="subscriptions")
|
|||
|
|
credential_uuid = models.UUIDField("节点凭据", default=uuid.uuid4, unique=True, editable=False)
|
|||
|
|
token_version = models.PositiveIntegerField("订阅令牌版本", default=1, editable=False)
|
|||
|
|
provisioning_state = models.CharField(
|
|||
|
|
"节点下发状态",
|
|||
|
|
max_length=24,
|
|||
|
|
choices=ProvisioningState.choices,
|
|||
|
|
default=ProvisioningState.PENDING,
|
|||
|
|
)
|
|||
|
|
state_reason = models.CharField("状态说明", max_length=255, blank=True)
|
|||
|
|
created_at = models.DateTimeField("创建时间", auto_now_add=True)
|
|||
|
|
updated_at = models.DateTimeField("更新时间", auto_now=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "订阅"
|
|||
|
|
verbose_name_plural = "订阅"
|
|||
|
|
ordering = ["-created_at"]
|
|||
|
|
indexes = [models.Index(fields=["status", "expires_at"])]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return f"{self.user} · {self.plan}"
|
|||
|
|
|
|||
|
|
def clean(self):
|
|||
|
|
if self.route_mode == self.RouteMode.CUSTOM and not self.routing_policy:
|
|||
|
|
raise ValidationError({"routing_policy": "专用路由模式必须选择路由策略。"})
|
|||
|
|
if self.plan_id and self.user_id:
|
|||
|
|
if self.status == self.Status.ACTIVE and self.online_payment_pending:
|
|||
|
|
raise ValidationError({"status": "在线收款尚未接通,此付费套餐不能人工开通。"})
|
|||
|
|
if self.plan.audience == Plan.Audience.EMPLOYEE and self.user.identity_type != "employee":
|
|||
|
|
raise ValidationError({"plan": "该套餐仅限内部员工。"})
|
|||
|
|
duplicate = Subscription.objects.exclude(pk=self.pk).filter(
|
|||
|
|
user_id=self.user_id,
|
|||
|
|
status__in=[self.Status.PENDING, self.Status.ACTIVE, self.Status.SUSPENDED],
|
|||
|
|
)
|
|||
|
|
if duplicate.exists():
|
|||
|
|
raise ValidationError("该用户已有未结束的订阅。")
|
|||
|
|
|
|||
|
|
def save(self, *args, **kwargs):
|
|||
|
|
if self._state.adding and self.plan_id:
|
|||
|
|
self.apply_plan_snapshot()
|
|||
|
|
return super().save(*args, **kwargs)
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def used_bytes(self):
|
|||
|
|
return self.upload_bytes + self.download_bytes
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def remaining_bytes(self):
|
|||
|
|
if not self.traffic_limit_bytes:
|
|||
|
|
return None
|
|||
|
|
return max(0, self.traffic_limit_bytes - self.used_bytes)
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def usage_percent(self):
|
|||
|
|
if not self.traffic_limit_bytes:
|
|||
|
|
return 0
|
|||
|
|
return min(100, round(self.used_bytes * 100 / self.traffic_limit_bytes, 1))
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def online_payment_pending(self):
|
|||
|
|
# No verified-receipt adapter exists yet. Never treat an editable PAID
|
|||
|
|
# flag, an enabled catalog entry, or a manually active row as a receipt.
|
|||
|
|
return self.plan.online_payment_required and self.plan.price_for_user(self.user) > 0
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def is_usable(self):
|
|||
|
|
if (
|
|||
|
|
self.status != self.Status.ACTIVE
|
|||
|
|
or self.provisioning_state != self.ProvisioningState.ACTIVE
|
|||
|
|
or not self.user.service_enabled
|
|||
|
|
or self.online_payment_pending
|
|||
|
|
):
|
|||
|
|
return False
|
|||
|
|
if self.expires_at and self.expires_at <= timezone.now():
|
|||
|
|
return False
|
|||
|
|
if self.traffic_limit_bytes and self.used_bytes >= self.traffic_limit_bytes:
|
|||
|
|
return False
|
|||
|
|
return True
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def subscription_token(self):
|
|||
|
|
if not self.pk:
|
|||
|
|
return ""
|
|||
|
|
return signing.dumps(
|
|||
|
|
{"subscription_id": self.pk, "version": self.token_version},
|
|||
|
|
salt="toplc-vpn-subscription",
|
|||
|
|
compress=True,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def subscription_url(self):
|
|||
|
|
if not self.pk:
|
|||
|
|
return ""
|
|||
|
|
return f"{settings.PUBLIC_BASE_URL}/sub/{self.subscription_token}/config.yaml"
|
|||
|
|
|
|||
|
|
def apply_plan_snapshot(self):
|
|||
|
|
self.traffic_limit_bytes = self.plan.traffic_limit_bytes
|
|||
|
|
self.device_limit = self.plan.device_limit
|
|||
|
|
|
|||
|
|
def activate(self):
|
|||
|
|
if self.plan.online_payment_required and self.plan.price_for_user(self.user) > 0:
|
|||
|
|
raise ValidationError("在线收款尚未接通,此套餐不能人工开通。")
|
|||
|
|
if not self.user.service_enabled:
|
|||
|
|
raise ValidationError("用户账号尚未审核为正常状态。")
|
|||
|
|
now = timezone.now()
|
|||
|
|
self.apply_plan_snapshot()
|
|||
|
|
self.status = self.Status.ACTIVE
|
|||
|
|
self.starts_at = self.starts_at or now
|
|||
|
|
self.expires_at = self.plan.period_end(self.starts_at)
|
|||
|
|
self.provisioning_state = self.ProvisioningState.PENDING
|
|||
|
|
self.state_reason = ""
|
|||
|
|
self.save()
|
|||
|
|
|
|||
|
|
def suspend(self, reason=""):
|
|||
|
|
self.status = self.Status.SUSPENDED
|
|||
|
|
self.provisioning_state = self.ProvisioningState.REVOKE_PENDING
|
|||
|
|
self.state_reason = reason
|
|||
|
|
self.save(update_fields=["status", "provisioning_state", "state_reason", "updated_at"])
|
|||
|
|
|
|||
|
|
def cancel(self, reason=""):
|
|||
|
|
self.status = self.Status.CANCELLED
|
|||
|
|
self.provisioning_state = self.ProvisioningState.REVOKE_PENDING
|
|||
|
|
self.state_reason = reason
|
|||
|
|
self.credential_uuid = uuid.uuid4()
|
|||
|
|
self.token_version += 1
|
|||
|
|
self.save(
|
|||
|
|
update_fields=[
|
|||
|
|
"status",
|
|||
|
|
"provisioning_state",
|
|||
|
|
"state_reason",
|
|||
|
|
"credential_uuid",
|
|||
|
|
"token_version",
|
|||
|
|
"updated_at",
|
|||
|
|
]
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
def rotate_subscription(self):
|
|||
|
|
self.token_version += 1
|
|||
|
|
self.save(update_fields=["token_version", "updated_at"])
|
|||
|
|
|
|||
|
|
def nodes_for_subscription(self):
|
|||
|
|
nodes = Node.objects.filter(active=True, subscription_enabled=True, status=Node.Status.ONLINE)
|
|||
|
|
# Legacy profiles/configs must NEVER get a LAN node solely because their
|
|||
|
|
# subscription includes all nodes. Local identity proof is not wired yet.
|
|||
|
|
nodes = nodes.filter(office_only=False)
|
|||
|
|
if self.route_mode == self.RouteMode.DEDICATED:
|
|||
|
|
nodes = nodes.filter(pk__in=self.allowed_nodes.values("pk"))
|
|||
|
|
return nodes.order_by("sort_order", "name")
|
|||
|
|
|
|||
|
|
def office_nodes_for_authorization(self):
|
|||
|
|
"""Permission candidates only, NOT proof of office presence or a config grant.
|
|||
|
|
|
|||
|
|
Membership of a particular office/department is NOT required in company-
|
|||
|
|
network mode. Keep separate from nodes_for_subscription until the enrolled
|
|||
|
|
site/network proof and encrypted ingress are implemented and tested.
|
|||
|
|
"""
|
|||
|
|
user = self.user
|
|||
|
|
if not self.is_usable or user.identity_type != "employee" or not user.service_enabled:
|
|||
|
|
return Node.objects.none()
|
|||
|
|
nodes = Node.objects.filter(office_only=True, active=True,
|
|||
|
|
subscription_enabled=True, status=Node.Status.ONLINE).filter(
|
|||
|
|
models.Q(office_access_scope=Node.OfficeAccessScope.COMPANY_NETWORK)
|
|||
|
|
| models.Q(office_access_scope=Node.OfficeAccessScope.EXPLICIT_USERS, office_users=user)
|
|||
|
|
)
|
|||
|
|
if self.route_mode == self.RouteMode.DEDICATED:
|
|||
|
|
nodes = nodes.filter(pk__in=self.allowed_nodes.values("pk"))
|
|||
|
|
return nodes.order_by("sort_order", "name").distinct()
|
|||
|
|
|
|||
|
|
def effective_routing_policy(self):
|
|||
|
|
if self.route_mode == self.RouteMode.CUSTOM and self.routing_policy_id:
|
|||
|
|
return self.routing_policy
|
|||
|
|
return RoutingPolicy.objects.filter(is_global=True, active=True).first()
|
|||
|
|
|
|||
|
|
|
|||
|
|
class PlanApplication(models.Model):
|
|||
|
|
class Status(models.TextChoices):
|
|||
|
|
PENDING = "pending", "待处理"
|
|||
|
|
APPROVED = "approved", "已批准"
|
|||
|
|
REJECTED = "rejected", "已拒绝"
|
|||
|
|
CANCELLED = "cancelled", "已取消"
|
|||
|
|
|
|||
|
|
class PaymentStatus(models.TextChoices):
|
|||
|
|
NOT_REQUIRED = "not_required", "无需付款"
|
|||
|
|
UNPAID = "unpaid", "待付款"
|
|||
|
|
PAID = "paid", "已付款"
|
|||
|
|
REFUNDED = "refunded", "已退款"
|
|||
|
|
|
|||
|
|
user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="申请人", on_delete=models.PROTECT, related_name="plan_applications")
|
|||
|
|
plan = models.ForeignKey(Plan, verbose_name="申请套餐", on_delete=models.PROTECT, related_name="applications")
|
|||
|
|
subscription = models.ForeignKey(
|
|||
|
|
Subscription,
|
|||
|
|
verbose_name="自动开通的订阅",
|
|||
|
|
null=True,
|
|||
|
|
blank=True,
|
|||
|
|
editable=False,
|
|||
|
|
on_delete=models.PROTECT,
|
|||
|
|
related_name="plan_applications",
|
|||
|
|
)
|
|||
|
|
status = models.CharField("处理状态", max_length=20, choices=Status.choices, default=Status.PENDING, db_index=True)
|
|||
|
|
payment_status = models.CharField("付款状态", max_length=20, choices=PaymentStatus.choices, default=PaymentStatus.UNPAID)
|
|||
|
|
note = models.TextField("申请说明", blank=True)
|
|||
|
|
reviewer_note = models.TextField("审核备注", blank=True)
|
|||
|
|
reviewed_by = models.ForeignKey(
|
|||
|
|
settings.AUTH_USER_MODEL,
|
|||
|
|
verbose_name="审核人",
|
|||
|
|
null=True,
|
|||
|
|
blank=True,
|
|||
|
|
on_delete=models.SET_NULL,
|
|||
|
|
related_name="reviewed_plan_applications",
|
|||
|
|
)
|
|||
|
|
reviewed_at = models.DateTimeField("审核时间", null=True, blank=True)
|
|||
|
|
created_at = models.DateTimeField("申请时间", auto_now_add=True)
|
|||
|
|
updated_at = models.DateTimeField("更新时间", auto_now=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "套餐申请"
|
|||
|
|
verbose_name_plural = "套餐申请"
|
|||
|
|
ordering = ["-created_at"]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return f"{self.user} 申请 {self.plan}"
|
|||
|
|
|
|||
|
|
def approve(self, reviewer):
|
|||
|
|
with transaction.atomic():
|
|||
|
|
# All approval entry points lock user -> application -> plan -> subscription.
|
|||
|
|
# Do not FOR UPDATE a nullable select_related join (PostgreSQL rejects it).
|
|||
|
|
owner_id = type(self).objects.values_list("user_id", flat=True).get(pk=self.pk)
|
|||
|
|
user = get_user_model().objects.select_for_update().get(pk=owner_id)
|
|||
|
|
application = type(self).objects.select_for_update().get(pk=self.pk)
|
|||
|
|
if application.user_id != user.pk:
|
|||
|
|
raise ValidationError("申请归属已改变,请刷新后重试。")
|
|||
|
|
if application.status == self.Status.APPROVED and application.subscription_id:
|
|||
|
|
self.refresh_from_db()
|
|||
|
|
return application.subscription
|
|||
|
|
if application.status != self.Status.PENDING:
|
|||
|
|
raise ValidationError("只有待处理申请可以批准。")
|
|||
|
|
if not user.plan_application_allowed:
|
|||
|
|
raise ValidationError("申请人账号已暂停、离职、停用或状态异常;请先在用户管理中核实,套餐审核不会恢复账号。")
|
|||
|
|
application.plan = Plan.objects.select_for_update().get(pk=application.plan_id)
|
|||
|
|
if not application.plan.active:
|
|||
|
|
raise ValidationError("该套餐已停用,不能批准。")
|
|||
|
|
if application.plan.audience not in [Plan.Audience.ALL, user.identity_type]:
|
|||
|
|
raise ValidationError("套餐适用身份与申请人当前身份不符,请先核实身份或更换套餐。")
|
|||
|
|
if application.plan.employee_benefit and user.identity_type != "employee":
|
|||
|
|
raise ValidationError("员工福利套餐必须先核实内部员工身份。")
|
|||
|
|
amount = application.plan.price_for_user(user)
|
|||
|
|
if amount > 0 and application.plan.online_payment_required:
|
|||
|
|
raise ValidationError("在线收款尚未接通,不能人工标记付款来开通此套餐。")
|
|||
|
|
if amount > 0 and application.payment_status != self.PaymentStatus.PAID:
|
|||
|
|
raise ValidationError("付费套餐必须先标记为已付款。")
|
|||
|
|
if amount == 0 and application.payment_status in (self.PaymentStatus.UNPAID, self.PaymentStatus.NOT_REQUIRED):
|
|||
|
|
application.payment_status = self.PaymentStatus.NOT_REQUIRED
|
|||
|
|
|
|||
|
|
user.account_status = user.AccountStatus.ACTIVE
|
|||
|
|
user.approved_at = timezone.now()
|
|||
|
|
user.approved_by = reviewer
|
|||
|
|
user.save(update_fields=["account_status", "approved_at", "approved_by"])
|
|||
|
|
|
|||
|
|
open_statuses = [Subscription.Status.PENDING, Subscription.Status.ACTIVE, Subscription.Status.SUSPENDED]
|
|||
|
|
open_subscriptions = list(
|
|||
|
|
Subscription.objects.select_for_update()
|
|||
|
|
.filter(user=user, status__in=open_statuses)
|
|||
|
|
.order_by("-updated_at", "-pk")
|
|||
|
|
)
|
|||
|
|
if len(open_subscriptions) > 1:
|
|||
|
|
raise ValidationError("存在多个未结束订阅,请管理员核查;本次未取消任何订阅。")
|
|||
|
|
subscription = open_subscriptions[0] if open_subscriptions else Subscription(user=user, plan=application.plan)
|
|||
|
|
subscription.user = user
|
|||
|
|
|
|||
|
|
now = timezone.now()
|
|||
|
|
subscription.plan = application.plan
|
|||
|
|
subscription.apply_plan_snapshot()
|
|||
|
|
subscription.status = Subscription.Status.ACTIVE
|
|||
|
|
# A plan change is not an implicit renewal or a quota reset. Preserve
|
|||
|
|
# existing period, usage, credential, devices, and routing policy.
|
|||
|
|
if subscription.starts_at is None:
|
|||
|
|
subscription.starts_at = now
|
|||
|
|
subscription.expires_at = application.plan.period_end(now)
|
|||
|
|
subscription.provisioning_state = Subscription.ProvisioningState.PENDING
|
|||
|
|
subscription.state_reason = ""
|
|||
|
|
subscription.full_clean()
|
|||
|
|
subscription.save()
|
|||
|
|
application.status = self.Status.APPROVED
|
|||
|
|
application.subscription = subscription
|
|||
|
|
application.reviewed_by = reviewer
|
|||
|
|
application.reviewed_at = now
|
|||
|
|
application.save(
|
|||
|
|
update_fields=["status", "payment_status", "subscription", "reviewed_by", "reviewed_at", "updated_at"]
|
|||
|
|
)
|
|||
|
|
self.status = application.status
|
|||
|
|
self.subscription = subscription
|
|||
|
|
self.reviewed_by = reviewer
|
|||
|
|
self.reviewed_at = now
|
|||
|
|
self.payment_status = application.payment_status
|
|||
|
|
return subscription
|
|||
|
|
|
|||
|
|
@classmethod
|
|||
|
|
def submit(cls, *, user, plan, note=""):
|
|||
|
|
with transaction.atomic():
|
|||
|
|
user = get_user_model().objects.select_for_update().get(pk=user.pk)
|
|||
|
|
if not user.plan_application_allowed:
|
|||
|
|
raise ValidationError("账号当前不可申请套餐,请联系管理员核实账号状态。")
|
|||
|
|
plan = Plan.objects.select_for_update().get(pk=plan.pk)
|
|||
|
|
audiences = [Plan.Audience.ALL, user.identity_type]
|
|||
|
|
if not plan.active or plan.audience not in audiences or (
|
|||
|
|
plan.employee_benefit and user.identity_type != "employee"
|
|||
|
|
):
|
|||
|
|
raise ValidationError("该套餐当前不可申请,请重新选择。")
|
|||
|
|
if cls.objects.filter(user=user, status=cls.Status.PENDING).exists():
|
|||
|
|
raise ValidationError("您已有待处理申请,请等待管理员审核。")
|
|||
|
|
if user.subscriptions.filter(
|
|||
|
|
plan=plan, status__in=[Subscription.Status.PENDING, Subscription.Status.ACTIVE, Subscription.Status.SUSPENDED]
|
|||
|
|
).exists():
|
|||
|
|
raise ValidationError("您当前已经在使用该套餐,无需重复申请。")
|
|||
|
|
return cls.objects.create(
|
|||
|
|
user=user, plan=plan, note=note,
|
|||
|
|
payment_status=cls.PaymentStatus.NOT_REQUIRED if plan.price_for_user(user) == 0 else cls.PaymentStatus.UNPAID,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class UsageRecord(models.Model):
|
|||
|
|
subscription = models.ForeignKey(Subscription, verbose_name="订阅", on_delete=models.CASCADE, related_name="usage_records")
|
|||
|
|
node = models.ForeignKey(Node, verbose_name="节点", on_delete=models.PROTECT, related_name="usage_records")
|
|||
|
|
day = models.DateField("日期")
|
|||
|
|
upload_bytes = models.PositiveBigIntegerField("上传", default=0)
|
|||
|
|
download_bytes = models.PositiveBigIntegerField("下载", default=0)
|
|||
|
|
created_at = models.DateTimeField("创建时间", auto_now_add=True)
|
|||
|
|
updated_at = models.DateTimeField("更新时间", auto_now=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "每日流量"
|
|||
|
|
verbose_name_plural = "每日流量"
|
|||
|
|
ordering = ["-day", "subscription_id"]
|
|||
|
|
constraints = [
|
|||
|
|
models.UniqueConstraint(fields=["subscription", "node", "day"], name="unique_subscription_node_day")
|
|||
|
|
]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return f"{self.subscription} · {self.day}"
|
|||
|
|
|
|||
|
|
|
|||
|
|
class HourlyUsageRecord(models.Model):
|
|||
|
|
"""Proxy deltas grouped by server receipt hour, not a second billing ledger."""
|
|||
|
|
subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE, related_name="hourly_usage_records")
|
|||
|
|
node = models.ForeignKey(Node, on_delete=models.PROTECT, related_name="hourly_usage_records")
|
|||
|
|
hour = models.DateTimeField()
|
|||
|
|
upload_bytes = models.PositiveBigIntegerField(default=0)
|
|||
|
|
download_bytes = models.PositiveBigIntegerField(default=0)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
constraints = [models.UniqueConstraint(fields=["subscription", "node", "hour"], name="unique_subscription_node_hour")]
|
|||
|
|
indexes = [models.Index(fields=["subscription", "hour"], name="usage_subscription_hour")]
|
|||
|
|
|
|||
|
|
|
|||
|
|
class Device(models.Model):
|
|||
|
|
subscription = models.ForeignKey(Subscription, verbose_name="订阅", on_delete=models.CASCADE, related_name="devices")
|
|||
|
|
device_id = models.CharField("设备标识", max_length=128)
|
|||
|
|
name = models.CharField("设备名称", max_length=100, blank=True)
|
|||
|
|
platform = models.CharField("平台", max_length=50, blank=True)
|
|||
|
|
active = models.BooleanField("允许使用", default=True)
|
|||
|
|
last_seen_at = models.DateTimeField("最后在线", null=True, blank=True)
|
|||
|
|
upload_bytes = models.PositiveBigIntegerField("上传", default=0)
|
|||
|
|
download_bytes = models.PositiveBigIntegerField("下载", default=0)
|
|||
|
|
created_at = models.DateTimeField("首次出现", auto_now_add=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "设备"
|
|||
|
|
verbose_name_plural = "设备"
|
|||
|
|
constraints = [models.UniqueConstraint(fields=["subscription", "device_id"], name="unique_subscription_device")]
|
|||
|
|
ordering = ["-last_seen_at", "name"]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return self.name or self.device_id
|
|||
|
|
|
|||
|
|
|
|||
|
|
class ClientSession(models.Model):
|
|||
|
|
subscription = models.ForeignKey(
|
|||
|
|
Subscription,
|
|||
|
|
verbose_name="订阅",
|
|||
|
|
on_delete=models.CASCADE,
|
|||
|
|
related_name="client_sessions",
|
|||
|
|
)
|
|||
|
|
device = models.ForeignKey(
|
|||
|
|
Device,
|
|||
|
|
verbose_name="设备",
|
|||
|
|
on_delete=models.CASCADE,
|
|||
|
|
related_name="sessions",
|
|||
|
|
)
|
|||
|
|
token_digest = models.CharField("访问令牌摘要", max_length=64, unique=True, editable=False)
|
|||
|
|
expires_at = models.DateTimeField("令牌到期时间", db_index=True)
|
|||
|
|
last_seen_at = models.DateTimeField("最后访问", auto_now_add=True)
|
|||
|
|
revoked_at = models.DateTimeField("撤销时间", null=True, blank=True, db_index=True)
|
|||
|
|
created_at = models.DateTimeField("创建时间", auto_now_add=True)
|
|||
|
|
assigned_node = models.ForeignKey(Node, null=True, blank=True, on_delete=models.SET_NULL, related_name="assigned_sessions", verbose_name="AI 分配节点")
|
|||
|
|
dispatch_decision = models.JSONField("最近调度依据", default=dict, blank=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "客户端会话"
|
|||
|
|
verbose_name_plural = "客户端会话"
|
|||
|
|
ordering = ["-last_seen_at"]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return f"{self.subscription.user} · {self.device}"
|
|||
|
|
|
|||
|
|
@staticmethod
|
|||
|
|
def digest_token(token):
|
|||
|
|
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
|||
|
|
|
|||
|
|
@classmethod
|
|||
|
|
def issue(cls, subscription, device, lifetime=timedelta(days=30)):
|
|||
|
|
token = secrets.token_urlsafe(32)
|
|||
|
|
session = cls.objects.create(
|
|||
|
|
subscription=subscription,
|
|||
|
|
device=device,
|
|||
|
|
token_digest=cls.digest_token(token),
|
|||
|
|
expires_at=timezone.now() + lifetime,
|
|||
|
|
)
|
|||
|
|
return session, token
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def is_valid(self):
|
|||
|
|
return self.revoked_at is None and self.expires_at > timezone.now()
|
|||
|
|
|
|||
|
|
|
|||
|
|
class NodeDeployment(models.Model):
|
|||
|
|
subscription = models.ForeignKey(
|
|||
|
|
Subscription,
|
|||
|
|
verbose_name="订阅",
|
|||
|
|
on_delete=models.CASCADE,
|
|||
|
|
related_name="node_deployments",
|
|||
|
|
)
|
|||
|
|
node = models.ForeignKey(Node, verbose_name="节点", on_delete=models.CASCADE, related_name="deployments")
|
|||
|
|
deployed = models.BooleanField("已在节点生效", default=False)
|
|||
|
|
applied_at = models.DateTimeField("最近生效时间", null=True, blank=True)
|
|||
|
|
revoked_at = models.DateTimeField("最近撤销时间", null=True, blank=True)
|
|||
|
|
last_error = models.CharField("最近错误", max_length=500, blank=True)
|
|||
|
|
updated_at = models.DateTimeField("更新时间", auto_now=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "节点下发状态"
|
|||
|
|
verbose_name_plural = "节点下发状态"
|
|||
|
|
constraints = [
|
|||
|
|
models.UniqueConstraint(fields=["subscription", "node"], name="unique_subscription_node_deployment")
|
|||
|
|
]
|
|||
|
|
ordering = ["node", "subscription"]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return f"{self.subscription} · {self.node}"
|
|||
|
|
|
|||
|
|
|
|||
|
|
class NodeReport(models.Model):
|
|||
|
|
node = models.ForeignKey(Node, verbose_name="节点", on_delete=models.CASCADE, related_name="reports")
|
|||
|
|
report_id = models.UUIDField("报告 ID")
|
|||
|
|
received_at = models.DateTimeField("接收时间", auto_now_add=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "节点上报去重记录"
|
|||
|
|
verbose_name_plural = "节点上报去重记录"
|
|||
|
|
constraints = [models.UniqueConstraint(fields=["node", "report_id"], name="unique_node_report")]
|
|||
|
|
ordering = ["-received_at"]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return f"{self.node.slug} · {self.report_id}"
|
|||
|
|
|
|||
|
|
|
|||
|
|
class NodeTrafficSample(models.Model):
|
|||
|
|
node = models.ForeignKey(
|
|||
|
|
Node,
|
|||
|
|
verbose_name="节点",
|
|||
|
|
on_delete=models.CASCADE,
|
|||
|
|
related_name="traffic_samples",
|
|||
|
|
)
|
|||
|
|
report = models.OneToOneField(
|
|||
|
|
NodeReport,
|
|||
|
|
verbose_name="节点报告",
|
|||
|
|
on_delete=models.SET_NULL,
|
|||
|
|
null=True,
|
|||
|
|
blank=True,
|
|||
|
|
related_name="traffic_sample",
|
|||
|
|
)
|
|||
|
|
sampled_at = models.DateTimeField("采样时间", auto_now_add=True, db_index=True)
|
|||
|
|
interval_seconds = models.PositiveSmallIntegerField("采样间隔(秒)", default=60)
|
|||
|
|
upload_bytes = models.PositiveBigIntegerField("区间上传", default=0)
|
|||
|
|
download_bytes = models.PositiveBigIntegerField("区间下载", default=0)
|
|||
|
|
upload_bytes_per_second = models.PositiveBigIntegerField("上传速度(B/s)", default=0)
|
|||
|
|
download_bytes_per_second = models.PositiveBigIntegerField("下载速度(B/s)", default=0)
|
|||
|
|
active_subscriptions = models.PositiveSmallIntegerField("已下发订阅数", default=0)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "节点流量采样"
|
|||
|
|
verbose_name_plural = "节点流量采样"
|
|||
|
|
ordering = ["-sampled_at"]
|
|||
|
|
indexes = [
|
|||
|
|
models.Index(fields=["node", "sampled_at"], name="node_traffic_node_sample_idx"),
|
|||
|
|
]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return f"{self.node.slug} · {self.sampled_at:%Y-%m-%d %H:%M:%S}"
|
|||
|
|
|
|||
|
|
|
|||
|
|
class RouteObservation(models.Model):
|
|||
|
|
class AccessKind(models.TextChoices):
|
|||
|
|
HTTP = "http", "HTTP/HTTPS 网页"
|
|||
|
|
SOCKET = "socket", "Socket 连接"
|
|||
|
|
|
|||
|
|
class TargetType(models.TextChoices):
|
|||
|
|
DOMAIN = "domain", "域名"
|
|||
|
|
IP = "ip", "IP 地址"
|
|||
|
|
|
|||
|
|
class Network(models.TextChoices):
|
|||
|
|
TCP = "tcp", "TCP"
|
|||
|
|
UDP = "udp", "UDP"
|
|||
|
|
|
|||
|
|
class Outcome(models.TextChoices):
|
|||
|
|
DIRECT_FAILED = "direct_failed", "直连失败"
|
|||
|
|
PROXY_SUCCEEDED = "proxy_succeeded", "代理成功"
|
|||
|
|
PROXY_FAILED = "proxy_failed", "代理失败"
|
|||
|
|
|
|||
|
|
class FailureKind(models.TextChoices):
|
|||
|
|
TIMEOUT = "timeout", "超时"
|
|||
|
|
RESET = "reset", "连接重置"
|
|||
|
|
DNS = "dns", "DNS 异常"
|
|||
|
|
TLS = "tls", "TLS 异常"
|
|||
|
|
UNREACHABLE = "unreachable", "不可达"
|
|||
|
|
OTHER = "other", "其他"
|
|||
|
|
|
|||
|
|
report_id = models.UUIDField("客户端报告 ID", unique=True)
|
|||
|
|
subscription = models.ForeignKey(
|
|||
|
|
Subscription,
|
|||
|
|
verbose_name="订阅",
|
|||
|
|
on_delete=models.CASCADE,
|
|||
|
|
related_name="route_observations",
|
|||
|
|
)
|
|||
|
|
device = models.ForeignKey(
|
|||
|
|
Device,
|
|||
|
|
verbose_name="设备",
|
|||
|
|
on_delete=models.CASCADE,
|
|||
|
|
related_name="route_observations",
|
|||
|
|
)
|
|||
|
|
node = models.ForeignKey(
|
|||
|
|
Node,
|
|||
|
|
verbose_name="节点",
|
|||
|
|
on_delete=models.SET_NULL,
|
|||
|
|
null=True,
|
|||
|
|
blank=True,
|
|||
|
|
related_name="route_observations",
|
|||
|
|
)
|
|||
|
|
target_type = models.CharField("目标类型", max_length=10, choices=TargetType.choices)
|
|||
|
|
target = models.CharField("目标", max_length=253, db_index=True)
|
|||
|
|
port = models.PositiveIntegerField("端口")
|
|||
|
|
access_kind = models.CharField(
|
|||
|
|
"访问方式",
|
|||
|
|
max_length=10,
|
|||
|
|
choices=AccessKind.choices,
|
|||
|
|
default=AccessKind.SOCKET,
|
|||
|
|
db_index=True,
|
|||
|
|
)
|
|||
|
|
network = models.CharField("网络协议", max_length=6, choices=Network.choices)
|
|||
|
|
outcome = models.CharField("结果", max_length=24, choices=Outcome.choices, db_index=True)
|
|||
|
|
failure_kind = models.CharField(
|
|||
|
|
"失败类型",
|
|||
|
|
max_length=20,
|
|||
|
|
choices=FailureKind.choices,
|
|||
|
|
default=FailureKind.OTHER,
|
|||
|
|
)
|
|||
|
|
client_version = models.CharField("客户端版本", max_length=30, blank=True)
|
|||
|
|
evidence_kind = models.CharField("验证方式", max_length=12, blank=True, db_default="")
|
|||
|
|
related_report_id = models.UUIDField("对应直连失败报告", null=True, blank=True)
|
|||
|
|
scope = models.CharField("观测范围", max_length=20, default="public", db_default="public")
|
|||
|
|
received_at = models.DateTimeField("接收时间", auto_now_add=True, db_index=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "AI 路由观测"
|
|||
|
|
verbose_name_plural = "AI 路由观测"
|
|||
|
|
ordering = ["-received_at"]
|
|||
|
|
indexes = [
|
|||
|
|
models.Index(fields=["target_type", "target", "received_at"], name="route_obs_target_time_idx"),
|
|||
|
|
models.Index(fields=["device", "received_at"], name="route_obs_device_time_idx"),
|
|||
|
|
]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return f"{self.target}:{self.port} · {self.get_outcome_display()}"
|
|||
|
|
|
|||
|
|
|
|||
|
|
class RoutePolicyReceipt(models.Model):
|
|||
|
|
device = models.OneToOneField(Device, on_delete=models.CASCADE, related_name="route_policy_receipt")
|
|||
|
|
offered_revision = models.CharField(max_length=64, blank=True)
|
|||
|
|
applied_revision = models.CharField(max_length=64, blank=True)
|
|||
|
|
offered_at = models.DateTimeField(null=True, blank=True)
|
|||
|
|
applied_at = models.DateTimeField(null=True, blank=True)
|
|||
|
|
last_status = models.CharField(max_length=20, default="offered")
|
|||
|
|
client_version = models.CharField(max_length=30, blank=True)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class LearnedRouteRule(models.Model):
|
|||
|
|
class Source(models.TextChoices):
|
|||
|
|
PRESET = "preset", "系统预置"
|
|||
|
|
AI = "ai", "AI 学习"
|
|||
|
|
MANUAL = "manual", "管理员添加"
|
|||
|
|
|
|||
|
|
class MatchMode(models.TextChoices):
|
|||
|
|
EXACT = "exact", "精确目标"
|
|||
|
|
SUFFIX = "suffix", "域名及其子域"
|
|||
|
|
|
|||
|
|
class Status(models.TextChoices):
|
|||
|
|
PENDING = "pending", "学习中"
|
|||
|
|
ACTIVE = "active", "已生效"
|
|||
|
|
DISABLED = "disabled", "已禁用"
|
|||
|
|
|
|||
|
|
target_type = models.CharField("目标类型", max_length=10, choices=RouteObservation.TargetType.choices)
|
|||
|
|
target = models.CharField("目标", max_length=253)
|
|||
|
|
source = models.CharField("规则来源", max_length=12, choices=Source.choices, default=Source.AI, db_index=True)
|
|||
|
|
match_mode = models.CharField(
|
|||
|
|
"匹配方式",
|
|||
|
|
max_length=12,
|
|||
|
|
choices=MatchMode.choices,
|
|||
|
|
default=MatchMode.EXACT,
|
|||
|
|
help_text="域名预置规则通常选择“域名及其子域”;IP 地址只能精确匹配。",
|
|||
|
|
)
|
|||
|
|
status = models.CharField("状态", max_length=12, choices=Status.choices, default=Status.PENDING, db_index=True)
|
|||
|
|
confidence = models.DecimalField("置信度", max_digits=5, decimal_places=4, default=Decimal("0"))
|
|||
|
|
failure_reports = models.PositiveIntegerField("直连失败数", default=0)
|
|||
|
|
proxy_success_reports = models.PositiveIntegerField("代理成功数", default=0)
|
|||
|
|
distinct_devices = models.PositiveIntegerField("设备数", default=0)
|
|||
|
|
reason = models.CharField("学习依据", max_length=500, blank=True)
|
|||
|
|
valid_until = models.DateTimeField("有效期至", null=True, blank=True, db_index=True)
|
|||
|
|
manually_locked = models.BooleanField("人工锁定", default=False, help_text="启用后 AI 不再自动改变状态。")
|
|||
|
|
first_seen_at = models.DateTimeField("首次发现", auto_now_add=True)
|
|||
|
|
last_evaluated_at = models.DateTimeField("最近评估", null=True, blank=True)
|
|||
|
|
updated_at = models.DateTimeField("更新时间", auto_now=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "智能代理规则"
|
|||
|
|
verbose_name_plural = "智能代理规则"
|
|||
|
|
ordering = ["-status", "-confidence", "target"]
|
|||
|
|
constraints = [
|
|||
|
|
models.UniqueConstraint(fields=["target_type", "target"], name="unique_learned_route_target")
|
|||
|
|
]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return f"{self.target} · {self.get_status_display()}"
|
|||
|
|
|
|||
|
|
def clean(self):
|
|||
|
|
if self.target_type == RouteObservation.TargetType.IP and self.match_mode != self.MatchMode.EXACT:
|
|||
|
|
raise ValidationError({"match_mode": "IP 地址只能使用精确目标匹配。"})
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def is_effective(self):
|
|||
|
|
return self.status == self.Status.ACTIVE and (not self.valid_until or self.valid_until > timezone.now())
|
|||
|
|
|
|||
|
|
|
|||
|
|
class VpnAiFinding(models.Model):
|
|||
|
|
class Category(models.TextChoices):
|
|||
|
|
ROUTING = "routing", "路由学习"
|
|||
|
|
NODE = "node", "节点运维"
|
|||
|
|
SUBSCRIPTION = "subscription", "订阅诊断"
|
|||
|
|
SECURITY = "security", "安全"
|
|||
|
|
|
|||
|
|
class Severity(models.TextChoices):
|
|||
|
|
INFO = "info", "提示"
|
|||
|
|
WARNING = "warning", "警告"
|
|||
|
|
CRITICAL = "critical", "严重"
|
|||
|
|
|
|||
|
|
class Status(models.TextChoices):
|
|||
|
|
OPEN = "open", "待处理"
|
|||
|
|
RESOLVED = "resolved", "已恢复"
|
|||
|
|
IGNORED = "ignored", "已忽略"
|
|||
|
|
|
|||
|
|
fingerprint = models.CharField("诊断指纹", max_length=255, unique=True, editable=False)
|
|||
|
|
category = models.CharField("类别", max_length=20, choices=Category.choices)
|
|||
|
|
severity = models.CharField("等级", max_length=12, choices=Severity.choices)
|
|||
|
|
status = models.CharField("状态", max_length=12, choices=Status.choices, default=Status.OPEN, db_index=True)
|
|||
|
|
title = models.CharField("标题", max_length=200)
|
|||
|
|
summary = models.TextField("诊断说明")
|
|||
|
|
evidence = models.JSONField("证据", default=dict, blank=True)
|
|||
|
|
first_seen_at = models.DateTimeField("首次发现", auto_now_add=True)
|
|||
|
|
last_seen_at = models.DateTimeField("最近发现", auto_now=True)
|
|||
|
|
resolved_at = models.DateTimeField("恢复时间", null=True, blank=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "vpn-ai 诊断"
|
|||
|
|
verbose_name_plural = "vpn-ai 诊断"
|
|||
|
|
ordering = ["status", "-severity", "-last_seen_at"]
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return self.title
|
|||
|
|
|
|||
|
|
|
|||
|
|
class VpnAiRuntime(models.Model):
|
|||
|
|
service_name = models.CharField("服务名称", max_length=100, unique=True, default="vpn-ai")
|
|||
|
|
version = models.CharField("版本", max_length=30, default="0.2.0")
|
|||
|
|
worker_id = models.CharField("工作实例", max_length=100, blank=True)
|
|||
|
|
started_at = models.DateTimeField("启动时间", null=True, blank=True)
|
|||
|
|
last_heartbeat_at = models.DateTimeField("最近心跳", null=True, blank=True, db_index=True)
|
|||
|
|
last_cycle_at = models.DateTimeField("最近巡检", null=True, blank=True)
|
|||
|
|
cycle_count = models.PositiveBigIntegerField("巡检次数", default=0)
|
|||
|
|
observations_7d = models.PositiveIntegerField("近 7 天观测", default=0)
|
|||
|
|
active_rules = models.PositiveIntegerField("生效规则", default=0)
|
|||
|
|
open_findings = models.PositiveIntegerField("待处理诊断", default=0)
|
|||
|
|
last_error = models.TextField("最近错误", blank=True)
|
|||
|
|
dispatch_snapshot = models.JSONField("负载调度快照", default=dict, blank=True)
|
|||
|
|
updated_at = models.DateTimeField("更新时间", auto_now=True)
|
|||
|
|
|
|||
|
|
class Meta:
|
|||
|
|
verbose_name = "vpn-ai 控制台"
|
|||
|
|
verbose_name_plural = "vpn-ai 控制台"
|
|||
|
|
|
|||
|
|
def __str__(self):
|
|||
|
|
return self.service_name
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def is_healthy(self):
|
|||
|
|
return bool(self.last_heartbeat_at and self.last_heartbeat_at >= timezone.now() - timedelta(minutes=3))
|
|||
|
|
|
|||
|
|
|
|||
|
|
# Management-only team models are discovered by Django without coupling them
|
|||
|
|
# to the live per-person credential/provisioning path.
|
|||
|
|
from .team_models import Team, TeamMembership, TeamAuditEvent # noqa: E402,F401
|