928 lines
40 KiB
Python
928 lines
40 KiB
Python
|
|
import hashlib
|
||
|
|
import ipaddress
|
||
|
|
import json
|
||
|
|
import re
|
||
|
|
import secrets
|
||
|
|
import uuid
|
||
|
|
from datetime import timedelta
|
||
|
|
|
||
|
|
from django.conf import settings
|
||
|
|
from django.contrib import admin, messages
|
||
|
|
from django.contrib.admin.views.decorators import staff_member_required
|
||
|
|
from django.contrib.auth import authenticate, get_user_model, login
|
||
|
|
from django.contrib.auth.decorators import login_required
|
||
|
|
from django.core import signing
|
||
|
|
from django.core.exceptions import ValidationError
|
||
|
|
from django.db import connection, transaction
|
||
|
|
from django.db.models import F, Q, Sum
|
||
|
|
from django.http import Http404, HttpResponse, JsonResponse
|
||
|
|
from django.shortcuts import get_object_or_404, redirect, render
|
||
|
|
from django.utils import timezone
|
||
|
|
from django.views.decorators.http import require_http_methods
|
||
|
|
from django.views.decorators.cache import never_cache
|
||
|
|
from django.views.decorators.csrf import csrf_exempt
|
||
|
|
|
||
|
|
from accounts.forms import RegistrationForm
|
||
|
|
|
||
|
|
from .forms import PlanApplicationForm
|
||
|
|
from .git_releases import GitReleaseUnavailable, get_latest_windows_release
|
||
|
|
from .models import (
|
||
|
|
ClientSession,
|
||
|
|
Device,
|
||
|
|
Node,
|
||
|
|
NodeDeployment,
|
||
|
|
NodeReport,
|
||
|
|
NodeTrafficSample,
|
||
|
|
Plan,
|
||
|
|
PlanApplication,
|
||
|
|
RouteObservation,
|
||
|
|
Subscription,
|
||
|
|
UsageRecord,
|
||
|
|
HourlyUsageRecord,
|
||
|
|
)
|
||
|
|
from .usage_history import client_usage_history
|
||
|
|
from .usage_accounting import lock_usage_subscriptions, non_key_lock_options
|
||
|
|
from .lifecycle import personal_lifecycle
|
||
|
|
from .team_services import visible_teams
|
||
|
|
from .services import desired_subscriptions_for_node, render_mihomo, render_xray_client
|
||
|
|
from .tailscale_endpoint import client_tailscale_endpoint
|
||
|
|
|
||
|
|
|
||
|
|
@require_http_methods(["GET", "POST"])
|
||
|
|
def register(request):
|
||
|
|
if request.user.is_authenticated:
|
||
|
|
return redirect("portal-dashboard")
|
||
|
|
form = RegistrationForm(request.POST or None)
|
||
|
|
if request.method == "POST" and form.is_valid():
|
||
|
|
try:
|
||
|
|
user = form.save()
|
||
|
|
except ValidationError as exc:
|
||
|
|
form.add_error(None, exc)
|
||
|
|
else:
|
||
|
|
login(request, user)
|
||
|
|
if form.cleaned_data["plan"].online_payment_required and form.cleaned_data["plan"].price_for_user(user) > 0:
|
||
|
|
messages.success(request, "注册成功,套餐申请已登记。此套餐暂未开放付款,未扣款、未开通付费服务;内部员工请联系管理员核实身份。")
|
||
|
|
else:
|
||
|
|
messages.success(request, "注册成功,套餐申请已一并提交。免费套餐审核后自动开通;付费套餐须确认付款后审核。")
|
||
|
|
return redirect("portal-dashboard")
|
||
|
|
return render(request, "registration/register.html", {"form": form})
|
||
|
|
|
||
|
|
|
||
|
|
@never_cache
|
||
|
|
@login_required
|
||
|
|
def dashboard(request):
|
||
|
|
subscriptions = request.user.subscriptions.select_related("plan", "routing_policy").all()
|
||
|
|
subscription = subscriptions.exclude(status__in=[Subscription.Status.CANCELLED, Subscription.Status.EXPIRED]).first()
|
||
|
|
if not subscription:
|
||
|
|
subscription = subscriptions.first()
|
||
|
|
if subscription:
|
||
|
|
_enforce_subscription(subscription)
|
||
|
|
applications = list(request.user.plan_applications.select_related("plan").all()[:10])
|
||
|
|
plans = Plan.objects.filter(active=True)
|
||
|
|
if request.user.identity_type == "employee":
|
||
|
|
plans = plans.filter(audience__in=[Plan.Audience.EMPLOYEE, Plan.Audience.ALL])
|
||
|
|
else:
|
||
|
|
plans = plans.filter(audience__in=[Plan.Audience.EXTERNAL, Plan.Audience.ALL], employee_benefit=False)
|
||
|
|
return render(
|
||
|
|
request,
|
||
|
|
"portal/dashboard.html",
|
||
|
|
{
|
||
|
|
"subscription": subscription,
|
||
|
|
"applications": applications,
|
||
|
|
"lifecycle": personal_lifecycle(request.user, subscription, applications[0] if applications else None),
|
||
|
|
"user_teams": visible_teams(request.user),
|
||
|
|
"plans": plans,
|
||
|
|
"plan_cards": [{"plan": plan, "label": plan.application_label(request.user),
|
||
|
|
"payment_pending": plan.online_payment_required and plan.price_for_user(request.user) > 0}
|
||
|
|
for plan in plans],
|
||
|
|
},
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
@login_required
|
||
|
|
@require_http_methods(["GET", "POST"])
|
||
|
|
def apply_plan(request):
|
||
|
|
if request.user.plan_applications.filter(status=PlanApplication.Status.PENDING).exists():
|
||
|
|
messages.info(request, "您已有待处理申请,请等待管理员审核。")
|
||
|
|
return redirect("portal-dashboard")
|
||
|
|
current_subscription = (
|
||
|
|
request.user.subscriptions.filter(
|
||
|
|
status__in=[Subscription.Status.PENDING, Subscription.Status.ACTIVE, Subscription.Status.SUSPENDED]
|
||
|
|
)
|
||
|
|
.select_related("plan")
|
||
|
|
.first()
|
||
|
|
)
|
||
|
|
form = PlanApplicationForm(request.POST or None, user=request.user)
|
||
|
|
if request.method == "POST" and form.is_valid():
|
||
|
|
if current_subscription and form.cleaned_data["plan"].pk == current_subscription.plan_id:
|
||
|
|
messages.info(request, "您当前已经在使用该套餐,无需重复申请。")
|
||
|
|
return redirect("portal-dashboard")
|
||
|
|
try:
|
||
|
|
application = form.save()
|
||
|
|
except ValidationError as exc:
|
||
|
|
form.add_error(None, exc)
|
||
|
|
else:
|
||
|
|
if application.plan.online_payment_required and application.payment_status == PlanApplication.PaymentStatus.UNPAID:
|
||
|
|
messages.success(request, "套餐申请已登记。此套餐暂未开放付款,未扣款、未开通付费服务;原有订阅不变。")
|
||
|
|
elif application.payment_status == PlanApplication.PaymentStatus.UNPAID:
|
||
|
|
messages.success(request, "套餐申请已提交。管理员确认付款并审核后会自动更新订阅。")
|
||
|
|
else:
|
||
|
|
messages.success(request, "套餐申请已提交,管理员审核后会自动创建或更新订阅。")
|
||
|
|
return redirect("portal-dashboard")
|
||
|
|
return render(
|
||
|
|
request,
|
||
|
|
"portal/application_form.html",
|
||
|
|
{"form": form, "current_subscription": current_subscription},
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
def subscription_config(request, token):
|
||
|
|
try:
|
||
|
|
payload = signing.loads(token, salt="toplc-vpn-subscription")
|
||
|
|
subscription_id = int(payload["subscription_id"])
|
||
|
|
token_version = int(payload["version"])
|
||
|
|
except (signing.BadSignature, KeyError, TypeError, ValueError):
|
||
|
|
raise Http404("订阅地址无效")
|
||
|
|
|
||
|
|
subscription = get_object_or_404(
|
||
|
|
Subscription.objects.select_related("user", "plan", "routing_policy"),
|
||
|
|
pk=subscription_id,
|
||
|
|
)
|
||
|
|
if subscription.token_version != token_version:
|
||
|
|
raise Http404("订阅地址已失效")
|
||
|
|
_enforce_subscription(subscription)
|
||
|
|
if not subscription.is_usable:
|
||
|
|
return HttpResponse("订阅尚未启用、已暂停或已到期。\n", status=403, content_type="text/plain; charset=utf-8")
|
||
|
|
try:
|
||
|
|
body = render_mihomo(subscription)
|
||
|
|
except ValueError as exc:
|
||
|
|
return HttpResponse(f"{exc}\n", status=503, content_type="text/plain; charset=utf-8")
|
||
|
|
|
||
|
|
response = HttpResponse(body, content_type="text/yaml; charset=utf-8")
|
||
|
|
response["Content-Disposition"] = 'inline; filename="toplc-mihomo.yaml"'
|
||
|
|
response["Profile-Update-Interval"] = "24"
|
||
|
|
expire = int(subscription.expires_at.timestamp()) if subscription.expires_at else 0
|
||
|
|
response["Subscription-Userinfo"] = (
|
||
|
|
f"upload={subscription.upload_bytes}; download={subscription.download_bytes}; "
|
||
|
|
f"total={subscription.traffic_limit_bytes}; expire={expire}"
|
||
|
|
)
|
||
|
|
response["Cache-Control"] = "no-store"
|
||
|
|
return response
|
||
|
|
|
||
|
|
|
||
|
|
@login_required
|
||
|
|
def api_me(request):
|
||
|
|
subscription = request.user.subscriptions.exclude(
|
||
|
|
status__in=[Subscription.Status.CANCELLED, Subscription.Status.EXPIRED]
|
||
|
|
).first()
|
||
|
|
return JsonResponse(
|
||
|
|
{
|
||
|
|
"username": request.user.username,
|
||
|
|
"display_name": request.user.display_name,
|
||
|
|
"identity_type": request.user.identity_type,
|
||
|
|
"account_status": request.user.account_status,
|
||
|
|
"subscription": (
|
||
|
|
{
|
||
|
|
"status": subscription.status,
|
||
|
|
"plan": subscription.plan.name,
|
||
|
|
"used_bytes": subscription.used_bytes,
|
||
|
|
"traffic_limit_bytes": subscription.traffic_limit_bytes,
|
||
|
|
"expires_at": subscription.expires_at.isoformat() if subscription.expires_at else None,
|
||
|
|
}
|
||
|
|
if subscription
|
||
|
|
else None
|
||
|
|
),
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
@require_http_methods(["GET"])
|
||
|
|
def client_update(request):
|
||
|
|
platform = request.GET.get("platform", "windows").strip().lower()
|
||
|
|
if platform != "windows":
|
||
|
|
return JsonResponse({"error": "暂无该平台的更新。"}, status=404)
|
||
|
|
current = request.GET.get("current", "").strip()[:30]
|
||
|
|
try:
|
||
|
|
manifest = get_latest_windows_release()
|
||
|
|
except GitReleaseUnavailable:
|
||
|
|
response = JsonResponse({"error": "公司 Git 更新服务暂时不可用,请稍后重试。"}, status=503)
|
||
|
|
response["Cache-Control"] = "no-store"
|
||
|
|
return response
|
||
|
|
|
||
|
|
payload = {
|
||
|
|
"available": _newer_stable_release(manifest["version"], current),
|
||
|
|
"version": manifest["version"],
|
||
|
|
"download_url": manifest["download_url"],
|
||
|
|
"sha256": manifest["sha256"],
|
||
|
|
"size": manifest["size"],
|
||
|
|
"notes": manifest.get("notes", ""),
|
||
|
|
"mandatory": bool(manifest.get("mandatory", False)),
|
||
|
|
}
|
||
|
|
response = JsonResponse(payload)
|
||
|
|
response["Cache-Control"] = "no-store"
|
||
|
|
return response
|
||
|
|
|
||
|
|
|
||
|
|
@require_http_methods(["GET"])
|
||
|
|
def client_download_latest(request):
|
||
|
|
try:
|
||
|
|
manifest = get_latest_windows_release()
|
||
|
|
except GitReleaseUnavailable:
|
||
|
|
response = JsonResponse({"error": "请稍后从公司 Git 下载软件。"}, status=503)
|
||
|
|
response["Cache-Control"] = "no-store"
|
||
|
|
return response
|
||
|
|
# Backward-compatible URL only. The platform never opens/streams a local
|
||
|
|
# installer and never republishes release bytes.
|
||
|
|
response = redirect(manifest["download_url"])
|
||
|
|
response["Cache-Control"] = "no-store"
|
||
|
|
return response
|
||
|
|
|
||
|
|
|
||
|
|
def _version_tuple(value):
|
||
|
|
match = re.fullmatch(r"v?(\d{1,5})\.(\d{1,5})\.(\d{1,5})(?:[-+][A-Za-z0-9.-]+)?", str(value))
|
||
|
|
return tuple(map(int, match.groups())) if match else (0, 0, 0)
|
||
|
|
|
||
|
|
|
||
|
|
def _newer_stable_release(stable, current):
|
||
|
|
offered, installed = _version_tuple(stable), _version_tuple(current)
|
||
|
|
return offered > installed or (offered == installed and bool(re.match(r"^v?\d+\.\d+\.\d+-", str(current))))
|
||
|
|
|
||
|
|
|
||
|
|
@csrf_exempt
|
||
|
|
@require_http_methods(["POST"])
|
||
|
|
def client_login(request):
|
||
|
|
try:
|
||
|
|
if len(request.body) > 16 * 1024:
|
||
|
|
raise ValueError
|
||
|
|
payload = json.loads(request.body or b"{}")
|
||
|
|
login_id = str(payload["login"]).strip()
|
||
|
|
password = str(payload["password"])
|
||
|
|
device_id = str(payload["device_id"]).strip()
|
||
|
|
client_platform = str(payload.get("platform", "windows")).strip().lower()
|
||
|
|
if client_platform not in {"windows", "android", "ios"}:
|
||
|
|
raise ValueError
|
||
|
|
platform_label = {
|
||
|
|
"windows": "Windows",
|
||
|
|
"android": "Android",
|
||
|
|
"ios": "iPhone / iPad",
|
||
|
|
}[client_platform]
|
||
|
|
default_device_name = f"{platform_label} 设备"
|
||
|
|
device_name = str(payload.get("device_name", default_device_name)).strip()[:100] or default_device_name
|
||
|
|
app_version = str(payload.get("app_version", "")).strip()[:30]
|
||
|
|
if not 1 <= len(login_id) <= 254 or not 8 <= len(password) <= 512:
|
||
|
|
raise ValueError
|
||
|
|
if not 16 <= len(device_id) <= 128 or any(ch not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.:" for ch in device_id):
|
||
|
|
raise ValueError
|
||
|
|
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
||
|
|
return JsonResponse({"error": "请求参数无效。"}, status=400)
|
||
|
|
|
||
|
|
User = get_user_model()
|
||
|
|
user = User.objects.filter(Q(username__iexact=login_id) | Q(email__iexact=login_id)).first()
|
||
|
|
authenticated = authenticate(request, username=user.username, password=password) if user else None
|
||
|
|
if not authenticated:
|
||
|
|
return JsonResponse({"error": "用户名、邮箱或密码不正确。"}, status=401)
|
||
|
|
if not authenticated.service_enabled:
|
||
|
|
return JsonResponse({"error": "账号尚未开通或已被停用。"}, status=403)
|
||
|
|
|
||
|
|
subscription = (
|
||
|
|
authenticated.subscriptions.exclude(status__in=[Subscription.Status.CANCELLED, Subscription.Status.EXPIRED])
|
||
|
|
.select_related("plan", "user")
|
||
|
|
.first()
|
||
|
|
)
|
||
|
|
if not subscription:
|
||
|
|
return JsonResponse({"error": "账号没有可用订阅。"}, status=403)
|
||
|
|
_enforce_subscription(subscription)
|
||
|
|
subscription.refresh_from_db()
|
||
|
|
if not subscription.is_usable:
|
||
|
|
return JsonResponse({"error": subscription.state_reason or "订阅尚未生效、已暂停或已到期。"}, status=403)
|
||
|
|
|
||
|
|
now = timezone.now()
|
||
|
|
with transaction.atomic():
|
||
|
|
subscription = Subscription.objects.select_for_update().select_related("plan", "user").get(pk=subscription.pk)
|
||
|
|
device = Device.objects.select_for_update().filter(subscription=subscription, device_id=device_id).first()
|
||
|
|
if device and not device.active:
|
||
|
|
return JsonResponse({"error": "该设备已被管理员禁用。"}, status=403)
|
||
|
|
if not device:
|
||
|
|
active_devices = Device.objects.filter(subscription=subscription, active=True).count()
|
||
|
|
if active_devices >= subscription.device_limit:
|
||
|
|
return JsonResponse({"error": f"设备数量已达到套餐上限({subscription.device_limit} 台)。"}, status=403)
|
||
|
|
device = Device.objects.create(
|
||
|
|
subscription=subscription,
|
||
|
|
device_id=device_id,
|
||
|
|
name=device_name,
|
||
|
|
platform=f"{platform_label} · 优创⁺纵横家 {app_version}".strip(" ·"),
|
||
|
|
active=True,
|
||
|
|
last_seen_at=now,
|
||
|
|
)
|
||
|
|
else:
|
||
|
|
device.name = device_name
|
||
|
|
device.platform = f"{platform_label} · 优创⁺纵横家 {app_version}".strip(" ·")
|
||
|
|
device.last_seen_at = now
|
||
|
|
device.save(update_fields=["name", "platform", "last_seen_at"])
|
||
|
|
|
||
|
|
ClientSession.objects.filter(device=device, revoked_at__isnull=True).update(revoked_at=now)
|
||
|
|
session, token = ClientSession.issue(subscription, device, lifetime=timedelta(days=30))
|
||
|
|
|
||
|
|
response = JsonResponse(
|
||
|
|
{
|
||
|
|
"access_token": token,
|
||
|
|
"token_type": "Bearer",
|
||
|
|
"expires_at": session.expires_at.isoformat(),
|
||
|
|
"profile": _client_profile_payload(subscription),
|
||
|
|
}
|
||
|
|
)
|
||
|
|
response["Cache-Control"] = "no-store"
|
||
|
|
return response
|
||
|
|
|
||
|
|
|
||
|
|
@require_http_methods(["GET"])
|
||
|
|
def client_profile(request):
|
||
|
|
session, error_response = _authenticate_client_session(request)
|
||
|
|
if error_response:
|
||
|
|
return error_response
|
||
|
|
response = JsonResponse({"profile": _client_profile_payload(session.subscription)})
|
||
|
|
response["Cache-Control"] = "no-store"
|
||
|
|
return response
|
||
|
|
|
||
|
|
|
||
|
|
def _client_gateway_payload():
|
||
|
|
"""Return the stable public NPM entrypoint without exposing private overlay IPs."""
|
||
|
|
host = str(getattr(settings, "VPN_PUBLIC_GATEWAY_HOST", "vpn.toplc.cn") or "vpn.toplc.cn").strip()
|
||
|
|
configured_ipv4 = str(getattr(settings, "VPN_PUBLIC_GATEWAY_IPV4", "") or "").strip()
|
||
|
|
public_ipv4 = None
|
||
|
|
if configured_ipv4:
|
||
|
|
try:
|
||
|
|
address = ipaddress.ip_address(configured_ipv4)
|
||
|
|
if address.version == 4 and address.is_global:
|
||
|
|
public_ipv4 = configured_ipv4
|
||
|
|
except ValueError:
|
||
|
|
pass
|
||
|
|
return {"host": host, "ipv4": public_ipv4}
|
||
|
|
|
||
|
|
|
||
|
|
@require_http_methods(["GET"])
|
||
|
|
def client_config(request):
|
||
|
|
session, error_response = _authenticate_client_session(request)
|
||
|
|
if error_response:
|
||
|
|
return error_response
|
||
|
|
subscription = session.subscription
|
||
|
|
node_slug = request.GET.get("node", "").strip()
|
||
|
|
route_mode = request.GET.get("route", "smart").strip().lower()
|
||
|
|
nodes = subscription.nodes_for_subscription().filter(protocol=Node.Protocol.VLESS_REALITY)
|
||
|
|
dispatch = None
|
||
|
|
if node_slug == "auto":
|
||
|
|
from .dispatch import choose_node
|
||
|
|
node, dispatch = choose_node(session, request.GET.get("exclude", "")[:3000].split(","), request.GET.get("new_connection") == "1")
|
||
|
|
else:
|
||
|
|
node = nodes.filter(slug=node_slug).first() if node_slug else nodes.first()
|
||
|
|
if not node:
|
||
|
|
return JsonResponse({"error": "所选线路不可用。"}, status=404)
|
||
|
|
try:
|
||
|
|
config = render_xray_client(subscription, node, route_mode=route_mode)
|
||
|
|
except ValueError as exc:
|
||
|
|
return JsonResponse({"error": str(exc)}, status=400)
|
||
|
|
payload = {
|
||
|
|
"config_contract": 2,
|
||
|
|
"gateway": _client_gateway_payload(),
|
||
|
|
"node": {"slug": node.slug, "name": node.name, "region": node.region},
|
||
|
|
"route_mode": route_mode,
|
||
|
|
"config": config,
|
||
|
|
"dispatch": dispatch,
|
||
|
|
}
|
||
|
|
tailscale_endpoint = client_tailscale_endpoint(session, node)
|
||
|
|
if tailscale_endpoint is not None:
|
||
|
|
payload["tailscale_endpoint"] = tailscale_endpoint
|
||
|
|
response = JsonResponse(payload)
|
||
|
|
response["Cache-Control"] = "no-store"
|
||
|
|
return response
|
||
|
|
|
||
|
|
|
||
|
|
@csrf_exempt
|
||
|
|
@require_http_methods(["POST"])
|
||
|
|
def client_observations(request):
|
||
|
|
session, error_response = _authenticate_client_session(request)
|
||
|
|
if error_response:
|
||
|
|
return error_response
|
||
|
|
try:
|
||
|
|
if len(request.body) > 32 * 1024:
|
||
|
|
raise ValueError
|
||
|
|
payload = json.loads(request.body or b"{}")
|
||
|
|
observations = payload["observations"]
|
||
|
|
if not isinstance(observations, list) or not 1 <= len(observations) <= 20:
|
||
|
|
raise ValueError
|
||
|
|
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
||
|
|
return JsonResponse({"error": "观测数据格式无效。"}, status=400)
|
||
|
|
|
||
|
|
allowed_nodes = {
|
||
|
|
node.slug: node
|
||
|
|
for node in session.subscription.nodes_for_subscription().filter(protocol=Node.Protocol.VLESS_REALITY)
|
||
|
|
}
|
||
|
|
accepted = 0
|
||
|
|
try:
|
||
|
|
with transaction.atomic():
|
||
|
|
# Serialize this device's ingestion budget. No unbounded telemetry flood.
|
||
|
|
Device.objects.select_for_update().get(pk=session.device_id)
|
||
|
|
if RouteObservation.objects.filter(device=session.device,
|
||
|
|
received_at__gte=timezone.now() - timedelta(hours=1)).count() + len(observations) > 120:
|
||
|
|
response = JsonResponse({"error": "观测频率过高,请稍后重试。"}, status=429)
|
||
|
|
response["Retry-After"] = "60"
|
||
|
|
return response
|
||
|
|
for item in observations:
|
||
|
|
if not isinstance(item, dict):
|
||
|
|
raise ValueError
|
||
|
|
report_id = uuid.UUID(str(item["report_id"]))
|
||
|
|
target_type = str(item["target_type"]).strip().lower()
|
||
|
|
target = _normalize_observation_target(target_type, str(item["target"]))
|
||
|
|
port = int(item["port"])
|
||
|
|
access_kind = str(
|
||
|
|
item.get(
|
||
|
|
"access_kind",
|
||
|
|
RouteObservation.AccessKind.HTTP
|
||
|
|
if port in {80, 443}
|
||
|
|
else RouteObservation.AccessKind.SOCKET,
|
||
|
|
)
|
||
|
|
).strip().lower()
|
||
|
|
network = str(item["network"]).strip().lower()
|
||
|
|
outcome = str(item["outcome"]).strip().lower()
|
||
|
|
failure_kind = str(item.get("failure_kind", RouteObservation.FailureKind.OTHER)).strip().lower()
|
||
|
|
client_version = str(item.get("client_version", ""))[:30]
|
||
|
|
node_slug = str(item.get("node", "")).strip()
|
||
|
|
scope = str(item.get("scope", "public"))
|
||
|
|
evidence_kind = str(item.get("evidence_kind", ""))
|
||
|
|
related_id = uuid.UUID(str(item["related_report_id"])) if item.get("related_report_id") else None
|
||
|
|
if scope not in {"public", "private_auxiliary"} or evidence_kind not in {"", "tls"}:
|
||
|
|
raise ValueError
|
||
|
|
if not 1 <= port <= 65535:
|
||
|
|
raise ValueError
|
||
|
|
if access_kind not in RouteObservation.AccessKind.values:
|
||
|
|
raise ValueError
|
||
|
|
if network not in RouteObservation.Network.values:
|
||
|
|
raise ValueError
|
||
|
|
if outcome not in RouteObservation.Outcome.values:
|
||
|
|
raise ValueError
|
||
|
|
if failure_kind not in RouteObservation.FailureKind.values:
|
||
|
|
raise ValueError
|
||
|
|
node = allowed_nodes.get(node_slug) if node_slug else None
|
||
|
|
if scope == "private_auxiliary":
|
||
|
|
from .private_auxiliary import permitted
|
||
|
|
if not permitted(session.subscription):
|
||
|
|
raise ValueError
|
||
|
|
node = None # Private evidence cannot affect public node scores/rules.
|
||
|
|
elif node_slug and node is None:
|
||
|
|
raise ValueError
|
||
|
|
if evidence_kind == "tls":
|
||
|
|
if outcome != "proxy_succeeded" or network != "tcp" or port != 443 or node is None:
|
||
|
|
raise ValueError
|
||
|
|
pair = RouteObservation.objects.filter(report_id=related_id, device=session.device,
|
||
|
|
target_type=target_type, target=target, port=port, network=network, node=node,
|
||
|
|
scope="public", outcome="direct_failed",
|
||
|
|
received_at__gte=timezone.now() - timedelta(minutes=10)).first()
|
||
|
|
if pair is None:
|
||
|
|
raise ValueError
|
||
|
|
prior = RouteObservation.objects.filter(report_id=report_id).first()
|
||
|
|
if prior and prior.device_id != session.device_id:
|
||
|
|
raise ValueError
|
||
|
|
_, created = RouteObservation.objects.get_or_create(
|
||
|
|
report_id=report_id,
|
||
|
|
defaults={
|
||
|
|
"subscription": session.subscription,
|
||
|
|
"device": session.device,
|
||
|
|
"node": node,
|
||
|
|
"target_type": target_type,
|
||
|
|
"target": target,
|
||
|
|
"port": port,
|
||
|
|
"access_kind": access_kind,
|
||
|
|
"network": network,
|
||
|
|
"outcome": outcome,
|
||
|
|
"failure_kind": failure_kind,
|
||
|
|
"client_version": client_version,
|
||
|
|
"scope": scope,
|
||
|
|
"evidence_kind": evidence_kind,
|
||
|
|
"related_report_id": related_id,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
accepted += int(created)
|
||
|
|
except (KeyError, TypeError, ValueError):
|
||
|
|
return JsonResponse({"error": "观测数据内容无效。"}, status=400)
|
||
|
|
return JsonResponse({"status": "accepted", "accepted": accepted})
|
||
|
|
|
||
|
|
|
||
|
|
@csrf_exempt
|
||
|
|
@require_http_methods(["POST"])
|
||
|
|
def client_logout(request):
|
||
|
|
session, error_response = _authenticate_client_session(request, require_usable=False)
|
||
|
|
if error_response:
|
||
|
|
return error_response
|
||
|
|
session.revoked_at = timezone.now()
|
||
|
|
session.save(update_fields=["revoked_at"])
|
||
|
|
return JsonResponse({"status": "logged_out"})
|
||
|
|
|
||
|
|
|
||
|
|
def health(request):
|
||
|
|
try:
|
||
|
|
with connection.cursor() as cursor:
|
||
|
|
cursor.execute("SELECT 1")
|
||
|
|
cursor.fetchone()
|
||
|
|
except Exception:
|
||
|
|
return JsonResponse({"status": "unhealthy", "database": "down"}, status=503)
|
||
|
|
return JsonResponse({"status": "ok", "database": "ok"})
|
||
|
|
|
||
|
|
|
||
|
|
@staff_member_required
|
||
|
|
def node_traffic_dashboard(request):
|
||
|
|
context = admin.site.each_context(request)
|
||
|
|
context.update(
|
||
|
|
{
|
||
|
|
"title": "节点实时流量监控",
|
||
|
|
"node_count": Node.objects.filter(active=True).count(),
|
||
|
|
}
|
||
|
|
)
|
||
|
|
return render(request, "admin/node_traffic.html", context)
|
||
|
|
|
||
|
|
|
||
|
|
@staff_member_required
|
||
|
|
@require_http_methods(["GET"])
|
||
|
|
def node_traffic_data(request):
|
||
|
|
try:
|
||
|
|
range_minutes = int(request.GET.get("minutes", "60"))
|
||
|
|
except ValueError:
|
||
|
|
range_minutes = 60
|
||
|
|
if range_minutes not in {15, 60, 360, 1440}:
|
||
|
|
range_minutes = 60
|
||
|
|
|
||
|
|
now = timezone.now()
|
||
|
|
since = now - timedelta(minutes=range_minutes)
|
||
|
|
nodes = list(Node.objects.filter(active=True).order_by("sort_order", "region", "name"))
|
||
|
|
samples_by_node = {node.pk: [] for node in nodes}
|
||
|
|
samples = NodeTrafficSample.objects.filter(
|
||
|
|
node_id__in=samples_by_node,
|
||
|
|
sampled_at__gte=since,
|
||
|
|
).order_by("sampled_at")
|
||
|
|
for sample in samples.iterator():
|
||
|
|
samples_by_node[sample.node_id].append(sample)
|
||
|
|
|
||
|
|
online_after = now - timedelta(minutes=5)
|
||
|
|
payload_nodes = []
|
||
|
|
for node in nodes:
|
||
|
|
node_samples = samples_by_node[node.pk]
|
||
|
|
latest = node_samples[-1] if node_samples else None
|
||
|
|
payload_nodes.append(
|
||
|
|
{
|
||
|
|
"id": node.pk,
|
||
|
|
"slug": node.slug,
|
||
|
|
"name": node.name,
|
||
|
|
"region": node.region,
|
||
|
|
"status": node.status,
|
||
|
|
"online": bool(
|
||
|
|
node.status == Node.Status.ONLINE
|
||
|
|
and node.last_seen_at
|
||
|
|
and node.last_seen_at >= online_after
|
||
|
|
),
|
||
|
|
"last_seen_at": node.last_seen_at.isoformat() if node.last_seen_at else None,
|
||
|
|
"current_upload_bytes_per_second": latest.upload_bytes_per_second if latest else 0,
|
||
|
|
"current_download_bytes_per_second": latest.download_bytes_per_second if latest else 0,
|
||
|
|
"total_upload_bytes": node.total_upload_bytes,
|
||
|
|
"total_download_bytes": node.total_download_bytes,
|
||
|
|
"active_subscriptions": latest.active_subscriptions if latest else 0,
|
||
|
|
"samples": [
|
||
|
|
{
|
||
|
|
"at": sample.sampled_at.isoformat(),
|
||
|
|
"upload_bytes": sample.upload_bytes,
|
||
|
|
"download_bytes": sample.download_bytes,
|
||
|
|
"upload_bytes_per_second": sample.upload_bytes_per_second,
|
||
|
|
"download_bytes_per_second": sample.download_bytes_per_second,
|
||
|
|
}
|
||
|
|
for sample in node_samples
|
||
|
|
],
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
response = JsonResponse(
|
||
|
|
{
|
||
|
|
"generated_at": now.isoformat(),
|
||
|
|
"range_minutes": range_minutes,
|
||
|
|
"nodes": payload_nodes,
|
||
|
|
}
|
||
|
|
)
|
||
|
|
response["Cache-Control"] = "no-store"
|
||
|
|
return response
|
||
|
|
|
||
|
|
|
||
|
|
@csrf_exempt
|
||
|
|
@require_http_methods(["GET", "POST"])
|
||
|
|
def node_sync(request):
|
||
|
|
node = _authenticate_node(request)
|
||
|
|
if not node:
|
||
|
|
return JsonResponse({"error": "node authentication failed"}, status=401)
|
||
|
|
|
||
|
|
now = timezone.now()
|
||
|
|
Node.objects.filter(pk=node.pk).update(
|
||
|
|
last_seen_at=now,
|
||
|
|
status=Node.Status.ONLINE,
|
||
|
|
agent_version=request.headers.get("X-Agent-Version", "")[:64],
|
||
|
|
)
|
||
|
|
|
||
|
|
desired = list(desired_subscriptions_for_node(node))
|
||
|
|
if request.method == "GET":
|
||
|
|
NodeDeployment.objects.bulk_create(
|
||
|
|
[NodeDeployment(node=node, subscription=subscription) for subscription in desired],
|
||
|
|
ignore_conflicts=True,
|
||
|
|
)
|
||
|
|
return JsonResponse(
|
||
|
|
{
|
||
|
|
"node": node.slug,
|
||
|
|
"generated_at": now.isoformat(),
|
||
|
|
"clients": [
|
||
|
|
{
|
||
|
|
"subscription_id": subscription.pk,
|
||
|
|
"email": f"sub-{subscription.pk}",
|
||
|
|
"uuid": str(subscription.credential_uuid),
|
||
|
|
"flow": "xtls-rprx-vision",
|
||
|
|
}
|
||
|
|
for subscription in desired
|
||
|
|
],
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
try:
|
||
|
|
payload = json.loads(request.body or b"{}")
|
||
|
|
report_id = uuid.UUID(str(payload["report_id"]))
|
||
|
|
applied_ids = {int(value) for value in payload.get("applied_subscription_ids", [])}
|
||
|
|
success = bool(payload.get("success", True))
|
||
|
|
error = str(payload.get("error", ""))[:500]
|
||
|
|
usage = payload.get("usage", [])
|
||
|
|
if not isinstance(usage, list):
|
||
|
|
raise ValueError("usage must be a list")
|
||
|
|
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
||
|
|
return JsonResponse({"error": "invalid report payload"}, status=400)
|
||
|
|
|
||
|
|
desired_ids = {subscription.pk for subscription in desired}
|
||
|
|
|
||
|
|
normalized_usage = []
|
||
|
|
try:
|
||
|
|
for item in usage:
|
||
|
|
subscription_id = int(item["subscription_id"])
|
||
|
|
upload_bytes = int(item.get("upload_bytes", 0))
|
||
|
|
download_bytes = int(item.get("download_bytes", 0))
|
||
|
|
if min(upload_bytes, download_bytes) < 0:
|
||
|
|
raise ValueError
|
||
|
|
if upload_bytes > 10 * 1024**4 or download_bytes > 10 * 1024**4:
|
||
|
|
raise ValueError
|
||
|
|
normalized_usage.append((subscription_id, upload_bytes, download_bytes))
|
||
|
|
except (KeyError, TypeError, ValueError):
|
||
|
|
return JsonResponse({"error": "invalid usage item"}, status=400)
|
||
|
|
|
||
|
|
known_deployment_ids = set(
|
||
|
|
NodeDeployment.objects.filter(node=node).values_list("subscription_id", flat=True)
|
||
|
|
) | desired_ids
|
||
|
|
if not applied_ids.issubset(known_deployment_ids):
|
||
|
|
return JsonResponse({"error": "applied subscription is not associated with this node"}, status=400)
|
||
|
|
if any(subscription_id not in known_deployment_ids for subscription_id, _, _ in normalized_usage):
|
||
|
|
return JsonResponse({"error": "usage item is not associated with this node"}, status=400)
|
||
|
|
|
||
|
|
with transaction.atomic():
|
||
|
|
# Serialize first reports as well as existing deployment rows. Otherwise
|
||
|
|
# two first reports can both try to create the same NodeDeployment.
|
||
|
|
Node.objects.select_for_update(**non_key_lock_options()).get(pk=node.pk)
|
||
|
|
report, created = NodeReport.objects.get_or_create(node=node, report_id=report_id)
|
||
|
|
if not created:
|
||
|
|
return JsonResponse({"status": "already_processed"})
|
||
|
|
|
||
|
|
lock_usage_subscriptions(known_deployment_ids | desired_ids)
|
||
|
|
|
||
|
|
deployments = {
|
||
|
|
deployment.subscription_id: deployment
|
||
|
|
for deployment in NodeDeployment.objects.select_for_update().filter(node=node)
|
||
|
|
}
|
||
|
|
touched_subscription_ids = set(deployments)
|
||
|
|
for subscription in desired:
|
||
|
|
deployment = deployments.get(subscription.pk)
|
||
|
|
if not deployment:
|
||
|
|
deployment = NodeDeployment(node=node, subscription=subscription)
|
||
|
|
deployments[subscription.pk] = deployment
|
||
|
|
touched_subscription_ids.add(subscription.pk)
|
||
|
|
|
||
|
|
if success:
|
||
|
|
for subscription_id, deployment in deployments.items():
|
||
|
|
should_be_deployed = subscription_id in applied_ids
|
||
|
|
if should_be_deployed:
|
||
|
|
deployment.deployed = True
|
||
|
|
deployment.applied_at = now
|
||
|
|
deployment.revoked_at = None
|
||
|
|
elif deployment.deployed:
|
||
|
|
deployment.deployed = False
|
||
|
|
deployment.revoked_at = now
|
||
|
|
deployment.last_error = ""
|
||
|
|
deployment.save()
|
||
|
|
else:
|
||
|
|
for subscription_id in desired_ids:
|
||
|
|
deployment = deployments[subscription_id]
|
||
|
|
deployment.last_error = error or "节点应用配置失败"
|
||
|
|
deployment.save(update_fields=["last_error", "updated_at"])
|
||
|
|
|
||
|
|
affected_usage_ids = set()
|
||
|
|
total_upload = 0
|
||
|
|
total_download = 0
|
||
|
|
for subscription_id, upload_bytes, download_bytes in normalized_usage:
|
||
|
|
record, _ = UsageRecord.objects.select_for_update().get_or_create(
|
||
|
|
subscription_id=subscription_id,
|
||
|
|
node=node,
|
||
|
|
day=timezone.localdate(),
|
||
|
|
)
|
||
|
|
record.upload_bytes += upload_bytes
|
||
|
|
record.download_bytes += download_bytes
|
||
|
|
record.save(update_fields=["upload_bytes", "download_bytes", "updated_at"])
|
||
|
|
# Same idempotent transaction as the daily ledger. Never rebill these
|
||
|
|
# rows; delayed deltas belong to their receipt hour, not guessed times.
|
||
|
|
hourly, _ = HourlyUsageRecord.objects.select_for_update().get_or_create(
|
||
|
|
subscription_id=subscription_id, node=node,
|
||
|
|
hour=now.replace(minute=0, second=0, microsecond=0),
|
||
|
|
)
|
||
|
|
hourly.upload_bytes += upload_bytes
|
||
|
|
hourly.download_bytes += download_bytes
|
||
|
|
hourly.save(update_fields=["upload_bytes", "download_bytes"])
|
||
|
|
affected_usage_ids.add(subscription_id)
|
||
|
|
total_upload += upload_bytes
|
||
|
|
total_download += download_bytes
|
||
|
|
|
||
|
|
if total_upload or total_download:
|
||
|
|
Node.objects.filter(pk=node.pk).update(
|
||
|
|
total_upload_bytes=F("total_upload_bytes") + total_upload,
|
||
|
|
total_download_bytes=F("total_download_bytes") + total_download,
|
||
|
|
)
|
||
|
|
|
||
|
|
previous_sample = (
|
||
|
|
NodeTrafficSample.objects.filter(node=node)
|
||
|
|
.order_by("-sampled_at")
|
||
|
|
.only("sampled_at")
|
||
|
|
.first()
|
||
|
|
)
|
||
|
|
interval_seconds = 60
|
||
|
|
if previous_sample:
|
||
|
|
interval_seconds = max(1, min(3600, round((now - previous_sample.sampled_at).total_seconds())))
|
||
|
|
NodeTrafficSample.objects.create(
|
||
|
|
node=node,
|
||
|
|
report=report,
|
||
|
|
interval_seconds=interval_seconds,
|
||
|
|
upload_bytes=total_upload,
|
||
|
|
download_bytes=total_download,
|
||
|
|
upload_bytes_per_second=total_upload // interval_seconds,
|
||
|
|
download_bytes_per_second=total_download // interval_seconds,
|
||
|
|
active_subscriptions=len(applied_ids),
|
||
|
|
)
|
||
|
|
|
||
|
|
for subscription in Subscription.objects.select_for_update().filter(pk__in=touched_subscription_ids):
|
||
|
|
has_deployment = subscription.node_deployments.filter(deployed=True).exists()
|
||
|
|
if subscription.status == Subscription.Status.ACTIVE:
|
||
|
|
state = (
|
||
|
|
Subscription.ProvisioningState.ACTIVE
|
||
|
|
if has_deployment
|
||
|
|
else Subscription.ProvisioningState.FAILED if not success else Subscription.ProvisioningState.PENDING
|
||
|
|
)
|
||
|
|
reason = "" if has_deployment else error
|
||
|
|
Subscription.objects.filter(pk=subscription.pk).update(
|
||
|
|
provisioning_state=state,
|
||
|
|
state_reason=reason,
|
||
|
|
)
|
||
|
|
elif subscription.provisioning_state == Subscription.ProvisioningState.REVOKE_PENDING and not has_deployment:
|
||
|
|
Subscription.objects.filter(pk=subscription.pk).update(
|
||
|
|
provisioning_state=Subscription.ProvisioningState.REVOKED
|
||
|
|
)
|
||
|
|
|
||
|
|
return JsonResponse({"status": "accepted", "usage_items": len(normalized_usage)})
|
||
|
|
|
||
|
|
|
||
|
|
def _authenticate_node(request):
|
||
|
|
slug = request.headers.get("X-Node-Slug", "").strip()
|
||
|
|
authorization = request.headers.get("Authorization", "")
|
||
|
|
if not authorization.startswith("Bearer "):
|
||
|
|
return None
|
||
|
|
token = authorization[7:].strip()
|
||
|
|
try:
|
||
|
|
node = Node.objects.get(slug=slug, active=True)
|
||
|
|
except Node.DoesNotExist:
|
||
|
|
return None
|
||
|
|
return node if node.check_agent_token(token) else None
|
||
|
|
|
||
|
|
|
||
|
|
def _authenticate_client_session(request, require_usable=True):
|
||
|
|
authorization = request.headers.get("Authorization", "")
|
||
|
|
if not authorization.startswith("Bearer "):
|
||
|
|
return None, JsonResponse({"error": "缺少客户端访问令牌。"}, status=401)
|
||
|
|
token = authorization[7:].strip()
|
||
|
|
if not 32 <= len(token) <= 256:
|
||
|
|
return None, JsonResponse({"error": "客户端访问令牌无效。"}, status=401)
|
||
|
|
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||
|
|
session = (
|
||
|
|
ClientSession.objects.select_related("device", "subscription__user", "subscription__plan")
|
||
|
|
.filter(token_digest=digest, revoked_at__isnull=True)
|
||
|
|
.first()
|
||
|
|
)
|
||
|
|
if not session or not secrets.compare_digest(session.token_digest, digest) or not session.is_valid:
|
||
|
|
return None, JsonResponse({"error": "登录已失效,请重新登录。"}, status=401)
|
||
|
|
if not session.device.active:
|
||
|
|
return None, JsonResponse({"error": "该设备已被管理员禁用。"}, status=403)
|
||
|
|
if require_usable:
|
||
|
|
_enforce_subscription(session.subscription)
|
||
|
|
session.subscription.refresh_from_db()
|
||
|
|
if not session.subscription.is_usable:
|
||
|
|
return None, JsonResponse(
|
||
|
|
{"error": session.subscription.state_reason or "订阅不可用。"},
|
||
|
|
status=403,
|
||
|
|
)
|
||
|
|
now = timezone.now()
|
||
|
|
ClientSession.objects.filter(pk=session.pk).update(last_seen_at=now)
|
||
|
|
Device.objects.filter(pk=session.device_id).update(last_seen_at=now)
|
||
|
|
session.last_seen_at = now
|
||
|
|
session.device.last_seen_at = now
|
||
|
|
return session, None
|
||
|
|
|
||
|
|
|
||
|
|
def _client_profile_payload(subscription):
|
||
|
|
from .private_auxiliary import profile_grants
|
||
|
|
nodes = subscription.nodes_for_subscription().filter(protocol=Node.Protocol.VLESS_REALITY)
|
||
|
|
history, ranges = client_usage_history(subscription)
|
||
|
|
return {
|
||
|
|
"username": subscription.user.username,
|
||
|
|
"display_name": subscription.user.display_name,
|
||
|
|
"email": subscription.user.email,
|
||
|
|
"identity_type": subscription.user.identity_type,
|
||
|
|
"dispatch_mode": "vpn-ai",
|
||
|
|
"private_auxiliary_nodes": profile_grants(subscription),
|
||
|
|
"usage_history": history,
|
||
|
|
"usage_history_ranges": ranges,
|
||
|
|
"subscription": {
|
||
|
|
"status": subscription.status,
|
||
|
|
"plan": subscription.plan.name,
|
||
|
|
"used_bytes": subscription.used_bytes,
|
||
|
|
"traffic_limit_bytes": subscription.traffic_limit_bytes,
|
||
|
|
"expires_at": subscription.expires_at.isoformat() if subscription.expires_at else None,
|
||
|
|
"device_limit": subscription.device_limit,
|
||
|
|
},
|
||
|
|
"nodes": [
|
||
|
|
{
|
||
|
|
"slug": node.slug,
|
||
|
|
"name": node.name,
|
||
|
|
"region": node.region,
|
||
|
|
"status": node.status,
|
||
|
|
}
|
||
|
|
for node in nodes
|
||
|
|
],
|
||
|
|
"route_modes": [
|
||
|
|
{"id": "smart", "name": "AI 智能代理"},
|
||
|
|
{"id": "global", "name": "全局代理"},
|
||
|
|
{"id": "direct", "name": "仅直连"},
|
||
|
|
],
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def _normalize_observation_target(target_type, target):
|
||
|
|
target = target.strip().rstrip(".").lower()
|
||
|
|
if target_type == RouteObservation.TargetType.IP:
|
||
|
|
address = ipaddress.ip_address(target)
|
||
|
|
if not address.is_global:
|
||
|
|
raise ValueError
|
||
|
|
return address.compressed
|
||
|
|
if target_type != RouteObservation.TargetType.DOMAIN:
|
||
|
|
raise ValueError
|
||
|
|
try:
|
||
|
|
ipaddress.ip_address(target)
|
||
|
|
except ValueError:
|
||
|
|
pass
|
||
|
|
else:
|
||
|
|
raise ValueError # Cannot disguise a private IP as a domain.
|
||
|
|
try:
|
||
|
|
target = target.encode("idna").decode("ascii")
|
||
|
|
except UnicodeError as exc:
|
||
|
|
raise ValueError from exc
|
||
|
|
if not 1 <= len(target) <= 253 or "." not in target:
|
||
|
|
raise ValueError
|
||
|
|
protected_domains = {"toplc.cn", "ucvl.cn", "ucvl.net", "localhost"}
|
||
|
|
if target in protected_domains or target.endswith((".local", ".toplc.cn", ".ucvl.cn", ".ucvl.net",
|
||
|
|
".localhost", ".lan", ".internal", ".home", ".invalid", ".test", ".example", ".arpa", ".onion")):
|
||
|
|
raise ValueError
|
||
|
|
if any(
|
||
|
|
not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label)
|
||
|
|
for label in target.split(".")
|
||
|
|
):
|
||
|
|
raise ValueError
|
||
|
|
return target
|
||
|
|
|
||
|
|
|
||
|
|
def _enforce_subscription(subscription):
|
||
|
|
now = timezone.now()
|
||
|
|
update_fields = []
|
||
|
|
if subscription.status == Subscription.Status.ACTIVE:
|
||
|
|
if subscription.expires_at and subscription.expires_at <= now:
|
||
|
|
subscription.status = Subscription.Status.EXPIRED
|
||
|
|
subscription.state_reason = "套餐已到期"
|
||
|
|
subscription.provisioning_state = Subscription.ProvisioningState.REVOKE_PENDING
|
||
|
|
update_fields.extend(["status", "state_reason", "provisioning_state"])
|
||
|
|
elif subscription.traffic_limit_bytes and subscription.used_bytes >= subscription.traffic_limit_bytes:
|
||
|
|
subscription.status = Subscription.Status.SUSPENDED
|
||
|
|
subscription.state_reason = "流量额度已用完"
|
||
|
|
subscription.provisioning_state = Subscription.ProvisioningState.REVOKE_PENDING
|
||
|
|
update_fields.extend(["status", "state_reason", "provisioning_state"])
|
||
|
|
if update_fields:
|
||
|
|
subscription.save(update_fields=[*update_fields, "updated_at"])
|