Compare commits
10 Commits
0bedd1c4d1
...
8937044f55
| Author | SHA1 | Date | |
|---|---|---|---|
| 8937044f55 | |||
| 76126f7a0c | |||
| be27529054 | |||
| daaed39bac | |||
| 837bf55f6a | |||
| 038e5b6ab5 | |||
| a274cc40c8 | |||
| fc8c03f2c3 | |||
| b461a476a2 | |||
| e023fb6579 |
@@ -45,8 +45,20 @@ abstract class AppText {
|
||||
String get quotaToday;
|
||||
String get minutes;
|
||||
String get quotaFree;
|
||||
String get planFreeTag; // 额度卡右上短标签「免费版」(不含「每日10分钟」,避免挤占行宽)
|
||||
String get watchAd;
|
||||
String get adUnlocked;
|
||||
// 免费版 10 分钟卡控 + 看广告加时(累加式)
|
||||
String get quotaLeftLabel; // 连接期倒计时前缀「剩余」
|
||||
String get quotaUsedUp; // 额度卡:今日已用完
|
||||
String get watchAdMore; // 「看广告加时」CTA
|
||||
String get quotaExhaustedNotice; // 倒计时归零自动切断提示
|
||||
String get adPlaying; // 占位广告:播放中
|
||||
String adRewarded(int minutes); // 占位广告:已加 N 分钟
|
||||
String get adFailed; // 看广告加时失败
|
||||
String get quotaDesktopTitle; // 桌面版额度耗尽弹窗标题
|
||||
String get quotaDesktopBody; // 桌面版额度耗尽弹窗正文
|
||||
String get gotIt; // 知道了
|
||||
|
||||
// ── 节点页 ──
|
||||
String get chooseNode;
|
||||
@@ -59,6 +71,7 @@ abstract class AppText {
|
||||
// 连通看门狗:当前节点数据面不可用时的提示
|
||||
String get nodeUnhealthySwitched; // 智能选择已自动切换
|
||||
String get nodeUnhealthyError; // 手动节点:断开并提示
|
||||
String get nodeReconnecting; // 弱网抖动:自动重连当前节点中(#18)
|
||||
String get smartSub;
|
||||
String get recommended;
|
||||
|
||||
|
||||
@@ -53,9 +53,31 @@ class StringsEn extends AppText {
|
||||
@override
|
||||
String get quotaFree => 'Free · 10 min/day';
|
||||
@override
|
||||
String get planFreeTag => 'Free';
|
||||
@override
|
||||
String get watchAd => 'Watch ad to start';
|
||||
@override
|
||||
String get adUnlocked => 'Unlocked for today';
|
||||
@override
|
||||
String get quotaLeftLabel => 'Left';
|
||||
@override
|
||||
String get quotaUsedUp => 'Daily free time used up';
|
||||
@override
|
||||
String get watchAdMore => 'Watch ad for more time';
|
||||
@override
|
||||
String get quotaExhaustedNotice => 'Daily free time used up. Watch an ad to add time or upgrade.';
|
||||
@override
|
||||
String get adPlaying => 'Ad playing…';
|
||||
@override
|
||||
String adRewarded(int minutes) => '+$minutes min added';
|
||||
@override
|
||||
String get adFailed => 'Failed to add time, please retry';
|
||||
@override
|
||||
String get quotaDesktopTitle => 'Daily free time used up';
|
||||
@override
|
||||
String get quotaDesktopBody => 'Watch ads in the mobile app to add time, or upgrade for unlimited access.';
|
||||
@override
|
||||
String get gotIt => 'Got it';
|
||||
|
||||
@override
|
||||
String get chooseNode => 'Choose server';
|
||||
@@ -74,6 +96,8 @@ class StringsEn extends AppText {
|
||||
@override
|
||||
String get nodeUnhealthyError => 'Current node is unreachable — reconnect or switch node';
|
||||
@override
|
||||
String get nodeReconnecting => 'Network unstable, reconnecting…';
|
||||
@override
|
||||
String get smartSub => 'Picks the best node for your network';
|
||||
@override
|
||||
String get recommended => 'Recommended';
|
||||
|
||||
@@ -52,9 +52,31 @@ class StringsZh extends AppText {
|
||||
@override
|
||||
String get quotaFree => '免费版 · 每日 10 分钟';
|
||||
@override
|
||||
String get planFreeTag => '免费版';
|
||||
@override
|
||||
String get watchAd => '看广告开始使用';
|
||||
@override
|
||||
String get adUnlocked => '已解锁 · 今日可用';
|
||||
@override
|
||||
String get quotaLeftLabel => '剩余';
|
||||
@override
|
||||
String get quotaUsedUp => '今日免费时长已用完';
|
||||
@override
|
||||
String get watchAdMore => '看广告加时';
|
||||
@override
|
||||
String get quotaExhaustedNotice => '今日免费时长已用完,看广告加时或升级会员';
|
||||
@override
|
||||
String get adPlaying => '广告播放中…';
|
||||
@override
|
||||
String adRewarded(int minutes) => '已加 $minutes 分钟';
|
||||
@override
|
||||
String get adFailed => '加时失败,请重试';
|
||||
@override
|
||||
String get quotaDesktopTitle => '今日免费时长已用完';
|
||||
@override
|
||||
String get quotaDesktopBody => '前往移动端 App 看广告加时,或升级会员畅享无限时长。';
|
||||
@override
|
||||
String get gotIt => '知道了';
|
||||
|
||||
@override
|
||||
String get chooseNode => '选择节点';
|
||||
@@ -73,6 +95,8 @@ class StringsZh extends AppText {
|
||||
@override
|
||||
String get nodeUnhealthyError => '当前节点异常,请重连或更换节点';
|
||||
@override
|
||||
String get nodeReconnecting => '网络波动,正在重连…';
|
||||
@override
|
||||
String get smartSub => '根据当前网络环境,自动选择最优节点';
|
||||
@override
|
||||
String get recommended => '推荐';
|
||||
|
||||
@@ -12,6 +12,7 @@ class Me {
|
||||
this.devicesUsed = 0,
|
||||
this.devicesMax = 1,
|
||||
this.quotaTodayMin,
|
||||
this.quotaCapMin,
|
||||
this.dataTodayGb = 0,
|
||||
this.weeklyGb = const [],
|
||||
this.totpEnabled = false,
|
||||
@@ -29,9 +30,13 @@ class Me {
|
||||
final int devicesMax;
|
||||
|
||||
/// 今日**剩余**额度(分钟);null = 不限(pro/team)。
|
||||
/// 后端已算好 = 套餐每日上限 − 今日已用。
|
||||
/// 后端已算好 = 当日额度 − 今日已用(账户共享,非每设备)。
|
||||
final int? quotaTodayMin;
|
||||
|
||||
/// 今日**总额度**(分钟)= 套餐每日上限 + 看广告累加分钟;null = 不限。
|
||||
/// 供进度条分母使用(剩余 / 总额度)。
|
||||
final int? quotaCapMin;
|
||||
|
||||
/// 今日已用流量(GB)。
|
||||
final double dataTodayGb;
|
||||
|
||||
@@ -51,6 +56,7 @@ class Me {
|
||||
devicesUsed: (m['devices_used'] as num?)?.toInt() ?? 0,
|
||||
devicesMax: (m['devices_max'] as num?)?.toInt() ?? 1,
|
||||
quotaTodayMin: (m['quota_today_min'] as num?)?.toInt(),
|
||||
quotaCapMin: (m['quota_cap_min'] as num?)?.toInt(),
|
||||
dataTodayGb: (m['data_today_gb'] as num?)?.toDouble() ?? 0,
|
||||
weeklyGb: ((m['weekly_gb'] as List<dynamic>?) ?? const [])
|
||||
.map((e) => (e as num).toDouble())
|
||||
|
||||
@@ -11,6 +11,7 @@ import '../state/app_providers.dart';
|
||||
import '../state/connection_provider.dart';
|
||||
import '../state/nodes_provider.dart';
|
||||
import '../state/quota_provider.dart';
|
||||
import '../widgets/ad_reward_dialog.dart';
|
||||
import '../widgets/app_top_bar.dart';
|
||||
import '../widgets/connect_button.dart';
|
||||
import '../widgets/country_code.dart';
|
||||
@@ -52,11 +53,18 @@ class ConnectPage extends ConsumerWidget {
|
||||
VpnPhase.on => t.capOn,
|
||||
};
|
||||
|
||||
// 免费额度耗尽:off 态连接键灰化不可点,点击弹加时(移动看广告 / 桌面升级)。
|
||||
final isDesktop = context.formFactor == FormFactor.desktop;
|
||||
final connectEnabled = !(isFree && quota.isExhausted && conn.phase == VpnPhase.off);
|
||||
void onQuotaBlockedTap() => showQuotaAdFlow(context, ref, isDesktop: isDesktop);
|
||||
|
||||
final button = ConnectButton(
|
||||
phase: conn.phase,
|
||||
elapsed: conn.elapsed,
|
||||
offLabel: t.connectNow,
|
||||
secureLabel: t.secure,
|
||||
enabled: connectEnabled,
|
||||
onDisabledTap: onQuotaBlockedTap,
|
||||
onTap: () => ref.read(connectionProvider.notifier).toggle(),
|
||||
);
|
||||
|
||||
@@ -75,7 +83,13 @@ class ConnectPage extends ConsumerWidget {
|
||||
|
||||
final infoChildren = <Widget>[
|
||||
if (isFree)
|
||||
QuotaCard(quota: quota, t: t, onWatchAd: () => ref.read(quotaProvider.notifier).watchAd()),
|
||||
QuotaCard(
|
||||
quota: quota,
|
||||
t: t,
|
||||
countdown: conn.freeCountdown,
|
||||
isDesktop: isDesktop,
|
||||
onWatchAd: onQuotaBlockedTap,
|
||||
),
|
||||
if (conn.phase == VpnPhase.on) _SpeedRow(t: t, down: down, up: up, latency: latencyValue),
|
||||
_CurrentNodeCard(t: t, node: node, smart: smart, pingLabel: pingLabel, showLabel: isWide, onTap: onOpenNodes),
|
||||
];
|
||||
@@ -100,6 +114,8 @@ class ConnectPage extends ConsumerWidget {
|
||||
offLabel: t.connectNow,
|
||||
secureLabel: t.secure,
|
||||
size: 176,
|
||||
enabled: connectEnabled,
|
||||
onDisabledTap: onQuotaBlockedTap,
|
||||
onTap: () => ref.read(connectionProvider.notifier).toggle(),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
@@ -120,7 +136,13 @@ class ConnectPage extends ConsumerWidget {
|
||||
const SizedBox(height: 24),
|
||||
SizedBox(
|
||||
width: 340,
|
||||
child: QuotaCard(quota: quota, t: t, onWatchAd: () => ref.read(quotaProvider.notifier).watchAd()),
|
||||
child: QuotaCard(
|
||||
quota: quota,
|
||||
t: t,
|
||||
countdown: conn.freeCountdown,
|
||||
isDesktop: isDesktop,
|
||||
onWatchAd: onQuotaBlockedTap,
|
||||
),
|
||||
),
|
||||
],
|
||||
if (conn.phase == VpnPhase.on) ...[
|
||||
|
||||
@@ -99,7 +99,23 @@ class AccountApi {
|
||||
Future<RedeemResult> redeem(String code) async =>
|
||||
RedeemResult.fromJson(await _c.postJson('/v1/redeem', {'code': code}));
|
||||
|
||||
/// POST /v1/ads/unlock — 看广告解锁今日免费额度。
|
||||
Future<void> adUnlock({required String deviceId, required String adToken}) =>
|
||||
_c.postJson('/v1/ads/unlock', {'device_id': deviceId, 'ad_token': adToken});
|
||||
/// POST /v1/ads/unlock — 看广告加时(累加式)。返回本次加时分钟与最新剩余分钟。
|
||||
Future<AdUnlockResult> adUnlock({required String deviceId, required String adToken}) async {
|
||||
final body = await _c.postJson('/v1/ads/unlock', {'device_id': deviceId, 'ad_token': adToken});
|
||||
return AdUnlockResult(
|
||||
grantedMinutes: (body['granted_minutes'] as num?)?.toInt() ?? 0,
|
||||
minutesRemaining: (body['minutes_remaining'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 看广告加时结果(POST /v1/ads/unlock 响应)。
|
||||
class AdUnlockResult {
|
||||
const AdUnlockResult({required this.grantedMinutes, required this.minutesRemaining});
|
||||
|
||||
/// 本次广告实际加时分钟(已达每日封顶时为 0)。
|
||||
final int grantedMinutes;
|
||||
|
||||
/// 加时后账户当日剩余分钟(全账户共享)。
|
||||
final int minutesRemaining;
|
||||
}
|
||||
|
||||
@@ -40,11 +40,19 @@ class MeNotifier extends AsyncNotifier<Me> {
|
||||
return ref.read(accountApiProvider).me();
|
||||
}
|
||||
|
||||
/// 手动刷新(如连接/兑换后)。
|
||||
/// 手动刷新(如兑换后 / 下拉刷新)。会短暂进 loading 态(触发整页转圈)。
|
||||
Future<void> refresh() async {
|
||||
state = const AsyncLoading();
|
||||
state = await AsyncValue.guard(() => ref.read(accountApiProvider).me());
|
||||
}
|
||||
|
||||
/// 静默刷新:不进 loading 态、成功才替换。供连接期/断开后刷新「今日剩余」用,
|
||||
/// 避免 refresh() 的 AsyncLoading 让连接页整页闪 spinner(meLoadingProvider)。
|
||||
Future<void> silentRefresh() async {
|
||||
if (!ref.read(authProvider).isLoggedIn) return;
|
||||
final next = await AsyncValue.guard(() => ref.read(accountApiProvider).me());
|
||||
if (next is AsyncData<Me>) state = next;
|
||||
}
|
||||
}
|
||||
|
||||
final meProvider = AsyncNotifierProvider<MeNotifier, Me>(MeNotifier.new);
|
||||
|
||||
@@ -19,9 +19,11 @@ import '../services/api_config.dart';
|
||||
import '../services/auth_api.dart';
|
||||
import '../services/connect_api.dart';
|
||||
import '../services/device_identity.dart';
|
||||
import 'account_providers.dart';
|
||||
import 'app_providers.dart';
|
||||
import 'auth_provider.dart';
|
||||
import 'nodes_provider.dart';
|
||||
import 'quota_provider.dart';
|
||||
import 'settings_provider.dart';
|
||||
|
||||
// 设备 ID 由 deviceIdentityProvider 提供(secure storage 持久化的稳定 UUID)。
|
||||
@@ -35,7 +37,12 @@ enum VpnPhase { off, connecting, on }
|
||||
// ── 连接状态快照 ──────────────────────────────────────────────────
|
||||
|
||||
class ConnectionState {
|
||||
const ConnectionState({required this.phase, this.elapsed = Duration.zero, this.error});
|
||||
const ConnectionState({
|
||||
required this.phase,
|
||||
this.elapsed = Duration.zero,
|
||||
this.error,
|
||||
this.freeCountdown,
|
||||
});
|
||||
|
||||
final VpnPhase phase;
|
||||
final Duration elapsed;
|
||||
@@ -43,18 +50,27 @@ class ConnectionState {
|
||||
/// 连接失败/中断原因(已本地化);null = 无错误。供 UI 提示,不再静默吞掉。
|
||||
final String? error;
|
||||
|
||||
ConnectionState copyWith({VpnPhase? phase, Duration? elapsed}) =>
|
||||
ConnectionState(phase: phase ?? this.phase, elapsed: elapsed ?? this.elapsed);
|
||||
/// 免费版连接期剩余额度(倒计时);null = 不适用(会员/未连接/额度不限)。
|
||||
/// 由状态机按「连接时锁定的剩余额度 − 已用时长」本地推算,归零即自动切断。
|
||||
final Duration? freeCountdown;
|
||||
|
||||
ConnectionState copyWith({VpnPhase? phase, Duration? elapsed, Duration? freeCountdown}) =>
|
||||
ConnectionState(
|
||||
phase: phase ?? this.phase,
|
||||
elapsed: elapsed ?? this.elapsed,
|
||||
freeCountdown: freeCountdown ?? this.freeCountdown,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is ConnectionState &&
|
||||
other.phase == phase &&
|
||||
other.elapsed == elapsed &&
|
||||
other.error == error;
|
||||
other.error == error &&
|
||||
other.freeCountdown == freeCountdown;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(phase, elapsed, error);
|
||||
int get hashCode => Object.hash(phase, elapsed, error, freeCountdown);
|
||||
}
|
||||
|
||||
// ── 连通看门狗 ─────────────────────────────────────────────────────
|
||||
@@ -76,6 +92,8 @@ const _kUrltestStale = Duration(seconds: 45);
|
||||
// stats 帧在此时长内到过即视为「在流」。超过(app 挂起/唤醒未恢复)时看门狗路径 A 不判活,
|
||||
// 避免把 app 被挂起的空档错算成节点死。须 > 原生 stats 轮询间隔(~1s),留足余量。
|
||||
const _kStatsLive = Duration(seconds: 10);
|
||||
// 无备用节点时,弱网抖动判「节点异常」先自动重连当前节点的最大次数;超过才真报错。#18
|
||||
const _kMaxAutoReconnect = 3;
|
||||
|
||||
// ── 状态机 ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -140,6 +158,12 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
ConnectApi? _api;
|
||||
// 实际所连节点(连接时锁定):看门狗探测/判活针对它,而非会随 ping 漂移的 effectiveNode。
|
||||
Node? _connectedNode;
|
||||
// 无备用节点时「先自动重连当前节点」的连续尝试计数;连接恢复健康(urltest 成功)或
|
||||
// 用户主动连接时清零,只有持续失败才耗尽额度后真报「节点异常」。#18
|
||||
int _autoReconnectAttempts = 0;
|
||||
// 免费版:连接时锁定的剩余额度(秒);连接期按「_freeRemainingSec − 已用秒」倒计时,
|
||||
// 归零即自动切断(_onFreeQuotaExhausted)。null = 会员/额度不限,不倒计时。
|
||||
int? _freeRemainingSec;
|
||||
|
||||
// ── 公有 API ───────────────────────────────────────────────────
|
||||
|
||||
@@ -147,6 +171,7 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
void toggle() {
|
||||
switch (state.phase) {
|
||||
case VpnPhase.off:
|
||||
_autoReconnectAttempts = 0; // 用户主动连接:重置弱网自动重连额度(#18)
|
||||
_connect();
|
||||
case VpnPhase.on:
|
||||
_userDisconnect = true; // 用户主动断开:其 kernel off 不当作节点异常
|
||||
@@ -170,6 +195,10 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
_userDisconnect = false;
|
||||
_lastUrltestOk = null; // 重置 urltest 判活基准(连上后由 _onStats 首次成功置位)
|
||||
_lastStatsAt = null; // 重置 stats 在流基准(连上后由 _onStats 首帧置位)
|
||||
// 免费版:锁定本次连接可用的剩余额度(账户共享,权威取自 me)。会员为 null 不倒计时。
|
||||
_freeRemainingSec = _ref.read(isFreePlanProvider)
|
||||
? _ref.read(quotaProvider).remainingMinutes * 60
|
||||
: null;
|
||||
state = const ConnectionState(phase: VpnPhase.connecting);
|
||||
|
||||
final node = _ref.read(effectiveNodeProvider);
|
||||
@@ -202,6 +231,12 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
if (mounted) state = const ConnectionState(phase: VpnPhase.off);
|
||||
return;
|
||||
}
|
||||
// 免费额度已用完(服务端兜底):本地置耗尽 → 按钮灰化、点击弹广告/升级。回 off。
|
||||
if (e.code == 'QUOTA_EXHAUSTED') {
|
||||
_ref.read(quotaProvider.notifier).markExhausted();
|
||||
if (mounted) state = ConnectionState(phase: VpnPhase.off, error: zh ? e.messageZh : e.messageEn);
|
||||
return;
|
||||
}
|
||||
// 把后端/网络错误冒泡到 UI(原静默回 off,用户不知所以)。
|
||||
if (mounted) state = ConnectionState(phase: VpnPhase.off, error: zh ? e.messageZh : e.messageEn);
|
||||
} catch (e) {
|
||||
@@ -250,12 +285,26 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
} catch (_) {}
|
||||
// 携带 _offNotice(节点异常/null);与 kernel off 读同一字段,不互相覆盖。
|
||||
if (mounted) state = ConnectionState(phase: VpnPhase.off, error: _offNotice);
|
||||
_refreshQuota(); // 会话结束 → 刷新「今日剩余」反映本次消耗
|
||||
}
|
||||
|
||||
// 静默刷新 /me(不闪整页 spinner),让免费额度「今日剩余」跨会话/跨设备更新。
|
||||
void _refreshQuota() {
|
||||
if (_ref.read(authProvider).isLoggedIn && _ref.read(isFreePlanProvider)) {
|
||||
unawaited(_ref.read(meProvider.notifier).silentRefresh());
|
||||
}
|
||||
}
|
||||
|
||||
void _onKernelStatus(VpnStatus s) {
|
||||
if (!mounted) return;
|
||||
switch (s) {
|
||||
case VpnStatus.on:
|
||||
// 免费版:若本次「on」不是经 _connect 而来(如 Android 常驻隧道、app 重启后
|
||||
// 自动同步到已在跑的隧道),_freeRemainingSec 还是 null → 倒计时不启。这里兜底
|
||||
// 按当前额度补锁定,保证连接页显示的是倒计时(会变)而非静态「今日剩余」。
|
||||
if (_freeRemainingSec == null && _ref.read(isFreePlanProvider)) {
|
||||
_freeRemainingSec = _ref.read(quotaProvider).remainingMinutes * 60;
|
||||
}
|
||||
state = state.copyWith(phase: VpnPhase.on);
|
||||
_startElapsed();
|
||||
_startWatchdog();
|
||||
@@ -269,15 +318,20 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
// 必须排除 connecting 握手期的瞬态 off——macOS NE 连接序列是 off→connecting→off→
|
||||
// connecting→on,connecting 期的 off 是握手抖动、不是异常(否则一连接就误报「节点异常」)。
|
||||
final wasConnected = state.phase == VpnPhase.on;
|
||||
_stopElapsed();
|
||||
_stopWatchdog();
|
||||
if (!_userDisconnect && wasConnected && _offNotice == null) {
|
||||
_offNotice = _ref.read(appTextProvider).nodeUnhealthyError;
|
||||
// 意外掉线(非用户主动、曾连上;弱网抖动最常见的就是这条 kernel off)。先自动重连
|
||||
// **当前节点**(不换节点——弱网是本地网络问题,换节点无益还会来回横跳),重试用尽才
|
||||
// 报「节点异常」。(wasConnected 闸:重连握手期再掉线时 phase 已非 on,不自我循环触发。)#18
|
||||
logLine('Watchdog', 'unexpected kernel ${s.name} after connected → node interrupted');
|
||||
unawaited(_ref.read(nodesProvider.notifier).refresh());
|
||||
_userDisconnect = false;
|
||||
unawaited(_handleUnexpectedOff());
|
||||
return;
|
||||
}
|
||||
state = ConnectionState(phase: VpnPhase.off, error: _offNotice);
|
||||
_userDisconnect = false;
|
||||
_stopElapsed();
|
||||
_stopWatchdog();
|
||||
_refreshQuota(); // 内核掉线也算会话结束 → 刷新「今日剩余」
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,6 +354,7 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
if (ds.isEmpty) return;
|
||||
// urltest 成功:经 proxy 出站(REALITY 到节点)真实可达 → 记录时刻(供路径 A 判活)+ 回写延迟。
|
||||
_lastUrltestOk = now;
|
||||
_autoReconnectAttempts = 0; // 节点已恢复健康 → 清零自动重连计数,下次抖动重获满额重试。#18
|
||||
final best = ds.reduce((a, b) => a < b ? a : b);
|
||||
_ref.read(nodesProvider.notifier).setLivePing(node.uuid, best);
|
||||
}
|
||||
@@ -370,12 +425,38 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 手动选定节点(或智能模式无其他可用节点):断开并提示,尊重用户选择、不自动换。
|
||||
// 提示走 _offNotice,由 _disconnect/_onKernelStatus 应用,避免被 kernel off 覆盖。
|
||||
// 无备用节点(手动选定节点 / 智能但无其他可用):弱网抖动别一判死就断开+要用户手动重连。
|
||||
// 先自动重连**当前节点**,连续失败超过上限再真报「节点异常」。#18
|
||||
if (await _tryAutoReconnectCurrent()) return;
|
||||
// 重试用尽:断开并提示「节点异常」。提示走 _offNotice,由 _disconnect/_onKernelStatus 应用。
|
||||
_offNotice = t.nodeUnhealthyError;
|
||||
await _disconnect();
|
||||
}
|
||||
|
||||
/// 弱网抖动:自动重连**当前节点**(不换节点、不改 selectedNode),bounded。
|
||||
/// 返回 true = 已发起重连(额度内);false = 已用尽额度,调用方应改报「节点异常」。#18
|
||||
/// urltest 成功(_onStats)或用户主动连接(toggle)会把计数清零 → 只有持续失败才耗尽。
|
||||
Future<bool> _tryAutoReconnectCurrent() async {
|
||||
if (_autoReconnectAttempts >= _kMaxAutoReconnect) return false;
|
||||
_autoReconnectAttempts++;
|
||||
final Node node = _connectedNode ?? _ref.read(effectiveNodeProvider);
|
||||
logLine('Watchdog', 'auto-reconnect current node ${node.code} (attempt $_autoReconnectAttempts/$_kMaxAutoReconnect)');
|
||||
await _disconnect();
|
||||
await _connect();
|
||||
// 重连握手中给「网络波动,正在重连…」瞬态提示(连上后随 copyWith 清除)。
|
||||
if (mounted && state.phase != VpnPhase.off) {
|
||||
state = ConnectionState(phase: state.phase, error: _ref.read(appTextProvider).nodeReconnecting);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// 意外内核掉线(弱网)的处理:先自动重连当前节点,额度用尽才断开并报「节点异常」。#18
|
||||
Future<void> _handleUnexpectedOff() async {
|
||||
if (await _tryAutoReconnectCurrent()) return;
|
||||
_offNotice = _ref.read(appTextProvider).nodeUnhealthyError;
|
||||
await _disconnect();
|
||||
}
|
||||
|
||||
/// 选延迟最优、可用(status up)、非当前节点的 code;无则 null。
|
||||
String? _pickAlternativeCode(String excludeCode) {
|
||||
final nodes = (_ref.read(nodesProvider).valueOrNull ?? const [])
|
||||
@@ -397,18 +478,41 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
_elapsed = Timer.periodic(const Duration(seconds: 1), (_) => _refreshElapsed());
|
||||
}
|
||||
|
||||
/// 按墙上时钟把 elapsed 刷成 now - _connectedAt(切后台回来也准)。
|
||||
/// 按墙上时钟把 elapsed 刷成 now - _connectedAt(切后台回来也准);免费版顺带推算
|
||||
/// 倒计时,归零即自动切断。倒计时用墙上时钟,后台/锁屏漏跳也会在回前台补上、准时切。
|
||||
void _refreshElapsed() {
|
||||
final at = _connectedAt;
|
||||
if (mounted && state.phase == VpnPhase.on && at != null) {
|
||||
state = state.copyWith(elapsed: _now().difference(at));
|
||||
if (!mounted || state.phase != VpnPhase.on || at == null) return;
|
||||
final elapsed = _now().difference(at);
|
||||
|
||||
Duration? countdown;
|
||||
final capSec = _freeRemainingSec;
|
||||
if (capSec != null) {
|
||||
final leftSec = capSec - elapsed.inSeconds;
|
||||
if (leftSec <= 0) {
|
||||
unawaited(_onFreeQuotaExhausted());
|
||||
return;
|
||||
}
|
||||
countdown = Duration(seconds: leftSec);
|
||||
}
|
||||
state = ConnectionState(phase: VpnPhase.on, elapsed: elapsed, freeCountdown: countdown);
|
||||
}
|
||||
|
||||
/// 免费额度耗尽:主动切断隧道(不报节点异常),本地置耗尽让按钮灰化,并拉 me 校准。
|
||||
Future<void> _onFreeQuotaExhausted() async {
|
||||
_freeRemainingSec = null;
|
||||
_userDisconnect = true; // 视为主动断开,不触发「节点异常」
|
||||
_offNotice = _ref.read(appTextProvider).quotaExhaustedNotice;
|
||||
_ref.read(quotaProvider.notifier).markExhausted();
|
||||
logLine('Quota', 'free daily minutes used up → auto disconnect');
|
||||
await _disconnect();
|
||||
}
|
||||
|
||||
void _stopElapsed() {
|
||||
_elapsed?.cancel();
|
||||
_elapsed = null;
|
||||
_connectedAt = null;
|
||||
_freeRemainingSec = null;
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
// quota_provider.dart — 免费版每日额度状态(Riverpod)
|
||||
//
|
||||
// 设计约定(design/CLAUDE.md §7 / §2):免费额度权威在服务端。
|
||||
// 总额度取自 plans 的 free.daily_minutes,今日剩余取自 me.quota_today_min
|
||||
// (后端已算好 = 上限 − 今日已用)。adUnlocked 为本地会话态(看广告需 ad SDK,
|
||||
// 尚未接入,保留本地乐观置位)。
|
||||
// 设计约定(design/CLAUDE.md §7 / §2):免费额度权威在服务端,且**全账户共享**
|
||||
// (非每设备)。总额度取自 me.quota_cap_min(= 套餐每日上限 + 看广告累加分钟),
|
||||
// 今日剩余取自 me.quota_today_min(后端已算好 = 额度 − 今日已用)。
|
||||
//
|
||||
// 看广告加时(累加式):watchAd() 调 /v1/ads/unlock,服务端校验后 +N 分钟并回传最新
|
||||
// 剩余,客户端随即刷新 me 让额度权威同步。占位广告 SDK 阶段用客户端生成的 ad_token,
|
||||
// 服务端 DevVerifier 放行(nonce 仍防重放)。
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../services/device_identity.dart';
|
||||
import 'account_providers.dart';
|
||||
|
||||
/// 免费额度快照。
|
||||
@@ -13,18 +18,14 @@ class FreeQuotaState {
|
||||
const FreeQuotaState({
|
||||
this.totalMinutes = 10,
|
||||
this.remainingMinutes = 10,
|
||||
this.adUnlocked = false,
|
||||
});
|
||||
|
||||
/// 每日总额度(分钟)。§7:免费版每日 10 分钟。
|
||||
/// 今日总额度(分钟)= 套餐每日上限 + 看广告累加。§7:免费版基础每日 10 分钟。
|
||||
final int totalMinutes;
|
||||
|
||||
/// 今日剩余分钟(展示值,权威以服务端为准)。
|
||||
/// 今日剩余分钟(权威以服务端为准;连接期倒计时由连接状态机本地推算)。
|
||||
final int remainingMinutes;
|
||||
|
||||
/// 今日是否已观看激励视频解锁。
|
||||
final bool adUnlocked;
|
||||
|
||||
/// 进度(0–1),用于进度条宽度。
|
||||
double get progress =>
|
||||
totalMinutes == 0 ? 0 : (remainingMinutes / totalMinutes).clamp(0.0, 1.0);
|
||||
@@ -32,11 +33,12 @@ class FreeQuotaState {
|
||||
/// 是否进入低额度警示(≤3 分钟切 warning 色)。
|
||||
bool get isLow => remainingMinutes <= 3;
|
||||
|
||||
FreeQuotaState copyWith({int? totalMinutes, int? remainingMinutes, bool? adUnlocked}) =>
|
||||
FreeQuotaState(
|
||||
/// 今日额度是否已耗尽(剩余 0):连接按钮据此灰化,点击弹广告/升级。
|
||||
bool get isExhausted => remainingMinutes <= 0;
|
||||
|
||||
FreeQuotaState copyWith({int? totalMinutes, int? remainingMinutes}) => FreeQuotaState(
|
||||
totalMinutes: totalMinutes ?? this.totalMinutes,
|
||||
remainingMinutes: remainingMinutes ?? this.remainingMinutes,
|
||||
adUnlocked: adUnlocked ?? this.adUnlocked,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -53,18 +55,41 @@ class QuotaController extends StateNotifier<FreeQuotaState> {
|
||||
void _sync() {
|
||||
final me = _ref.read(meProvider).valueOrNull;
|
||||
final plans = _ref.read(plansProvider).valueOrNull;
|
||||
var total = 10; // §7 默认免费 10 分钟,plans 就绪后以其为准
|
||||
var base = 10; // §7 默认免费基础 10 分钟,plans 就绪后以其为准
|
||||
if (plans != null) {
|
||||
for (final p in plans) {
|
||||
if (p.code == 'free' && p.dailyMinutes != null) total = p.dailyMinutes!;
|
||||
if (p.code == 'free' && p.dailyMinutes != null) base = p.dailyMinutes!;
|
||||
}
|
||||
}
|
||||
// 总额度优先取服务端 quota_cap_min(含看广告加时);缺省回退基础额度。
|
||||
final total = me?.quotaCapMin ?? base;
|
||||
final remaining = (me?.quotaTodayMin ?? total).clamp(0, total);
|
||||
state = state.copyWith(totalMinutes: total, remainingMinutes: remaining);
|
||||
state = FreeQuotaState(totalMinutes: total, remainingMinutes: remaining);
|
||||
}
|
||||
|
||||
/// 观看激励视频后解锁今日使用(本地乐观;真实 ad 校验待 ad SDK 接入)。
|
||||
void watchAd() => state = state.copyWith(adUnlocked: true);
|
||||
/// 连接期倒计时归零 → 本地立即置耗尽(按钮随即灰化);登录态下再静默拉 me 让服务端权威同步。
|
||||
void markExhausted() {
|
||||
state = state.copyWith(remainingMinutes: 0);
|
||||
_ref.read(meProvider.notifier).silentRefresh();
|
||||
}
|
||||
|
||||
/// 看广告加时:调 /v1/ads/unlock 累加分钟,成功后刷新 me 拿最新额度。
|
||||
/// 返回本次加时分钟(null = 失败)。占位阶段用客户端生成的 ad_token。
|
||||
Future<int?> watchAd() async {
|
||||
try {
|
||||
final deviceId = await _ref.read(deviceIdentityProvider).deviceId();
|
||||
final res = await _ref.read(accountApiProvider).adUnlock(
|
||||
deviceId: deviceId,
|
||||
adToken: const Uuid().v4(), // 占位 ad_token(DevVerifier 放行)
|
||||
);
|
||||
// 乐观置位剩余,再静默拉 me 校准(账户共享,以服务端为准;不闪整页 spinner)。
|
||||
state = state.copyWith(remainingMinutes: res.minutesRemaining);
|
||||
await _ref.read(meProvider.notifier).silentRefresh();
|
||||
return res.grantedMinutes;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final quotaProvider = StateNotifierProvider<QuotaController, FreeQuotaState>(
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
// ad_reward_dialog.dart — 免费额度耗尽后的「加时」入口(占位广告流程 + 桌面升级提示)
|
||||
//
|
||||
// 移动端:弹占位广告(「广告播放中…」→ 3s 假播放 → 调 /v1/ads/unlock 加时 → 显示奖励)。
|
||||
// 桌面端(Windows/macOS):免费版硬 10 分钟/天不可延,无广告——弹「去移动端看广告或升级」。
|
||||
// 接真广告 SDK(AdMob 激励视频)时,只需把 onWatch 换成「真播完再回调」即可,UI 不变。
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../l10n/app_text.dart';
|
||||
import '../pangolin_theme.dart';
|
||||
import '../state/app_providers.dart';
|
||||
import '../state/quota_provider.dart';
|
||||
import 'pangolin_icons.dart';
|
||||
|
||||
/// 展示加时流程。isDesktop=true 走升级提示(无广告),否则走占位广告加时。
|
||||
Future<void> showQuotaAdFlow(BuildContext context, WidgetRef ref, {required bool isDesktop}) async {
|
||||
final t = ref.read(appTextProvider);
|
||||
if (isDesktop) {
|
||||
await showDialog<void>(context: context, builder: (_) => _DesktopUpgradeDialog(t: t));
|
||||
return;
|
||||
}
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => _PlaceholderAdDialog(
|
||||
t: t,
|
||||
onWatch: () => ref.read(quotaProvider.notifier).watchAd(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 桌面版:免费硬 10 分钟不可延,提示去移动端加时或升级会员。
|
||||
class _DesktopUpgradeDialog extends StatelessWidget {
|
||||
const _DesktopUpgradeDialog({required this.t});
|
||||
final AppText t;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final c = context.pangolin;
|
||||
return AlertDialog(
|
||||
backgroundColor: c.surface,
|
||||
title: Text(t.quotaDesktopTitle,
|
||||
style: PangolinText.body.copyWith(color: c.fg1, fontWeight: FontWeight.w700)),
|
||||
content: Text(t.quotaDesktopBody, style: PangolinText.sm.copyWith(color: c.fg2)),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(t.gotIt, style: PangolinText.sm.copyWith(color: c.accent, fontWeight: FontWeight.w700)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum _AdPhase { playing, done, failed }
|
||||
|
||||
/// 移动端占位激励广告:播放中 → 加时成功/失败。成功后短暂展示奖励再自动关闭。
|
||||
class _PlaceholderAdDialog extends StatefulWidget {
|
||||
const _PlaceholderAdDialog({required this.t, required this.onWatch});
|
||||
final AppText t;
|
||||
final Future<int?> Function() onWatch;
|
||||
|
||||
@override
|
||||
State<_PlaceholderAdDialog> createState() => _PlaceholderAdDialogState();
|
||||
}
|
||||
|
||||
class _PlaceholderAdDialogState extends State<_PlaceholderAdDialog> {
|
||||
_AdPhase _phase = _AdPhase.playing;
|
||||
int _granted = 0;
|
||||
Timer? _closeTimer;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_run();
|
||||
}
|
||||
|
||||
Future<void> _run() async {
|
||||
// 占位「播放」3s(接真 SDK 后由激励视频完成回调替代)。
|
||||
await Future<void>.delayed(const Duration(seconds: 3));
|
||||
if (!mounted) return;
|
||||
final granted = await widget.onWatch();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
if (granted != null && granted > 0) {
|
||||
_phase = _AdPhase.done;
|
||||
_granted = granted;
|
||||
} else {
|
||||
_phase = _AdPhase.failed;
|
||||
}
|
||||
});
|
||||
if (_phase == _AdPhase.done) {
|
||||
_closeTimer = Timer(const Duration(milliseconds: 1300), () {
|
||||
if (mounted) Navigator.of(context).pop();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_closeTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final c = context.pangolin;
|
||||
final t = widget.t;
|
||||
|
||||
Widget body;
|
||||
switch (_phase) {
|
||||
case _AdPhase.playing:
|
||||
body = Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
SizedBox(
|
||||
width: 34,
|
||||
height: 34,
|
||||
child: CircularProgressIndicator(color: c.accent, strokeWidth: 3),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(t.adPlaying, style: PangolinText.sm.copyWith(color: c.fg2, fontWeight: FontWeight.w600)),
|
||||
]);
|
||||
case _AdPhase.done:
|
||||
body = Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
Icon(PangolinIcons.checkCircle, size: 40, color: c.success),
|
||||
const SizedBox(height: 14),
|
||||
Text(t.adRewarded(_granted),
|
||||
style: PangolinText.body.copyWith(color: c.success, fontWeight: FontWeight.w700)),
|
||||
]);
|
||||
case _AdPhase.failed:
|
||||
body = Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
Icon(PangolinIcons.alertTriangle, size: 36, color: c.danger),
|
||||
const SizedBox(height: 14),
|
||||
Text(t.adFailed, style: PangolinText.sm.copyWith(color: c.fg2, fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 14),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(t.gotIt, style: PangolinText.sm.copyWith(color: c.accent, fontWeight: FontWeight.w700)),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
return Dialog(
|
||||
backgroundColor: c.surface,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(PangolinRadius.lg)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 28),
|
||||
child: AnimatedSize(
|
||||
duration: PangolinMotion.base,
|
||||
child: body,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,11 +24,19 @@ class ConnectButton extends StatefulWidget {
|
||||
required this.secureLabel,
|
||||
this.elapsed = Duration.zero,
|
||||
this.size = 208,
|
||||
this.enabled = true,
|
||||
this.onDisabledTap,
|
||||
});
|
||||
|
||||
final VpnPhase phase;
|
||||
final VoidCallback onTap;
|
||||
|
||||
/// 是否可点。免费额度耗尽时置 false → 灰化不可连,点击走 onDisabledTap。
|
||||
final bool enabled;
|
||||
|
||||
/// 灰化态被点击的回调(如弹看广告加时/升级)。enabled=false 时生效。
|
||||
final VoidCallback? onDisabledTap;
|
||||
|
||||
/// off 态圆内文字(如「点击连接」/「CONNECT」)。
|
||||
final String offLabel;
|
||||
|
||||
@@ -55,18 +63,26 @@ class _ConnectButtonState extends State<ConnectButton> with SingleTickerProvider
|
||||
Widget build(BuildContext context) {
|
||||
final c = context.pangolin;
|
||||
final s = widget.phase;
|
||||
// 免费额度耗尽:off 态灰化不可连(锁图标 + 柔和阴影),点击走 onDisabledTap。
|
||||
final disabled = !widget.enabled && s == VpnPhase.off;
|
||||
|
||||
final Color fill = switch (s) {
|
||||
VpnPhase.off => c.bgSubtle,
|
||||
VpnPhase.connecting => c.accent,
|
||||
VpnPhase.on => c.success,
|
||||
};
|
||||
final Color fg = s == VpnPhase.off ? c.accent : PangolinColors.white;
|
||||
final IconData icon = switch (s) {
|
||||
VpnPhase.off => PangolinIcons.power,
|
||||
VpnPhase.connecting => PangolinIcons.loader,
|
||||
VpnPhase.on => PangolinIcons.shieldCheck,
|
||||
};
|
||||
final Color fill = disabled
|
||||
? c.bgSubtle
|
||||
: switch (s) {
|
||||
VpnPhase.off => c.bgSubtle,
|
||||
VpnPhase.connecting => c.accent,
|
||||
VpnPhase.on => c.success,
|
||||
};
|
||||
final Color fg = disabled
|
||||
? c.fg3
|
||||
: (s == VpnPhase.off ? c.accent : PangolinColors.white);
|
||||
final IconData icon = disabled
|
||||
? PangolinIcons.lock
|
||||
: switch (s) {
|
||||
VpnPhase.off => PangolinIcons.power,
|
||||
VpnPhase.connecting => PangolinIcons.loader,
|
||||
VpnPhase.on => PangolinIcons.shieldCheck,
|
||||
};
|
||||
|
||||
// off 用柔和阴影;connecting/on 增加同色光晕环(box-shadow,不动背景计算)。
|
||||
final List<BoxShadow> glow = s == VpnPhase.off
|
||||
@@ -84,7 +100,7 @@ class _ConnectButtonState extends State<ConnectButton> with SingleTickerProvider
|
||||
button: true,
|
||||
label: widget.offLabel,
|
||||
child: GestureDetector(
|
||||
onTap: widget.onTap,
|
||||
onTap: disabled ? widget.onDisabledTap : widget.onTap,
|
||||
child: AnimatedContainer(
|
||||
duration: PangolinMotion.slow,
|
||||
curve: PangolinMotion.easeOut,
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
// quota_card.dart — 免费版每日额度卡(纯展示)
|
||||
// quota_card.dart — 免费版每日额度卡
|
||||
//
|
||||
// 今日剩余分钟 + 进度条(≤3 分钟切 warning 色)+「看广告开始使用」;
|
||||
// 解锁后变绿「已解锁 · 今日可用」。状态由 quota_provider 注入,本地仅展示。
|
||||
// 三态展示(额度全账户共享):
|
||||
// ① 连接中(countdown != null):显示剩余倒计时 mm:ss + 进度条随之收缩。
|
||||
// ② 未连接·有余额:显示今日剩余分钟 + 进度条;移动端附「看广告加时」。
|
||||
// ③ 未连接·已耗尽:显示「今日已用完」+ 移动端「看广告加时」/ 桌面「升级会员」。
|
||||
// 状态由 quota_provider(剩余)+ connection_provider(倒计时)注入,本地仅展示。
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../l10n/app_text.dart';
|
||||
@@ -10,16 +13,55 @@ import '../state/quota_provider.dart';
|
||||
import 'pangolin_icons.dart';
|
||||
|
||||
class QuotaCard extends StatelessWidget {
|
||||
const QuotaCard({super.key, required this.quota, required this.t, required this.onWatchAd});
|
||||
const QuotaCard({
|
||||
super.key,
|
||||
required this.quota,
|
||||
required this.t,
|
||||
required this.onWatchAd,
|
||||
this.countdown,
|
||||
this.isDesktop = false,
|
||||
});
|
||||
|
||||
final FreeQuotaState quota;
|
||||
final AppText t;
|
||||
|
||||
/// 额度耗尽时的加时入口(移动端占位广告 / 桌面升级提示)。
|
||||
final VoidCallback onWatchAd;
|
||||
|
||||
/// 连接期剩余倒计时;null = 未连接(展示今日剩余分钟)。
|
||||
final Duration? countdown;
|
||||
|
||||
/// 桌面端(Windows/macOS):免费硬 10 分钟不可延,不显示看广告按钮。
|
||||
final bool isDesktop;
|
||||
|
||||
static String _mmss(Duration d) {
|
||||
final m = d.inMinutes.remainder(60).toString().padLeft(2, '0');
|
||||
final s = d.inSeconds.remainder(60).toString().padLeft(2, '0');
|
||||
return '$m:$s';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final c = context.pangolin;
|
||||
final barColor = quota.isLow ? c.warning : c.accent;
|
||||
final connected = countdown != null;
|
||||
final exhausted = quota.isExhausted && !connected;
|
||||
|
||||
// 进度与主值:连接期用倒计时,未连接用剩余分钟。
|
||||
final double progress;
|
||||
final String label;
|
||||
final String value;
|
||||
if (connected) {
|
||||
final totalSec = quota.totalMinutes * 60;
|
||||
progress = totalSec == 0 ? 0 : (countdown!.inSeconds / totalSec).clamp(0.0, 1.0);
|
||||
label = t.quotaLeftLabel;
|
||||
value = _mmss(countdown!);
|
||||
} else {
|
||||
progress = quota.progress;
|
||||
label = exhausted ? t.quotaUsedUp : t.quotaToday;
|
||||
value = exhausted ? '' : '${quota.remainingMinutes} ${t.minutes}';
|
||||
}
|
||||
final low = connected ? countdown!.inMinutes < 3 : quota.isLow;
|
||||
final barColor = exhausted ? c.danger : (low ? c.warning : c.accent);
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.fromLTRB(14, 12, 14, 12),
|
||||
@@ -33,23 +75,32 @@ class QuotaCard extends StatelessWidget {
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(children: [
|
||||
Icon(PangolinIcons.clock, size: 15, color: c.accent),
|
||||
Icon(PangolinIcons.clock, size: 15, color: exhausted ? c.danger : c.accent),
|
||||
const SizedBox(width: 7),
|
||||
Text(t.quotaToday,
|
||||
// 标签固定、绝不省略(此前用 Flexible 让「今日剩余」被挤成「今日…」)。
|
||||
Text(label,
|
||||
style: PangolinText.caption.copyWith(color: c.fg2, fontWeight: FontWeight.w600, fontSize: 12)),
|
||||
const SizedBox(width: 7),
|
||||
Text('${quota.remainingMinutes} ${t.minutes}',
|
||||
style: PangolinText.mono.copyWith(color: c.fg1, fontSize: 14, fontWeight: FontWeight.w600)),
|
||||
if (value.isNotEmpty) ...[
|
||||
const SizedBox(width: 7),
|
||||
// 数值可作为最后收缩项(极端窄屏/三位数分钟才会省略)。
|
||||
Flexible(
|
||||
child: Text(value,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: PangolinText.mono.copyWith(color: c.fg1, fontSize: 14, fontWeight: FontWeight.w600)),
|
||||
),
|
||||
],
|
||||
const SizedBox(width: 8),
|
||||
const Spacer(),
|
||||
// 短标签「免费版」——每日额度由卡片本身表达,不再挤进右上角。
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 3),
|
||||
decoration: BoxDecoration(color: c.bgSubtle, borderRadius: BorderRadius.circular(PangolinRadius.full)),
|
||||
child: Text(t.quotaFree,
|
||||
child: Text(t.planFreeTag,
|
||||
style: PangolinText.caption.copyWith(color: c.fg3, fontWeight: FontWeight.w600, fontSize: 10.5)),
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 9),
|
||||
// 进度条:剩余比例;≤3 分钟切 warning 色(满宽轨道 + 比例填充)
|
||||
// 进度条:剩余比例;≤3 分钟 warning、耗尽 danger(满宽轨道 + 比例填充)。
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
child: SizedBox(
|
||||
@@ -58,7 +109,7 @@ class QuotaCard extends StatelessWidget {
|
||||
Positioned.fill(child: ColoredBox(color: c.bgSubtle)),
|
||||
FractionallySizedBox(
|
||||
alignment: Alignment.centerLeft,
|
||||
widthFactor: quota.progress,
|
||||
widthFactor: progress,
|
||||
child: AnimatedContainer(
|
||||
duration: PangolinMotion.base,
|
||||
curve: PangolinMotion.easeOut,
|
||||
@@ -68,30 +119,25 @@ class QuotaCard extends StatelessWidget {
|
||||
]),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 11),
|
||||
if (quota.adUnlocked)
|
||||
SizedBox(
|
||||
height: 38,
|
||||
child: Center(
|
||||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
Icon(PangolinIcons.checkCircle, size: 16, color: c.success),
|
||||
const SizedBox(width: 7),
|
||||
Text(t.adUnlocked,
|
||||
style: PangolinText.sm.copyWith(color: c.success, fontWeight: FontWeight.w700, fontSize: 13)),
|
||||
]),
|
||||
),
|
||||
)
|
||||
else
|
||||
_WatchAdButton(t: t, onTap: onWatchAd),
|
||||
// 加时按钮:未连接时显示。移动端「看广告加时」;桌面仅耗尽时给「升级会员」。
|
||||
if (!connected && (!isDesktop || exhausted)) ...[
|
||||
const SizedBox(height: 11),
|
||||
_ActionButton(
|
||||
label: isDesktop ? t.upgrade : t.watchAdMore,
|
||||
icon: isDesktop ? PangolinIcons.zap : PangolinIcons.playCircle,
|
||||
onTap: onWatchAd,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _WatchAdButton extends StatelessWidget {
|
||||
const _WatchAdButton({required this.t, required this.onTap});
|
||||
final AppText t;
|
||||
class _ActionButton extends StatelessWidget {
|
||||
const _ActionButton({required this.label, required this.icon, required this.onTap});
|
||||
final String label;
|
||||
final IconData icon;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
@@ -107,9 +153,9 @@ class _WatchAdButton extends StatelessWidget {
|
||||
height: 38,
|
||||
child: Center(
|
||||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
Icon(PangolinIcons.playCircle, size: 16, color: c.accent),
|
||||
Icon(icon, size: 16, color: c.accent),
|
||||
const SizedBox(width: 7),
|
||||
Text(t.watchAd,
|
||||
Text(label,
|
||||
style: PangolinText.sm.copyWith(color: c.accent, fontWeight: FontWeight.w700, fontSize: 13)),
|
||||
]),
|
||||
),
|
||||
|
||||
@@ -12,4 +12,14 @@ class AppDelegate: FlutterAppDelegate {
|
||||
override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// 隐藏到托盘后点 Dock 图标 → 唤回主窗口。窗口被 window_manager.hide()(orderOut:)
|
||||
// 隐藏时 hasVisibleWindows=false,系统只发 reopen 事件、不会自动显示;不接管就"点了没反应"。
|
||||
override func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
|
||||
if !flag {
|
||||
mainFlutterWindow?.makeKeyAndOrderFront(nil)
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
name: pangolin_vpn
|
||||
description: 穿山甲 · Pangolin — 极简、稳定、跨平台网络加速客户端。
|
||||
publish_to: "none"
|
||||
version: 1.0.43+44
|
||||
version: 1.0.48+49
|
||||
|
||||
environment:
|
||||
sdk: ^3.5.0
|
||||
|
||||
@@ -20,6 +20,7 @@ const _frozenMeKeys = <String>{
|
||||
'devices_used',
|
||||
'devices_max',
|
||||
'quota_today_min',
|
||||
'quota_cap_min',
|
||||
'data_today_gb',
|
||||
'weekly_gb',
|
||||
'totp_enabled',
|
||||
@@ -37,6 +38,7 @@ Map<String, dynamic> _meSample() => {
|
||||
'devices_used': 2,
|
||||
'devices_max': 5,
|
||||
'quota_today_min': null, // pro/team 不限 → null
|
||||
'quota_cap_min': null, // pro/team 不限 → null
|
||||
'data_today_gb': 1.5,
|
||||
'weekly_gb': [0.1, 0.2, 0.0, 1.0, 2.0, 0.5, 1.5],
|
||||
'totp_enabled': true,
|
||||
|
||||
@@ -76,12 +76,12 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('额度卡(已解锁)· $suffix', (tester) async {
|
||||
testWidgets('额度卡(已耗尽)· $suffix', (tester) async {
|
||||
await goldenOf(
|
||||
tester,
|
||||
QuotaCard(quota: const FreeQuotaState(adUnlocked: true), t: t, onWatchAd: () {}),
|
||||
QuotaCard(quota: const FreeQuotaState(remainingMinutes: 0), t: t, onWatchAd: () {}),
|
||||
find.byType(QuotaCard),
|
||||
'quota_unlocked_$suffix',
|
||||
'quota_exhausted_$suffix',
|
||||
dark: dark,
|
||||
);
|
||||
});
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 8.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 8.8 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 9.5 KiB After Width: | Height: | Size: 9.0 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 9.4 KiB |
@@ -11,8 +11,10 @@ import 'package:pangolin_vpn/bridge/vpn_bridge_provider.dart';
|
||||
import 'package:pangolin_vpn/l10n/strings_zh.dart';
|
||||
import 'package:pangolin_vpn/models/node.dart';
|
||||
import 'package:pangolin_vpn/services/connect_api.dart';
|
||||
import 'package:pangolin_vpn/services/device_identity.dart';
|
||||
import 'package:pangolin_vpn/state/connection_provider.dart';
|
||||
import 'package:pangolin_vpn/state/nodes_provider.dart';
|
||||
import 'package:pangolin_vpn/state/quota_provider.dart';
|
||||
|
||||
// 可控假桥:能手动推 VpnStatus,无内部计时器(避免 pending timer)。
|
||||
class _FakeBridge implements VpnBridge {
|
||||
@@ -54,6 +56,16 @@ class _FakeConnectApi extends ConnectApi {
|
||||
void dispose() {}
|
||||
}
|
||||
|
||||
// 内存 SecureKV:避免测试里 flutter_secure_storage 平台通道无 handler 时 deviceId() 挂起
|
||||
// (进而 _connect 卡在 connecting)。#18 自动重连会走 _connect,必须让 deviceId() 立即返回。
|
||||
class _MemKV implements SecureKV {
|
||||
final _m = <String, String>{};
|
||||
@override
|
||||
Future<String?> read(String key) async => _m[key];
|
||||
@override
|
||||
Future<void> write(String key, String value) async => _m[key] = value;
|
||||
}
|
||||
|
||||
// 两节点都可用(status=up)。
|
||||
class _StubNodes extends NodesNotifier {
|
||||
@override
|
||||
@@ -84,6 +96,7 @@ void main() {
|
||||
ProviderContainer(overrides: [
|
||||
vpnBridgeProvider.overrideWithValue(bridge),
|
||||
nodesProvider.overrideWith(nodes ?? _StubNodes.new),
|
||||
deviceIdentityProvider.overrideWithValue(DeviceIdentity(store: _MemKV())),
|
||||
connectApiFactoryProvider.overrideWithValue((_) => _FakeConnectApi()),
|
||||
connectionProvider.overrideWith(
|
||||
(ref) => ConnectionController(ref, ref.watch(vpnBridgeProvider), now: now)),
|
||||
@@ -100,19 +113,42 @@ void main() {
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
testWidgets('路径A:意外内核掉线(非用户主动)→ 置「节点异常」提示', (tester) async {
|
||||
// #18:意外内核掉线(弱网最常见)先自动重连当前节点,不换节点、不立即报「节点异常」;
|
||||
// 连续失败超过 _kMaxAutoReconnect(3) 次才真报「节点异常」。
|
||||
testWidgets('#18 意外内核掉线(弱网)→ 先自动重连当前节点,超上限才报「节点异常」', (tester) async {
|
||||
final bridge = _FakeBridge();
|
||||
final c = makeContainer(bridge); // 节点都 up,排除路径B
|
||||
final c = makeContainer(bridge); // 节点都 up(排除路径B);默认智能
|
||||
addTearDown(bridge.dispose);
|
||||
addTearDown(c.dispose);
|
||||
await tester.pumpWidget(UncontrolledProviderScope(container: c, child: const SizedBox()));
|
||||
await driveOn(tester, c, bridge);
|
||||
expect(c.read(connectionProvider).phase, VpnPhase.on);
|
||||
bridge.emit(VpnStatus.off); // 模拟节点数据面死 → REALITY 断 → 内核自报 off
|
||||
c.read(nodesProvider);
|
||||
c.read(connectionProvider); // 实例化控制器,使其订阅 bridge.statusStream(否则首个 emit 丢失)
|
||||
await tester.pump();
|
||||
final st = c.read(connectionProvider);
|
||||
expect(st.phase, VpnPhase.off, reason: '内核掉线应回 off');
|
||||
expect(st.error, t.nodeUnhealthyError, reason: '非用户主动掉线应给「节点异常」提示');
|
||||
final initialSel = c.read(selectedNodeCodeProvider);
|
||||
const maxRetries = 3; // = _kMaxAutoReconnect
|
||||
|
||||
Future<void> dropOnce() async {
|
||||
bridge.emit(VpnStatus.on);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
bridge.emit(VpnStatus.off); // 弱网:数据面瞬断 → 内核自报 off
|
||||
// 泵到重连尝试(_connect fake 会失败回 off)settle,避免下一轮 emit(on) 与本轮 async 交错。
|
||||
for (var k = 0; k < 15 && c.read(connectionProvider).phase != VpnPhase.off; k++) {
|
||||
await tester.pump(const Duration(milliseconds: 10));
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < maxRetries; i++) {
|
||||
await dropOnce();
|
||||
expect(c.read(connectionProvider).error, isNot(t.nodeUnhealthyError),
|
||||
reason: '第${i + 1}次弱网掉线应自动重连,不应报「节点异常」');
|
||||
expect(c.read(selectedNodeCodeProvider), initialSel, reason: '弱网不应换节点');
|
||||
}
|
||||
// 额度用尽 → 报「节点异常」。
|
||||
await dropOnce();
|
||||
expect(c.read(connectionProvider).phase, VpnPhase.off);
|
||||
expect(c.read(connectionProvider).error, t.nodeUnhealthyError,
|
||||
reason: '自动重连用尽后应给「节点异常」');
|
||||
});
|
||||
|
||||
testWidgets('路径B:服务端判当前节点 down(智能)→ 切到其他可用节点', (tester) async {
|
||||
@@ -126,17 +162,21 @@ void main() {
|
||||
expect(c.read(selectedNodeCodeProvider), 'JP', reason: '智能模式应自动切到其他可用节点');
|
||||
});
|
||||
|
||||
testWidgets('路径B:服务端判当前节点 down(手动)→ 断开 + 提示,不自动换', (tester) async {
|
||||
// 路径B(服务端判当前节点 down)手动模式无备用:也走自动重连当前节点(不换、不立即报「节点异常」)。
|
||||
// 重试用尽 → 报「节点异常」的额度逻辑由上面的 kernel-off 用例覆盖(同一 _tryAutoReconnectCurrent)。
|
||||
testWidgets('#18 路径B 手动节点被判 down(无备用)→ 自动重连当前节点,不换、不立即报「节点异常」', (tester) async {
|
||||
final bridge = _FakeBridge();
|
||||
final c = makeContainer(bridge, nodes: _StubNodesHKDown.new);
|
||||
addTearDown(bridge.dispose);
|
||||
addTearDown(c.dispose);
|
||||
await tester.pumpWidget(UncontrolledProviderScope(container: c, child: const SizedBox()));
|
||||
c.read(selectedNodeCodeProvider.notifier).select('HK'); // 手动选定 HK(已 down)
|
||||
await driveOn(tester, c, bridge);
|
||||
final st = c.read(connectionProvider);
|
||||
expect(st.phase, VpnPhase.off, reason: '手动模式节点 down 应断开');
|
||||
expect(st.error, t.nodeUnhealthyError, reason: '应给节点异常提示');
|
||||
c.read(selectedNodeCodeProvider.notifier).select('HK'); // 手动 HK(已 down),无备用
|
||||
await driveOn(tester, c, bridge); // on → 看门狗 _checkHealth 判 HK down → _onNodeUnhealthy
|
||||
for (var k = 0; k < 15 && c.read(connectionProvider).phase != VpnPhase.off; k++) {
|
||||
await tester.pump(const Duration(milliseconds: 10));
|
||||
}
|
||||
expect(c.read(connectionProvider).error, isNot(t.nodeUnhealthyError),
|
||||
reason: '首次判死应自动重连当前节点,不立即报「节点异常」');
|
||||
expect(c.read(selectedNodeCodeProvider), 'HK', reason: '手动模式不应自动换节点');
|
||||
});
|
||||
|
||||
@@ -279,4 +319,36 @@ void main() {
|
||||
bridge.emit(VpnStatus.off); // 收尾:停看门狗/计时器
|
||||
await tester.pump();
|
||||
});
|
||||
|
||||
// 免费版 10 分钟卡控:连接期倒计时,墙上时钟越过额度即自动切断 + 本地置耗尽(#21)。
|
||||
testWidgets('免费额度倒计时归零 → 自动切断 + 置耗尽', (tester) async {
|
||||
final bridge = _FakeBridge();
|
||||
var fake = DateTime(2026, 7, 1, 12);
|
||||
final c = makeContainer(bridge, now: () => fake); // 未登录默认免费,剩余 10 分钟
|
||||
addTearDown(bridge.dispose);
|
||||
addTearDown(c.dispose);
|
||||
await tester.pumpWidget(UncontrolledProviderScope(container: c, child: const SizedBox()));
|
||||
c.read(nodesProvider);
|
||||
await tester.pump();
|
||||
|
||||
// 免费默认剩余 10 分钟 → toggle 触发 _connect 锁定 600s 倒计时(fake api 抛错不影响锁定)。
|
||||
expect(c.read(quotaProvider).remainingMinutes, 10);
|
||||
c.read(connectionProvider.notifier).toggle();
|
||||
await tester.pump();
|
||||
bridge.emit(VpnStatus.on); // _startElapsed:_connectedAt = fake(T0)
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(c.read(connectionProvider).phase, VpnPhase.on);
|
||||
expect(c.read(connectionProvider).freeCountdown, isNotNull, reason: '连接期应有倒计时');
|
||||
|
||||
// 快进墙上时钟越过 10 分钟 → 下一个 1s tick 触发 _refreshElapsed → 切断。
|
||||
fake = fake.add(const Duration(seconds: 601));
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
|
||||
expect(c.read(connectionProvider).phase, VpnPhase.off, reason: '额度用完应自动切断');
|
||||
expect(c.read(connectionProvider).error, t.quotaExhaustedNotice, reason: '应给「已用完」提示');
|
||||
expect(c.read(quotaProvider).isExhausted, true, reason: '切断后本地置耗尽 → 按钮灰化');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -41,24 +41,29 @@ void main() {
|
||||
expect(const FreeQuotaState(remainingMinutes: 3).isLow, true);
|
||||
expect(const FreeQuotaState(remainingMinutes: 4).isLow, false);
|
||||
});
|
||||
test('isExhausted:剩余 ≤0 为真', () {
|
||||
expect(const FreeQuotaState(remainingMinutes: 0).isExhausted, true);
|
||||
expect(const FreeQuotaState(remainingMinutes: 1).isExhausted, false);
|
||||
});
|
||||
});
|
||||
|
||||
// 未登录默认态:总额 10 / 剩余 10 / 未解锁;watchAd 本地置位。
|
||||
// 未登录默认态:总额 10 / 剩余 10 / 未耗尽。
|
||||
group('quotaProvider', () {
|
||||
test('默认 10/10 未解锁', () {
|
||||
test('默认 10/10 未耗尽', () {
|
||||
final c = _container();
|
||||
addTearDown(c.dispose);
|
||||
final q = c.read(quotaProvider);
|
||||
expect(q.totalMinutes, 10);
|
||||
expect(q.remainingMinutes, 10);
|
||||
expect(q.adUnlocked, false);
|
||||
expect(q.isExhausted, false);
|
||||
});
|
||||
|
||||
test('watchAd 解锁今日使用', () {
|
||||
test('markExhausted 本地立即置剩余 0', () {
|
||||
final c = _container();
|
||||
addTearDown(c.dispose);
|
||||
c.read(quotaProvider.notifier).watchAd();
|
||||
expect(c.read(quotaProvider).adUnlocked, true);
|
||||
c.read(quotaProvider.notifier).markExhausted();
|
||||
expect(c.read(quotaProvider).remainingMinutes, 0);
|
||||
expect(c.read(quotaProvider).isExhausted, true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -12,24 +12,32 @@ void main() {
|
||||
setUpAll(disableGoogleFontsFetching);
|
||||
const t = StringsZh();
|
||||
|
||||
testWidgets('额度卡:未解锁显示看广告按钮,点击回调', (tester) async {
|
||||
testWidgets('额度卡(移动·有余额):显示看广告加时按钮,点击回调', (tester) async {
|
||||
var watched = 0;
|
||||
await tester.pumpWidget(wrapThemed(
|
||||
QuotaCard(quota: const FreeQuotaState(), t: t, onWatchAd: () => watched++),
|
||||
));
|
||||
await tester.pump();
|
||||
expect(find.text(t.watchAd), findsOneWidget);
|
||||
await tester.tap(find.text(t.watchAd));
|
||||
expect(find.text(t.watchAdMore), findsOneWidget);
|
||||
await tester.tap(find.text(t.watchAdMore));
|
||||
expect(watched, 1);
|
||||
});
|
||||
|
||||
testWidgets('额度卡:已解锁显示已解锁文案', (tester) async {
|
||||
testWidgets('额度卡(耗尽):显示今日已用完 + 看广告加时', (tester) async {
|
||||
await tester.pumpWidget(wrapThemed(
|
||||
QuotaCard(quota: const FreeQuotaState(adUnlocked: true), t: t, onWatchAd: () {}),
|
||||
QuotaCard(quota: const FreeQuotaState(remainingMinutes: 0), t: t, onWatchAd: () {}),
|
||||
));
|
||||
await tester.pump();
|
||||
expect(find.text(t.adUnlocked), findsOneWidget);
|
||||
expect(find.byIcon(PangolinIcons.checkCircle), findsOneWidget);
|
||||
expect(find.text(t.quotaUsedUp), findsOneWidget);
|
||||
expect(find.text(t.watchAdMore), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('额度卡(桌面·有余额):不显示加时按钮', (tester) async {
|
||||
await tester.pumpWidget(wrapThemed(
|
||||
QuotaCard(quota: const FreeQuotaState(), t: t, isDesktop: true, onWatchAd: () {}),
|
||||
));
|
||||
await tester.pump();
|
||||
expect(find.text(t.watchAdMore), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('推荐卡:展示推荐胶囊与文案,选中显示对勾', (tester) async {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
; 前置: 先在 client/ 跑 `flutter build windows`(Release),产物在
|
||||
; ..\..\build\windows\x64\runner\Release
|
||||
#define MyAppName "穿山甲 Pangolin"
|
||||
#define MyAppVersion "1.0.43"
|
||||
#define MyAppVersion "1.0.47"
|
||||
#define MyAppPublisher "Pangolin"
|
||||
#define MyAppExeName "pangolin_vpn.exe"
|
||||
#define BuildDir "..\..\build\windows\x64\runner\Release"
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>免费版 10 分钟卡控 + 累加式看广告加时(设计 · #21)</title>
|
||||
<style>
|
||||
:root{
|
||||
--bg:#0f1117; --panel:#171a22; --panel2:#1d2129; --fg:#e6e8ee; --fg2:#a8afbd;
|
||||
--accent:#e0884f; --accent2:#5fb0c9; --ok:#5ec27a; --bad:#e06a6a; --warn:#e0b84f;
|
||||
--border:#272c36; --mono:"SF Mono",ui-monospace,Menlo,Consolas,monospace;
|
||||
--sans:-apple-system,"PingFang SC","Helvetica Neue",Arial,sans-serif;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:var(--bg);color:var(--fg);font-family:var(--sans);line-height:1.7;font-size:15px}
|
||||
.wrap{max-width:920px;margin:0 auto;padding:48px 24px 96px}
|
||||
h1{font-size:30px;line-height:1.3;margin:0 0 8px;letter-spacing:-.01em}
|
||||
.sub{color:var(--fg2);font-size:15px;margin:0 0 32px}
|
||||
h2{font-size:21px;margin:44px 0 14px;padding-bottom:8px;border-bottom:1px solid var(--border)}
|
||||
h3{font-size:16px;margin:26px 0 8px;color:var(--accent2)}
|
||||
p{margin:10px 0}
|
||||
code{font-family:var(--mono);font-size:.88em;background:var(--panel2);padding:1px 6px;border-radius:5px;color:#f0d9c4}
|
||||
pre{background:#0a0c11;border:1px solid var(--border);border-radius:10px;padding:14px 16px;overflow-x:auto;font-family:var(--mono);font-size:13px;line-height:1.55;color:#cdd3df}
|
||||
.tag{display:inline-block;font-size:12px;font-weight:600;padding:2px 9px;border-radius:999px;vertical-align:middle}
|
||||
.tag.ok{background:rgba(94,194,122,.16);color:var(--ok)}
|
||||
.tag.warn{background:rgba(224,184,79,.16);color:var(--warn)}
|
||||
.tag.info{background:rgba(95,176,201,.16);color:var(--accent2)}
|
||||
.card{background:var(--panel);border:1px solid var(--border);border-radius:12px;padding:18px 20px;margin:16px 0}
|
||||
.card.root{border-left:3px solid var(--accent)}
|
||||
.card h3{margin-top:0}
|
||||
table{width:100%;border-collapse:collapse;margin:16px 0;font-size:14px}
|
||||
th,td{text-align:left;padding:9px 12px;border-bottom:1px solid var(--border);vertical-align:top}
|
||||
th{color:var(--fg2);font-weight:600;font-size:13px}
|
||||
td code{font-size:.85em}
|
||||
ul,ol{padding-left:22px;margin:10px 0}
|
||||
li{margin:5px 0}
|
||||
.lead{background:linear-gradient(180deg,rgba(224,136,79,.10),transparent);border:1px solid var(--border);border-radius:12px;padding:18px 20px;margin:0 0 8px}
|
||||
.small{color:var(--fg2);font-size:13px}
|
||||
a{color:var(--accent2)}
|
||||
.back{display:inline-block;margin-bottom:24px;font-size:13px}
|
||||
b{color:#fff}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<a class="back" href="index.html">← 返回文档索引</a>
|
||||
|
||||
<h1>免费版 10 分钟卡控 + 累加式看广告加时</h1>
|
||||
<p class="sub">设计 · todo #21 · <span class="tag info">后端 + 前端 + 数据库</span> · 额度全账户共享</p>
|
||||
|
||||
<div class="lead">
|
||||
免费版此前<b>形同虚设</b>:连接页无倒计时、时间到不卡控、按钮永远可点。根因在服务端——
|
||||
<code>ConnectNode</code> 免费门每次连接都发<b>固定 <code>daily_minutes×1min</code> TTL、从不扣减已用</b>,
|
||||
重连即崭新 10 分钟,日额度从未真正强制。本次将其改为<b>账户级(全设备共享)真卡控</b> +
|
||||
<b>累加式看广告加时</b>:连接期倒计时、到点自动切断、耗尽按钮灰化、点击弹广告、看完 +N 分钟。
|
||||
</div>
|
||||
|
||||
<h2>目标与口径(已确认)</h2>
|
||||
<ul>
|
||||
<li><b>连接期倒计时</b>:连上后显示剩余 mm:ss,到 0 自动切断隧道。</li>
|
||||
<li><b>耗尽卡控</b>:额度用完 → 连接按钮变灰不可点。</li>
|
||||
<li><b>看广告加时(累加式)</b>:点灰按钮弹广告,看完 <b>+10 分钟</b>(可重复,每日封顶 <b>120 分钟</b>)。</li>
|
||||
<li><b>占位广告 SDK</b>:先跑通假流程(dialog→“播放中”→奖励),服务端用放行式 <code>DevVerifier</code>(nonce 仍防重放),接真 AdMob 时替换。</li>
|
||||
<li><b>桌面(Windows/macOS)</b>:免费 = <b>硬 10 分钟/天不可延</b>,无广告;到点→切断+灰按钮+提示“去移动端看广告或升级”。</li>
|
||||
<li><b>额度全账户共享</b>:非每设备。服务端 <code>usage_daily</code> 本就按 <code>user_id</code> 聚合所有设备的 <code>minutes_used</code>,天然账户级;客户端倒计时仅本地近似,权威始终以 <code>quota_today_min</code> 为准。</li>
|
||||
</ul>
|
||||
|
||||
<h2>数据模型</h2>
|
||||
<div class="card root">
|
||||
<h3>migration 000020_ad_bonus_minutes(sqlite + mysql)</h3>
|
||||
<pre>ALTER TABLE usage_daily ADD COLUMN ad_bonus_minutes INT NOT NULL DEFAULT 0;</pre>
|
||||
<p>当日免费额度 = <code>plans.daily_minutes</code>(free=10)+ <code>usage_daily.ad_bonus_minutes</code>(看广告累加);
|
||||
剩余 = 额度 − <code>minutes_used</code>。历史列 <code>ad_unlocked_at</code>(布尔式当日解锁)保留但不再用于卡控。</p>
|
||||
</div>
|
||||
|
||||
<h2>后端</h2>
|
||||
<table>
|
||||
<tr><th>层</th><th>改动</th></tr>
|
||||
<tr><td><code>usage/store.go</code></td><td><code>AddAdBonusMinutes(uid,day,add,ceiling)</code>:事务内 <code>LockForUpdate</code> 读旧值 → 累加封顶 → upsert,返回<b>新总额 + 本次实际加时</b>。<code>DailyUsage</code>/<code>GetDay</code>/<code>GetUsageRange</code> 补读 <code>ad_bonus_minutes</code>。<code>MarkAdUnlocked</code> 标 deprecated。</td></tr>
|
||||
<tr><td><code>usage/service.go</code></td><td>常量 <code>adBonusPerAd=10</code> / <code>adDailyBonusCeiling=120</code>。<code>TodaySummary</code> 加 <code>MinutesCap</code>(=daily+bonus)/ <code>AdBonusMinutes</code>;<code>remaining=cap−used</code>。<code>UnlockAd</code> 改累加:verify+nonce 后 <code>+adBonusPerAd</code> 封顶,返回 <code>(granted, remaining)</code>。</td></tr>
|
||||
<tr><td><code>usage/ads.go</code> + <code>main.go</code></td><td>放行式 <code>DevVerifier</code>(<code>Verify</code> 恒 nil)。<code>main.go</code> 按 <code>ADS_DEV_MODE</code>/默认装配(替换现在的 <code>nil</code>——否则 <code>UnlockAd</code> 直接 <code>ErrInternal</code>,占位流程走不通)。nonce 防重放仍生效。</td></tr>
|
||||
<tr><td><code>httpapi/nodes.go</code> ConnectNode</td><td>新增 <code>nodes.store.AccountDayMinutes(uid,day)→(used,bonus)</code>。免费门:<code>allowance=daily+bonus</code>,<code>remaining=allowance−used</code>;<code>remaining≤0</code>→拒 <code>QUOTA_EXHAUSTED</code>;否则 <b><code>TTL=remaining×1min</code></b>(凭证到点硬切断兜底,防绕过客户端)。</td></tr>
|
||||
<tr><td><code>httpapi/account.go</code> /me</td><td>补读 <code>ad_bonus_minutes</code>;<code>quota_today_min</code> 分母改 <code>daily+bonus</code>;新增 <code>quota_cap_min</code>(=allowance,客户端进度条分母)。</td></tr>
|
||||
<tr><td><code>usage/handler.go</code></td><td><code>POST /v1/ads/unlock</code>:204 → <b>200</b> 返回 <code>{granted_minutes, minutes_remaining}</code>。</td></tr>
|
||||
</table>
|
||||
|
||||
<h2>前端(四端共享 Dart)</h2>
|
||||
<table>
|
||||
<tr><th>层</th><th>改动</th></tr>
|
||||
<tr><td><code>models/me.dart</code></td><td>加 <code>quotaCapMin</code>(当日总额度)。</td></tr>
|
||||
<tr><td><code>state/quota_provider.dart</code></td><td><code>total=me.quotaCapMin</code>;<code>isExhausted</code>;<code>markExhausted()</code>(倒计时归零本地置耗尽 + 登录态拉 me 校准);<code>watchAd()</code> async 调 <code>/ads/unlock</code>(占位 ad_token=uuid)→ 刷新 me,返回 granted。</td></tr>
|
||||
<tr><td><code>state/connection_provider.dart</code></td><td>连接时锁定 <code>_freeRemainingSec</code>(会员为 null 不倒计时)。复用 elapsed 计时器每 tick 算 <code>countdown=cap−elapsed</code>,写入 <code>ConnectionState.freeCountdown</code>;<b>归零→自动切断</b>(<code>_onFreeQuotaExhausted</code>:主动断开不报节点异常 + <code>markExhausted</code>)。倒计时用墙上时钟,后台漏跳回前台补上、准时切。连接遇后端 <code>QUOTA_EXHAUSTED</code> 兜底置耗尽。</td></tr>
|
||||
<tr><td><code>widgets/connect_button.dart</code></td><td>加 <code>enabled</code>/<code>onDisabledTap</code>:off 态额度耗尽 → 灰化(锁图标),点击走加时流程。</td></tr>
|
||||
<tr><td><code>widgets/quota_card.dart</code></td><td>三态:连接中显示倒计时 mm:ss + 进度收缩;未连接有余额显示剩余分钟;耗尽显示“今日已用完”。移动端「看广告加时」/ 桌面「升级会员」。</td></tr>
|
||||
<tr><td><code>widgets/ad_reward_dialog.dart</code>(新)</td><td>移动端占位广告:“广告播放中…”→3s→调 <code>watchAd</code>→显示“已加 N 分钟”自动关闭。桌面版:升级/移动端提示弹窗(无广告)。</td></tr>
|
||||
<tr><td>l10n(zh/en)</td><td>倒计时/今日已用完/看广告加时/占位广告播放/奖励/桌面升级提示 双语文案。</td></tr>
|
||||
</table>
|
||||
|
||||
<h2>时序</h2>
|
||||
<div class="card">
|
||||
<h3>移动端典型流</h3>
|
||||
<pre>连接 → /me remaining=10 → 倒计时 10:00 …… 00:00
|
||||
→ 客户端 _onFreeQuotaExhausted:切断隧道 + 按钮灰化 + markExhausted
|
||||
点灰按钮 → 占位广告 dialog(3s)→ POST /ads/unlock(DevVerifier 放行 + nonce)
|
||||
→ 服务端 ad_bonus_minutes += 10(封顶 120)→ 返回 granted=10, remaining=10
|
||||
→ 刷新 /me(quota_cap_min=20, quota_today_min=10)→ 按钮恢复可连
|
||||
再次连接 → ConnectNode remaining=allowance−used → TTL=remaining(服务端硬切断兜底)</pre>
|
||||
</div>
|
||||
<p class="small"><b>桌面</b>:同样倒计时 + 到点切断 + 灰按钮,但点击弹“去移动端看广告或升级会员”,<b>无加时路径</b>(硬 10 分钟/天)。</p>
|
||||
|
||||
<h2>验证</h2>
|
||||
<ul>
|
||||
<li>后端单测:<code>AddAdBonusMinutes</code> 累加+封顶(SQLite 实库);<code>TodaySummary</code> cap/remaining;<code>UnlockAd</code> 走 DevVerifier 加时;ConnectNode remaining≤0 拒 / TTL=remaining(集成测试)。</li>
|
||||
<li>客户端:<code>flutter analyze</code> + <code>flutter test</code>(quota 倒计时/耗尽/加时;额度卡三态;/me 契约含 <code>quota_cap_min</code>)。</li>
|
||||
<li>真机:免费连接→倒计时→到 0 自动断+灰按钮;点灰→移动弹占位广告→+10 分钟→恢复可连;桌面到点→灰+升级提示(无广告);同账户两设备共享同一剩余。</li>
|
||||
</ul>
|
||||
|
||||
<h2>不在本轮</h2>
|
||||
<ul>
|
||||
<li>真 AdMob/激励视频 SDK 接入(<code>DevVerifier</code> 占位替换)。</li>
|
||||
<li>广告频次风控细化(现仅每日封顶 <code>adDailyBonusCeiling</code>)。</li>
|
||||
<li>客户端倒计时与服务端 <code>minutes_used</code> 聚合延迟的精确对账(以服务端 TTL 硬切断兜底)。</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -44,6 +44,11 @@
|
||||
</div>
|
||||
|
||||
<h2>设计方案 / Specs</h2>
|
||||
<a class="doc" href="free-quota-ad.html">
|
||||
<div class="t">免费版 10 分钟卡控 + 累加式看广告加时 <span class="tag html">HTML</span></div>
|
||||
<div class="d">免费版真卡控(账户级/全设备共享):连接期倒计时 + 到点自动切断 + 耗尽按钮灰化 + 点击弹广告看完 +10 分钟(累加,每日封顶 120)。桌面硬 10 分钟不可延。服务端 ad_bonus_minutes 累加模型 + ConnectNode 按 remaining 卡控 + TTL 硬切断;占位 DevVerifier。#21。</div>
|
||||
<div class="path">docs/free-quota-ad.html</div>
|
||||
</a>
|
||||
<a class="doc" href="device-limit-design.html">
|
||||
<div class="t">设备数量限制 + 超限 UX <span class="tag html">HTML</span></div>
|
||||
<div class="d">真正启用套餐设备上限(free 1 / pro 3 / team 10):卡在登录(非硬拒登,返回 device_limit 信号)+ 选择移除/一键踢最旧 + 服务端按 last_seen 自动清理久不活跃。复用现成 DeleteDevice/ResolvePlan。无 DB schema 变更。#16。</div>
|
||||
|
||||
+28
-6
@@ -294,10 +294,11 @@ paths:
|
||||
/ads/unlock:
|
||||
post:
|
||||
operationId: adsUnlock
|
||||
summary: 激励视频广告解锁当日时长
|
||||
summary: 激励视频广告加时(累加式)
|
||||
description: |
|
||||
免费版用户完成激励视频广告后调用。服务端向广告平台(AdMob/Unity)校验 ad_token 真伪,
|
||||
通过后记录 `usage_daily.ad_unlocked_at`,当日 connect 接口方可放行。
|
||||
通过后向 `usage_daily.ad_bonus_minutes` 累加固定分钟(每日封顶),当日免费额度随之上浮。
|
||||
额度为**全账户共享**(非每设备)。响应返回本次实际加时与最新剩余分钟。
|
||||
tags: [Commerce]
|
||||
requestBody:
|
||||
required: true
|
||||
@@ -315,8 +316,20 @@ paths:
|
||||
type: string
|
||||
description: 广告 SDK 签发的服务端回执 token
|
||||
responses:
|
||||
"204":
|
||||
description: 广告解锁成功(无响应体)
|
||||
"200":
|
||||
description: 广告加时成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [granted_minutes, minutes_remaining]
|
||||
properties:
|
||||
granted_minutes:
|
||||
type: integer
|
||||
description: 本次广告实际加时分钟(已达每日封顶时为 0)
|
||||
minutes_remaining:
|
||||
type: integer
|
||||
description: 加时后账户当日剩余分钟(全账户共享)
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
"401":
|
||||
@@ -715,14 +728,23 @@ components:
|
||||
type: integer
|
||||
description: 今日已使用分钟数
|
||||
example: 3
|
||||
minutes_cap:
|
||||
type: integer
|
||||
nullable: true
|
||||
description: 今日额度 = 套餐每日分钟 + 看广告累加分钟;付费无限制时为 null
|
||||
example: 20
|
||||
minutes_remaining:
|
||||
type: integer
|
||||
nullable: true
|
||||
description: 今日剩余分钟数,付费无限制时为 null
|
||||
description: 今日剩余分钟数(全账户共享),付费无限制时为 null
|
||||
example: 7
|
||||
ad_bonus_minutes:
|
||||
type: integer
|
||||
description: 今日已通过看广告累加的分钟数
|
||||
example: 10
|
||||
ad_unlocked:
|
||||
type: boolean
|
||||
description: 免费版今日是否已完成激励广告解锁
|
||||
description: 免费版今日是否已通过看广告加过时(ad_bonus_minutes > 0,历史字段)
|
||||
example: false
|
||||
|
||||
Device:
|
||||
|
||||
@@ -301,7 +301,23 @@ func mountV1(r chi.Router, sqlDB *sql.DB, rdb *redis.Client, nodeSvc *nodes.Serv
|
||||
|
||||
// ── Usage ─────────────────────────────────────────────────────────────────
|
||||
usageStore := usage.NewStore(sqlDB)
|
||||
usageSvc := usage.NewService(usageStore, rdb, nil, time.Hour)
|
||||
// Ad verifier: real AdMob SSV in production; a放行式 DevVerifier when
|
||||
// ADS_DEV_MODE=1 (or no AdMob configured) so the placeholder看广告加时 flow
|
||||
// works end-to-end before the real ad SDK is wired in. Nonce replay
|
||||
// protection still applies either way.
|
||||
var adVerifier usage.AdVerifier
|
||||
if os.Getenv("ADS_DEV_MODE") == "1" {
|
||||
adVerifier = usage.DevVerifier{}
|
||||
slog.Warn("ads: DevVerifier enabled (ADS_DEV_MODE=1) — accepts any receipt; not for production")
|
||||
} else if os.Getenv("ADMOB_SSV") == "1" {
|
||||
adVerifier = usage.NewAdMobVerifier("", nil, 0, nil)
|
||||
} else {
|
||||
// Default (current state): no real ad network yet → placeholder verifier
|
||||
// so免费版看广告加时 is functional in the field.
|
||||
adVerifier = usage.DevVerifier{}
|
||||
slog.Warn("ads: no ad network configured — using DevVerifier placeholder")
|
||||
}
|
||||
usageSvc := usage.NewService(usageStore, rdb, adVerifier, time.Hour)
|
||||
usageHandler := usage.NewUsageHandler(usageSvc)
|
||||
deviceUsageHandler := usage.NewDeviceUsageHandler(usageSvc)
|
||||
adsHandler := usage.NewAdsUnlockHandler(usageSvc)
|
||||
|
||||
@@ -382,8 +382,14 @@ func (svc *Service) SessionActive(ctx context.Context, userID int64, deviceUUID
|
||||
if err != nil {
|
||||
return false, apierr.ErrInternal
|
||||
}
|
||||
if dev == nil || dev.UserID != userID {
|
||||
return true, nil // 未知 / 非本人设备:不据此登出
|
||||
if dev == nil {
|
||||
// 设备行已不存在 = 本设备被「移除」(DeleteDevice 删行)。已登录的客户端在登录时
|
||||
// 必然注册过自己的设备,轮询自身 device_id 却查无此行,只能是被移除 → 视为会话失效,
|
||||
// 让其登出(否则被移除的设备永远收到 active=true,不退出,只表现为数据面被断→「节点异常」)。
|
||||
return false, nil
|
||||
}
|
||||
if dev.UserID != userID {
|
||||
return true, nil // 非本人设备 uuid:不据此登出(fail-safe)
|
||||
}
|
||||
active, err := svc.sessions.HasActiveSession(ctx, userID, dev.ID)
|
||||
if err != nil {
|
||||
|
||||
@@ -31,7 +31,8 @@ type meResponse struct {
|
||||
// Web user-center fields.
|
||||
DevicesUsed int `json:"devices_used"`
|
||||
DevicesMax int `json:"devices_max"`
|
||||
QuotaTodayMin *int `json:"quota_today_min"` // null = unlimited (pro/team)
|
||||
QuotaTodayMin *int `json:"quota_today_min"` // 剩余分钟; null = unlimited (pro/team)
|
||||
QuotaCapMin *int `json:"quota_cap_min"` // 当日额度 = daily + 看广告 bonus; null = unlimited
|
||||
DataTodayGB float64 `json:"data_today_gb"`
|
||||
WeeklyGB []float64 `json:"weekly_gb"` // last 7 days, oldest→newest
|
||||
TOTPEnabled bool `json:"totp_enabled"`
|
||||
@@ -99,11 +100,12 @@ func (a *AccountAPI) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
// 日期在 Go 端算好传 ?,不用 MySQL 专属 UTC_DATE()(否则 SQLite 报错→恒 0)。
|
||||
var todayBytes uint64
|
||||
var todayMinutes int
|
||||
var todayAdBonus int
|
||||
today := time.Now().UTC().Format("2006-01-02")
|
||||
_ = a.db.QueryRowContext(ctx, `
|
||||
SELECT COALESCE(bytes_up, 0) + COALESCE(bytes_down, 0), COALESCE(minutes_used, 0)
|
||||
SELECT COALESCE(bytes_up, 0) + COALESCE(bytes_down, 0), COALESCE(minutes_used, 0), COALESCE(ad_bonus_minutes, 0)
|
||||
FROM usage_daily WHERE user_id = ? AND date = ?
|
||||
`, uid, today).Scan(&todayBytes, &todayMinutes)
|
||||
`, uid, today).Scan(&todayBytes, &todayMinutes, &todayAdBonus)
|
||||
|
||||
resp := meResponse{
|
||||
UUID: uuid,
|
||||
@@ -121,11 +123,14 @@ func (a *AccountAPI) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
resp.ExpiresAt = &s
|
||||
}
|
||||
// quota_today_min: null when the plan is unlimited, else remaining minutes.
|
||||
// 额度 = plan.daily_minutes + 当日看广告累加的 ad_bonus_minutes(账户共享)。
|
||||
if dailyMinutes.Valid {
|
||||
rem := int(dailyMinutes.Int64) - todayMinutes
|
||||
cap := int(dailyMinutes.Int64) + todayAdBonus
|
||||
rem := cap - todayMinutes
|
||||
if rem < 0 {
|
||||
rem = 0
|
||||
}
|
||||
resp.QuotaCapMin = &cap
|
||||
resp.QuotaTodayMin = &rem
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,6 @@ func TestContractMeResponse(t *testing.T) {
|
||||
assertFrozenKeys(t, "/v1/me", jsonTagSet(meResponse{}),
|
||||
"uuid", "email", "dp_uuid", "plan", "expires_at",
|
||||
"devices_used", "devices_max",
|
||||
"quota_today_min", "data_today_gb", "weekly_gb", "totp_enabled",
|
||||
"quota_today_min", "quota_cap_min", "data_today_gb", "weekly_gb", "totp_enabled",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -206,16 +206,33 @@ func (a *NodeAPI) ConnectNode(w http.ResponseWriter, r *http.Request) {
|
||||
// 2. Determine TTL from plan.
|
||||
var ttl time.Duration
|
||||
if ent.AdGate {
|
||||
// Free plan: flat 10-minute session for MVP (full ad-gate in a later pass).
|
||||
// Free plan: enforce the account-wide daily minute quota (shared across
|
||||
// ALL devices). allowance = plan.daily_minutes + 当日看广告累加的 bonus;
|
||||
// remaining = allowance − minutes_used. Credential TTL = remaining so the
|
||||
// data-plane hard-cuts when time runs out (backstop even if the client
|
||||
// countdown is bypassed). remaining ≤ 0 → 拒 QUOTA_EXHAUSTED, client 弹广告/升级.
|
||||
dm := int64(10)
|
||||
if ent.DailyMinutes.Valid {
|
||||
dm = ent.DailyMinutes.Int64
|
||||
}
|
||||
if dm <= 0 {
|
||||
apierr.WriteJSON(w, http.StatusForbidden, apierr.ErrQuotaExhausted)
|
||||
used, bonus, qerr := a.store.AccountDayMinutes(r.Context(), uid, time.Now().UTC())
|
||||
if qerr != nil {
|
||||
slog.Error("connect: account day minutes failed", "user", uid, "err", qerr)
|
||||
apierr.WriteJSON(w, http.StatusInternalServerError, apierr.ErrInternal)
|
||||
return
|
||||
}
|
||||
ttl = time.Duration(dm) * freeMinuteTTL
|
||||
remaining := dm + int64(bonus) - int64(used)
|
||||
if remaining <= 0 {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"code": "QUOTA_EXHAUSTED",
|
||||
"message_zh": "今日免费时长已用完,看广告加时或升级会员",
|
||||
"message_en": "Daily free minutes used up. Watch an ad to add time or upgrade.",
|
||||
})
|
||||
return
|
||||
}
|
||||
ttl = time.Duration(remaining) * freeMinuteTTL
|
||||
} else {
|
||||
ttl = paidCredentialTTL
|
||||
}
|
||||
|
||||
@@ -146,6 +146,10 @@ func (m *mockNodeStore) AccountDayBytes(_ context.Context, _ int64, _ time.Time)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (m *mockNodeStore) AccountDayMinutes(_ context.Context, _ int64, _ time.Time) (int, int, error) {
|
||||
return 0, 0, nil
|
||||
}
|
||||
|
||||
func (m *mockNodeStore) CountActiveDevices(_ context.Context, _ int64, _ time.Time) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
@@ -938,6 +942,72 @@ func TestReportUsage_Accumulates(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestReportUsage_AccountMinutesDedupPerUser verifies the account-level minutes are
|
||||
// deduped to WALL-CLOCK per user within a window: two devices of the same user active
|
||||
// in one window count as 1 minute (not 2), while bytes still sum and each device keeps
|
||||
// its own minute. Guards the多设备并发超计 fix.
|
||||
func TestReportUsage_AccountMinutesDedupPerUser(t *testing.T) {
|
||||
const nodeUUID = "test-node-usage-dedup"
|
||||
b := newTestServer(t, 1, nodeUUID)
|
||||
ctx := context.Background()
|
||||
// Two devices of user 101 (dev 55 & 66) + one device of user 202 (dev 77).
|
||||
b.store.devicesByDpUUID = map[string][2]int64{
|
||||
"dp-u1-d1": {101, 55},
|
||||
"dp-u1-d2": {101, 66},
|
||||
"dp-u2-d1": {202, 77},
|
||||
}
|
||||
|
||||
_, _, conn := enrollNode(t, b, nodeUUID)
|
||||
client := agentv1.NewAgentServiceClient(conn)
|
||||
if _, err := client.Register(ctx, &agentv1.RegisterRequest{NodeUUID: nodeUUID}); err != nil {
|
||||
t.Fatalf("Register: %v", err)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
if _, err := client.ReportUsage(ctx, &agentv1.UsageReport{
|
||||
NodeUUID: nodeUUID,
|
||||
WindowStartUnix: now.Add(-time.Minute).Unix(),
|
||||
WindowEndUnix: now.Unix(),
|
||||
Entries: []*agentv1.UsageEntry{
|
||||
{DpUUID: "dp-u1-d1", BytesUp: 100, BytesDown: 200, SessionMinutes: 1},
|
||||
{DpUUID: "dp-u1-d2", BytesUp: 10, BytesDown: 20, SessionMinutes: 1},
|
||||
{DpUUID: "dp-u2-d1", BytesUp: 5, BytesDown: 7, SessionMinutes: 1},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReportUsage: %v", err)
|
||||
}
|
||||
|
||||
// Account rollup: one entry per user; user 101 minutes deduped to 1 (not 2),
|
||||
// bytes summed across its two devices; user 202 = 1 minute.
|
||||
byUser := map[int64]mockUsageEntry{}
|
||||
for _, e := range b.store.usageLog() {
|
||||
byUser[e.UserID] = e
|
||||
}
|
||||
if len(byUser) != 2 {
|
||||
t.Fatalf("account rollup should have 2 users, got %d", len(byUser))
|
||||
}
|
||||
if u := byUser[101]; u.Minutes != 1 || u.BytesUp != 110 || u.BytesDown != 220 {
|
||||
t.Errorf("user101 account: minutes=%d bytesUp=%d bytesDown=%d, want 1/110/220 (墙上时钟去重)",
|
||||
u.Minutes, u.BytesUp, u.BytesDown)
|
||||
}
|
||||
if u := byUser[202]; u.Minutes != 1 || u.BytesUp != 5 {
|
||||
t.Errorf("user202 account: minutes=%d bytesUp=%d, want 1/5", u.Minutes, u.BytesUp)
|
||||
}
|
||||
|
||||
// Per-device: each of user101's two devices keeps its own minute (2 rows, 2 min total).
|
||||
var u1Rows int
|
||||
var u1Min int64
|
||||
for _, d := range b.store.deviceUsageLog() {
|
||||
if d.UserID == 101 {
|
||||
u1Rows++
|
||||
u1Min += d.Minutes
|
||||
}
|
||||
}
|
||||
if u1Rows != 2 || u1Min != 2 {
|
||||
t.Errorf("user101 per-device: rows=%d totalMinutes=%d, want 2/2 (每设备各计 1)", u1Rows, u1Min)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReportUsage_PerDevice verifies a per-device dp_uuid is dual-written: account
|
||||
// rollup (usage_daily) AND per-device attribution (usage_device_daily).
|
||||
func TestReportUsage_PerDevice(t *testing.T) {
|
||||
|
||||
@@ -290,6 +290,13 @@ func (h *Handler) ReportUsage(ctx context.Context, req *agentv1.UsageReport) (*a
|
||||
windowEnd := time.Unix(req.WindowEndUnix, 0).UTC()
|
||||
date := windowEnd.Truncate(24 * time.Hour)
|
||||
|
||||
// Account-level minutes are deduped to WALL-CLOCK per user: the免费额度是「所有
|
||||
// 设备共同的时间」,同一账户多台设备在同一窗口都活跃时只能算 1 分钟,否则 N 台并发 →
|
||||
// minutes_used = N×墙上时钟(超计,会把免费账号错误判耗尽)。字节是可加的 → 求和;
|
||||
// 分钟按窗口取 max(= 窗口墙上分钟)去重。每设备维度(usage_device_*)仍逐台累加。
|
||||
type acctAgg struct{ bytesUp, bytesDown, minutes int64 }
|
||||
byUser := make(map[int64]*acctAgg)
|
||||
|
||||
for _, entry := range req.Entries {
|
||||
if entry.DpUUID == "" {
|
||||
continue
|
||||
@@ -303,21 +310,18 @@ func (h *Handler) ReportUsage(ctx context.Context, req *agentv1.UsageReport) (*a
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
// Account-level rollup (always): daily (quota/today) + hourly (tz-aware
|
||||
// display curve, keyed by the window-end's UTC hour).
|
||||
if err := h.store.AccumulateUsage(ctx, userID, date,
|
||||
entry.BytesUp, entry.BytesDown, entry.SessionMinutes,
|
||||
); err != nil {
|
||||
slog.Warn("nodes.Handler.ReportUsage: accumulate failed",
|
||||
"user_id", userID, "err", err)
|
||||
// Fold into the per-user account aggregate (bytes sum, minutes max = 墙上时钟去重).
|
||||
a := byUser[userID]
|
||||
if a == nil {
|
||||
a = &acctAgg{}
|
||||
byUser[userID] = a
|
||||
}
|
||||
if err := h.store.AccumulateHourly(ctx, userID, windowEnd,
|
||||
entry.BytesUp, entry.BytesDown, entry.SessionMinutes,
|
||||
); err != nil {
|
||||
slog.Warn("nodes.Handler.ReportUsage: hourly accumulate failed",
|
||||
"user_id", userID, "err", err)
|
||||
a.bytesUp += entry.BytesUp
|
||||
a.bytesDown += entry.BytesDown
|
||||
if entry.SessionMinutes > a.minutes {
|
||||
a.minutes = entry.SessionMinutes
|
||||
}
|
||||
// Per-device attribution (only when the dp_uuid maps to a registered device;
|
||||
// Per-device attribution (per entry — each device's own bytes/minutes;
|
||||
// deviceID==0 means a legacy account-level credential — no device dimension).
|
||||
if deviceID > 0 {
|
||||
if err := h.store.AccumulateDeviceUsage(ctx, userID, deviceID, date,
|
||||
@@ -340,5 +344,16 @@ func (h *Handler) ReportUsage(ctx context.Context, req *agentv1.UsageReport) (*a
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Flush the account-level rollup once per user (deduped wall-clock minutes):
|
||||
// daily (quota/today) + hourly (tz-aware display curve, keyed by window-end's UTC hour).
|
||||
for userID, a := range byUser {
|
||||
if err := h.store.AccumulateUsage(ctx, userID, date, a.bytesUp, a.bytesDown, a.minutes); err != nil {
|
||||
slog.Warn("nodes.Handler.ReportUsage: accumulate failed", "user_id", userID, "err", err)
|
||||
}
|
||||
if err := h.store.AccumulateHourly(ctx, userID, windowEnd, a.bytesUp, a.bytesDown, a.minutes); err != nil {
|
||||
slog.Warn("nodes.Handler.ReportUsage: hourly accumulate failed", "user_id", userID, "err", err)
|
||||
}
|
||||
}
|
||||
return &agentv1.UsageAck{}, nil
|
||||
}
|
||||
|
||||
@@ -109,6 +109,11 @@ type NodeStore interface {
|
||||
// date — the basis for the GB 综合配额 connect gate. 0 when no usage yet.
|
||||
AccountDayBytes(ctx context.Context, userID int64, date time.Time) (int64, error)
|
||||
|
||||
// AccountDayMinutes returns the account's minutes_used and ad_bonus_minutes
|
||||
// for userID on date — the basis for the免费版分钟配额 connect gate. Both 0
|
||||
// when no usage row exists yet. Quota is account-wide (shared across devices).
|
||||
AccountDayMinutes(ctx context.Context, userID int64, date time.Time) (used, bonus int, err error)
|
||||
|
||||
// CountActiveDevices counts the user's devices seen since cutoff (active). Used
|
||||
// by the connect device-limit backstop; stale rows are excluded.
|
||||
CountActiveDevices(ctx context.Context, userID int64, cutoff time.Time) (int, error)
|
||||
@@ -478,6 +483,22 @@ func (s *SQLNodeStore) AccountDayBytes(ctx context.Context, userID int64, date t
|
||||
return total.Int64, nil
|
||||
}
|
||||
|
||||
// AccountDayMinutes returns the account's minutes_used and ad_bonus_minutes for
|
||||
// the day (0,0 when no usage row yet).
|
||||
func (s *SQLNodeStore) AccountDayMinutes(ctx context.Context, userID int64, date time.Time) (used, bonus int, err error) {
|
||||
err = s.db.QueryRowContext(ctx,
|
||||
`SELECT minutes_used, ad_bonus_minutes FROM usage_daily WHERE user_id = ? AND date = ?`,
|
||||
userID, date.Format("2006-01-02"),
|
||||
).Scan(&used, &bonus)
|
||||
if err == sql.ErrNoRows {
|
||||
return 0, 0, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("nodes.SQLNodeStore.AccountDayMinutes: %w", err)
|
||||
}
|
||||
return used, bonus, nil
|
||||
}
|
||||
|
||||
// CountActiveDevices counts the user's devices seen within the active window
|
||||
// (last_seen > cutoff). Mirrors devices.Store.CountActiveDevices for the connect
|
||||
// backstop; stale/never-seen rows are excluded.
|
||||
|
||||
@@ -29,8 +29,8 @@ func TestSQLiteMigrateUpDown(t *testing.T) {
|
||||
if dirty {
|
||||
t.Fatalf("schema dirty after MigrateUp")
|
||||
}
|
||||
if v != 19 {
|
||||
t.Errorf("version = %d, want 19", v)
|
||||
if v != 20 {
|
||||
t.Errorf("version = %d, want 20", v)
|
||||
}
|
||||
|
||||
// 2. Core tables exist.
|
||||
|
||||
@@ -58,6 +58,51 @@ func TestSQLite_UsageAccumulate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// AddAdBonusMinutes 是免费版累加式看广告加时的核心原语:每次广告 +N 分钟,
|
||||
// 封顶 ceiling,返回新总额与本次实际加时(封顶后为 0)。
|
||||
func TestSQLite_AddAdBonusMinutes(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db := openSQLite(t)
|
||||
us := usage.NewStore(db)
|
||||
day := time.Date(2026, 6, 30, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
// First ad on a fresh day → insert row, bonus 10.
|
||||
newBonus, granted, err := us.AddAdBonusMinutes(ctx, 7, day, 10, 25)
|
||||
if err != nil || newBonus != 10 || granted != 10 {
|
||||
t.Fatalf("first: newBonus=%d granted=%d err=%v, want 10/10", newBonus, granted, err)
|
||||
}
|
||||
|
||||
// Second ad → accumulate to 20.
|
||||
newBonus, granted, err = us.AddAdBonusMinutes(ctx, 7, day, 10, 25)
|
||||
if err != nil || newBonus != 20 || granted != 10 {
|
||||
t.Fatalf("second: newBonus=%d granted=%d err=%v, want 20/10", newBonus, granted, err)
|
||||
}
|
||||
|
||||
// Third ad → clamped at ceiling 25, so only +5 granted.
|
||||
newBonus, granted, err = us.AddAdBonusMinutes(ctx, 7, day, 10, 25)
|
||||
if err != nil || newBonus != 25 || granted != 5 {
|
||||
t.Fatalf("third: newBonus=%d granted=%d err=%v, want 25/5", newBonus, granted, err)
|
||||
}
|
||||
|
||||
// Fourth ad → already at ceiling, 0 granted.
|
||||
newBonus, granted, err = us.AddAdBonusMinutes(ctx, 7, day, 10, 25)
|
||||
if err != nil || newBonus != 25 || granted != 0 {
|
||||
t.Fatalf("fourth: newBonus=%d granted=%d err=%v, want 25/0", newBonus, granted, err)
|
||||
}
|
||||
|
||||
// Existing usage_daily columns are preserved alongside the bonus.
|
||||
if err := us.AggregateUsage(ctx, 7, day, 0, 0, 4); err != nil {
|
||||
t.Fatalf("aggregate: %v", err)
|
||||
}
|
||||
d, err := us.GetDay(ctx, 7, day)
|
||||
if err != nil || d == nil {
|
||||
t.Fatalf("getday: %v", err)
|
||||
}
|
||||
if d.AdBonusMinutes != 25 || d.MinutesUsed != 4 {
|
||||
t.Errorf("getday wrong: bonus=%d used=%d, want 25/4", d.AdBonusMinutes, d.MinutesUsed)
|
||||
}
|
||||
}
|
||||
|
||||
// HasActiveSession 是「近实时远程下线」的服务端判据:有非吊销会话=在线,
|
||||
// 强制退出(RevokeByDevice)后=离线 → 客户端轮询到即登出。
|
||||
func TestSQLite_SessionHasActiveSession(t *testing.T) {
|
||||
|
||||
@@ -41,6 +41,19 @@ type AdVerifier interface {
|
||||
Provider() string
|
||||
}
|
||||
|
||||
// DevVerifier is a placeholder AdVerifier that accepts any receipt. It exists
|
||||
// so the免费版看广告加时 flow can be exercised end-to-end with the client's
|
||||
// placeholder ad dialog before a real ad SDK (AdMob SSV) is wired in. Nonce
|
||||
// replay protection still applies at the service layer, so a token can only be
|
||||
// redeemed once. MUST NOT be used in production with real ad revenue.
|
||||
type DevVerifier struct{}
|
||||
|
||||
// Verify always succeeds.
|
||||
func (DevVerifier) Verify(context.Context, AdVerifyRequest) error { return nil }
|
||||
|
||||
// Provider names this placeholder verifier.
|
||||
func (DevVerifier) Provider() string { return "dev" }
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// AdMob Server-Side Verification (SSV)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
@@ -144,9 +144,16 @@ type adsUnlockRequest struct {
|
||||
AdToken string `json:"ad_token"`
|
||||
}
|
||||
|
||||
// ServeHTTP implements http.Handler. On success it returns 204 No Content
|
||||
// (matching the OpenAPI contract), including the idempotent already-unlocked
|
||||
// case.
|
||||
// adsUnlockResponse reports the minutes granted by this rewarded-ad view and
|
||||
// the account's new remaining minutes for today, so the client can refresh its
|
||||
// quota without a second /me round-trip.
|
||||
type adsUnlockResponse struct {
|
||||
GrantedMinutes int `json:"granted_minutes"`
|
||||
MinutesRemaining int `json:"minutes_remaining"`
|
||||
}
|
||||
|
||||
// ServeHTTP implements http.Handler. On success it returns 200 with the granted
|
||||
// minutes and new remaining quota (免费版累加式看广告加时).
|
||||
func (h *AdsUnlockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
@@ -168,13 +175,15 @@ func (h *AdsUnlockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
_, apiErr := h.svc.UnlockAd(r.Context(), userID, req.DeviceID, req.AdToken)
|
||||
granted, remaining, apiErr := h.svc.UnlockAd(r.Context(), userID, req.DeviceID, req.AdToken)
|
||||
if apiErr != nil {
|
||||
apierr.WriteJSON(w, adsErrorStatus(apiErr.Code), apiErr)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(adsUnlockResponse{GrantedMinutes: granted, MinutesRemaining: remaining})
|
||||
}
|
||||
|
||||
// adsErrorStatus maps an ads-unlock error code to an HTTP status.
|
||||
|
||||
@@ -11,16 +11,16 @@ import (
|
||||
const defaultFreeDailyMinutes = 10
|
||||
|
||||
// CheckFreeConnect enforces the free-plan connect gate and returns the user's
|
||||
// remaining minutes for today (UTC). It is called by #5's connect endpoint to
|
||||
// derive the free credential's TTL.
|
||||
// remaining minutes for today (UTC). The quota is account-wide (shared across
|
||||
// all devices).
|
||||
//
|
||||
// Rules:
|
||||
// Rules (免费版累加式看广告加时):
|
||||
// - plan.ad_gate == false (pro/team): not minute-gated. Returns Unlimited
|
||||
// when daily_minutes is NULL, otherwise the remaining minutes for the day.
|
||||
// - plan.ad_gate == true (free): today's ad_unlocked_at must be set and
|
||||
// minutes_used must be below daily_minutes (free = 10). Returns the
|
||||
// remaining minutes; otherwise a bilingual semantic error
|
||||
// (AD_NOT_UNLOCKED / QUOTA_EXHAUSTED).
|
||||
// - plan.ad_gate == true (free): the day's allowance = daily_minutes (free=10)
|
||||
// + ad_bonus_minutes (accumulated by watching rewarded ads). No ad is
|
||||
// required to connect at all — the base 10 minutes are always available.
|
||||
// Returns allowance − minutes_used; QUOTA_EXHAUSTED when that reaches 0.
|
||||
func (svc *Service) CheckFreeConnect(ctx context.Context, userID int64) (remainingMinutes int, apiErr *apierr.Error) {
|
||||
plan, err := svc.store.EffectivePlan(ctx, userID)
|
||||
if err != nil {
|
||||
@@ -51,16 +51,19 @@ func (svc *Service) CheckFreeConnect(ctx context.Context, userID int64) (remaini
|
||||
return remaining, nil
|
||||
}
|
||||
|
||||
// Free plan: require ad unlock + remaining minutes.
|
||||
// Free plan: allowance = base daily + ad bonus; remaining = allowance − used.
|
||||
day, err := svc.store.GetDay(ctx, userID, utcToday())
|
||||
if err != nil {
|
||||
return 0, apierr.ErrInternal
|
||||
}
|
||||
if day == nil || !day.AdUnlockedAt.Valid {
|
||||
return 0, apierr.ErrAdNotUnlocked
|
||||
allowance := limit
|
||||
used := 0
|
||||
if day != nil {
|
||||
allowance = limit + day.AdBonusMinutes
|
||||
used = day.MinutesUsed
|
||||
}
|
||||
if day.MinutesUsed >= limit {
|
||||
if used >= allowance {
|
||||
return 0, apierr.ErrQuotaExhausted
|
||||
}
|
||||
return limit - day.MinutesUsed, nil
|
||||
return allowance - used, nil
|
||||
}
|
||||
|
||||
@@ -13,6 +13,14 @@ import (
|
||||
// nowFunc is overridable in tests to pin "today".
|
||||
var nowFunc = time.Now
|
||||
|
||||
const (
|
||||
// adBonusPerAd is how many minutes one rewarded-ad view grants (免费版加时).
|
||||
adBonusPerAd = 10
|
||||
// adDailyBonusCeiling caps the total ad-granted minutes per UTC day, so the
|
||||
// free tier can't be extended indefinitely by ad-watching.
|
||||
adDailyBonusCeiling = 120
|
||||
)
|
||||
|
||||
// utcToday returns the current UTC calendar date (time truncated).
|
||||
func utcToday() time.Time {
|
||||
n := nowFunc().UTC()
|
||||
@@ -159,8 +167,10 @@ func (svc *Service) DeviceUsage(ctx context.Context, userID int64, days int) ([]
|
||||
// TodaySummary is the /v1/me today_usage block.
|
||||
type TodaySummary struct {
|
||||
MinutesUsed int `json:"minutes_used"`
|
||||
MinutesCap *int `json:"minutes_cap"` // 当日额度 = daily + ad_bonus; nil = unlimited
|
||||
MinutesRemaining *int `json:"minutes_remaining"` // nil = unlimited (pro/team)
|
||||
AdUnlocked bool `json:"ad_unlocked"`
|
||||
AdBonusMinutes int `json:"ad_bonus_minutes"` // 当日已通过看广告累加的分钟
|
||||
AdUnlocked bool `json:"ad_unlocked"` // 历史字段:当日曾解锁过(bonus>0)
|
||||
}
|
||||
|
||||
// TodaySummary returns the current user's usage summary for today (UTC),
|
||||
@@ -176,34 +186,38 @@ func (svc *Service) TodaySummary(ctx context.Context, userID int64) (*TodaySumma
|
||||
}
|
||||
|
||||
used := 0
|
||||
adUnlocked := false
|
||||
bonus := 0
|
||||
if day != nil {
|
||||
used = day.MinutesUsed
|
||||
adUnlocked = day.AdUnlockedAt.Valid
|
||||
bonus = day.AdBonusMinutes
|
||||
}
|
||||
|
||||
out := &TodaySummary{MinutesUsed: used, AdUnlocked: adUnlocked}
|
||||
out := &TodaySummary{MinutesUsed: used, AdBonusMinutes: bonus, AdUnlocked: bonus > 0}
|
||||
if plan.DailyMinutes.Valid {
|
||||
remaining := int(plan.DailyMinutes.Int64) - used
|
||||
cap := int(plan.DailyMinutes.Int64) + bonus
|
||||
remaining := cap - used
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
out.MinutesCap = &cap
|
||||
out.MinutesRemaining = &remaining
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UnlockAd verifies a rewarded-ad receipt and records the day's ad-unlock.
|
||||
// UnlockAd verifies a rewarded-ad receipt and grants additional free minutes.
|
||||
//
|
||||
// Flow: validate inputs → verify the receipt with the ad network → consume the
|
||||
// ad_token as a one-time nonce (replay-protected) → set ad_unlocked_at. A
|
||||
// second unlock on a day already unlocked is idempotent (alreadyUnlocked=true).
|
||||
func (svc *Service) UnlockAd(ctx context.Context, userID int64, deviceID, adToken string) (alreadyUnlocked bool, apiErr *apierr.Error) {
|
||||
// ad_token as a one-time nonce (replay-protected) → add adBonusPerAd minutes to
|
||||
// the day's ad bonus (capped at adDailyBonusCeiling). It returns the granted
|
||||
// minutes (0 when the daily ceiling was already reached) and the new remaining
|
||||
// minutes for today so the client can refresh its quota immediately.
|
||||
func (svc *Service) UnlockAd(ctx context.Context, userID int64, deviceID, adToken string) (granted, remaining int, apiErr *apierr.Error) {
|
||||
if deviceID == "" || adToken == "" {
|
||||
return false, apierr.ErrBadRequest
|
||||
return 0, 0, apierr.ErrBadRequest
|
||||
}
|
||||
if svc.verifier == nil {
|
||||
return false, apierr.ErrInternal
|
||||
return 0, 0, apierr.ErrInternal
|
||||
}
|
||||
|
||||
// 1. Authenticate the receipt with the ad network.
|
||||
@@ -212,22 +226,32 @@ func (svc *Service) UnlockAd(ctx context.Context, userID int64, deviceID, adToke
|
||||
DeviceID: deviceID,
|
||||
AdToken: adToken,
|
||||
}); err != nil {
|
||||
return false, apierr.ErrAdVerifyFailed
|
||||
return 0, 0, apierr.ErrAdVerifyFailed
|
||||
}
|
||||
|
||||
// 2. One-time nonce: a genuine receipt may only be redeemed once.
|
||||
if dup, err := svc.consumeAdNonce(ctx, adToken); err != nil {
|
||||
return false, apierr.ErrInternal
|
||||
return 0, 0, apierr.ErrInternal
|
||||
} else if dup {
|
||||
return false, apierr.ErrAdReplay
|
||||
return 0, 0, apierr.ErrAdReplay
|
||||
}
|
||||
|
||||
// 3. Record the unlock (idempotent per UTC day).
|
||||
already, err := svc.store.MarkAdUnlocked(ctx, userID, utcToday())
|
||||
if err != nil {
|
||||
return false, apierr.ErrInternal
|
||||
// 3. Grant the reward: add adBonusPerAd minutes, capped at the daily ceiling.
|
||||
_, g, addErr := svc.store.AddAdBonusMinutes(ctx, userID, utcToday(), adBonusPerAd, adDailyBonusCeiling)
|
||||
if addErr != nil {
|
||||
return 0, 0, apierr.ErrInternal
|
||||
}
|
||||
return already, nil
|
||||
granted = g
|
||||
|
||||
// 4. Recompute remaining for the client to refresh its quota immediately.
|
||||
summary, sErr := svc.TodaySummary(ctx, userID)
|
||||
if sErr != nil {
|
||||
return 0, 0, sErr
|
||||
}
|
||||
if summary.MinutesRemaining != nil {
|
||||
remaining = *summary.MinutesRemaining
|
||||
}
|
||||
return granted, remaining, nil
|
||||
}
|
||||
|
||||
// consumeAdNonce atomically records the ad_token so it cannot be reused.
|
||||
|
||||
@@ -29,11 +29,12 @@ type Plan struct {
|
||||
// minute counts plus the ad-unlock timestamp — never destinations or DNS, per
|
||||
// the no-log policy.
|
||||
type DailyUsage struct {
|
||||
Date time.Time
|
||||
BytesUp uint64
|
||||
BytesDown uint64
|
||||
MinutesUsed int
|
||||
AdUnlockedAt sql.NullTime
|
||||
Date time.Time
|
||||
BytesUp uint64
|
||||
BytesDown uint64
|
||||
MinutesUsed int
|
||||
AdBonusMinutes int // 当日看广告累加解锁的额外分钟(免费版加时)
|
||||
AdUnlockedAt sql.NullTime
|
||||
}
|
||||
|
||||
// Store wraps a *sql.DB and exposes the usage_daily / plans / users queries the
|
||||
@@ -86,7 +87,7 @@ func (s *Store) LookupUserIDByDPUUID(ctx context.Context, dpUUID string) (int64,
|
||||
// filled here; zero-filling is the handler's responsibility.
|
||||
func (s *Store) GetUsageRange(ctx context.Context, userID int64, from, to time.Time) ([]DailyUsage, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT date, bytes_up, bytes_down, minutes_used, ad_unlocked_at
|
||||
`SELECT date, bytes_up, bytes_down, minutes_used, ad_bonus_minutes, ad_unlocked_at
|
||||
FROM usage_daily
|
||||
WHERE user_id = ? AND date BETWEEN ? AND ?
|
||||
ORDER BY date ASC`,
|
||||
@@ -99,7 +100,7 @@ func (s *Store) GetUsageRange(ctx context.Context, userID int64, from, to time.T
|
||||
var out []DailyUsage
|
||||
for rows.Next() {
|
||||
var u DailyUsage
|
||||
if err := rows.Scan(&u.Date, &u.BytesUp, &u.BytesDown, &u.MinutesUsed, &u.AdUnlockedAt); err != nil {
|
||||
if err := rows.Scan(&u.Date, &u.BytesUp, &u.BytesDown, &u.MinutesUsed, &u.AdBonusMinutes, &u.AdUnlockedAt); err != nil {
|
||||
return nil, fmt.Errorf("store.GetUsageRange scan: %w", err)
|
||||
}
|
||||
out = append(out, u)
|
||||
@@ -212,11 +213,11 @@ func (s *Store) DeviceUsageRange(ctx context.Context, userID int64, from, to tim
|
||||
func (s *Store) GetDay(ctx context.Context, userID int64, day time.Time) (*DailyUsage, error) {
|
||||
var u DailyUsage
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT date, bytes_up, bytes_down, minutes_used, ad_unlocked_at
|
||||
`SELECT date, bytes_up, bytes_down, minutes_used, ad_bonus_minutes, ad_unlocked_at
|
||||
FROM usage_daily
|
||||
WHERE user_id = ? AND date = ?`,
|
||||
userID, day.UTC().Format(dateLayout)).
|
||||
Scan(&u.Date, &u.BytesUp, &u.BytesDown, &u.MinutesUsed, &u.AdUnlockedAt)
|
||||
Scan(&u.Date, &u.BytesUp, &u.BytesDown, &u.MinutesUsed, &u.AdBonusMinutes, &u.AdUnlockedAt)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -226,10 +227,75 @@ func (s *Store) GetDay(ctx context.Context, userID int64, day time.Time) (*Daily
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// AddAdBonusMinutes adds `add` minutes to usage_daily.ad_bonus_minutes for
|
||||
// (userID, day), capped so the day's total bonus never exceeds `ceiling`. It
|
||||
// returns the new bonus total and the minutes actually granted this call
|
||||
// (granted = newBonus − previous, i.e. 0 when the ceiling was already reached).
|
||||
// Runs inside a transaction with SELECT … FOR UPDATE so concurrent ad-unlocks
|
||||
// accumulate correctly (免费版累加式看广告加时).
|
||||
//
|
||||
// This is the additive successor to MarkAdUnlocked's per-day boolean unlock:
|
||||
// each rewarded ad grants +add minutes (repeatable) up to the daily ceiling.
|
||||
func (s *Store) AddAdBonusMinutes(ctx context.Context, userID int64, day time.Time, add, ceiling int) (newBonus, granted int, err error) {
|
||||
d := day.UTC().Format(dateLayout)
|
||||
|
||||
tx, err := s.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("store.AddAdBonusMinutes begin: %w", err)
|
||||
}
|
||||
committed := false
|
||||
defer func() {
|
||||
if !committed {
|
||||
_ = tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
var cur int
|
||||
row := tx.QueryRowContext(ctx,
|
||||
`SELECT ad_bonus_minutes FROM usage_daily WHERE user_id = ? AND date = ? `+s.dialect.LockForUpdate(),
|
||||
userID, d)
|
||||
switch scanErr := row.Scan(&cur); scanErr {
|
||||
case nil:
|
||||
newBonus = cur + add
|
||||
if ceiling > 0 && newBonus > ceiling {
|
||||
newBonus = ceiling
|
||||
}
|
||||
if newBonus != cur {
|
||||
if _, uErr := tx.ExecContext(ctx,
|
||||
`UPDATE usage_daily SET ad_bonus_minutes = ? WHERE user_id = ? AND date = ?`,
|
||||
newBonus, userID, d); uErr != nil {
|
||||
return 0, 0, fmt.Errorf("store.AddAdBonusMinutes update: %w", uErr)
|
||||
}
|
||||
}
|
||||
case sql.ErrNoRows:
|
||||
cur = 0
|
||||
newBonus = add
|
||||
if ceiling > 0 && newBonus > ceiling {
|
||||
newBonus = ceiling
|
||||
}
|
||||
if _, iErr := tx.ExecContext(ctx,
|
||||
`INSERT INTO usage_daily (user_id, date, ad_bonus_minutes) VALUES (?, ?, ?)`,
|
||||
userID, d, newBonus); iErr != nil {
|
||||
return 0, 0, fmt.Errorf("store.AddAdBonusMinutes insert: %w", iErr)
|
||||
}
|
||||
default:
|
||||
return 0, 0, fmt.Errorf("store.AddAdBonusMinutes select: %w", scanErr)
|
||||
}
|
||||
|
||||
if cErr := tx.Commit(); cErr != nil {
|
||||
return 0, 0, fmt.Errorf("store.AddAdBonusMinutes commit: %w", cErr)
|
||||
}
|
||||
committed = true
|
||||
return newBonus, newBonus - cur, nil
|
||||
}
|
||||
|
||||
// MarkAdUnlocked sets usage_daily.ad_unlocked_at for (userID, day) to now if it
|
||||
// is not already set. It returns alreadyUnlocked=true when the day was already
|
||||
// unlocked (making a second call idempotent). Runs inside a transaction with
|
||||
// SELECT … FOR UPDATE to be safe under concurrent unlock attempts.
|
||||
//
|
||||
// Deprecated: the免费版 ad model moved from a per-day boolean unlock to additive
|
||||
// minutes (see AddAdBonusMinutes). Retained only for backward compatibility.
|
||||
func (s *Store) MarkAdUnlocked(ctx context.Context, userID int64, day time.Time) (alreadyUnlocked bool, err error) {
|
||||
d := day.UTC().Format(dateLayout)
|
||||
now := time.Now().UTC()
|
||||
|
||||
@@ -297,22 +297,23 @@ func TestIntAggregateUnknownDPUUIDDropped(t *testing.T) {
|
||||
// Quota (CheckFreeConnect)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
func TestIntQuotaFreeNotUnlocked(t *testing.T) {
|
||||
func TestIntQuotaFreeBaseNoAd(t *testing.T) {
|
||||
db := setupMySQL(t)
|
||||
svc := usage.NewService(usage.NewStore(db), nil, fakeVerifier{ok: true}, time.Hour)
|
||||
|
||||
uid := createUser(t, db, "dp-q1") // no subscription → free plan
|
||||
|
||||
_, apiErr := svc.CheckFreeConnect(context.Background(), uid)
|
||||
if apiErr == nil || apiErr.Code != "AD_NOT_UNLOCKED" {
|
||||
t.Fatalf("expected AD_NOT_UNLOCKED, got %v", apiErr)
|
||||
// 免费版基础 10 分钟无需看广告即可连接(广告只用于加时)。
|
||||
rem, apiErr := svc.CheckFreeConnect(context.Background(), uid)
|
||||
if apiErr != nil {
|
||||
t.Fatalf("free base connect should succeed without ad, got %v", apiErr)
|
||||
}
|
||||
if apiErr.MessageZH == "" || apiErr.MessageEn == "" {
|
||||
t.Error("expected bilingual error messages")
|
||||
if rem != 10 {
|
||||
t.Errorf("remaining=%d, want 10 (base free minutes)", rem)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntQuotaFreeUnlockedRemainingDecrements(t *testing.T) {
|
||||
func TestIntQuotaFreeAdBonusAccumulates(t *testing.T) {
|
||||
db := setupMySQL(t)
|
||||
store := usage.NewStore(db)
|
||||
agg := usage.NewAggregator(store, nil, time.Minute, time.Minute)
|
||||
@@ -320,23 +321,26 @@ func TestIntQuotaFreeUnlockedRemainingDecrements(t *testing.T) {
|
||||
|
||||
uid := createUser(t, db, "dp-q2")
|
||||
|
||||
if _, err := store.MarkAdUnlocked(context.Background(), uid, time.Now().UTC()); err != nil {
|
||||
t.Fatalf("unlock: %v", err)
|
||||
}
|
||||
|
||||
// Base free minutes (no ad).
|
||||
rem, apiErr := svc.CheckFreeConnect(context.Background(), uid)
|
||||
if apiErr != nil {
|
||||
t.Fatalf("unexpected err: %v", apiErr)
|
||||
}
|
||||
if rem != 10 {
|
||||
t.Errorf("remaining=%d, want 10", rem)
|
||||
if apiErr != nil || rem != 10 {
|
||||
t.Fatalf("base: rem=%d err=%v, want 10", rem, apiErr)
|
||||
}
|
||||
|
||||
// Consume 4 minutes.
|
||||
// Watch an ad → +10 bonus → allowance 20.
|
||||
if _, _, err := store.AddAdBonusMinutes(context.Background(), uid, time.Now().UTC(), 10, 120); err != nil {
|
||||
t.Fatalf("add bonus: %v", err)
|
||||
}
|
||||
rem, _ = svc.CheckFreeConnect(context.Background(), uid)
|
||||
if rem != 20 {
|
||||
t.Errorf("after ad: remaining=%d, want 20", rem)
|
||||
}
|
||||
|
||||
// Consume 4 minutes → 16.
|
||||
agg.ReportUsage(context.Background(), usage.Report{DPUUID: "dp-q2", Minutes: 4})
|
||||
rem, _ = svc.CheckFreeConnect(context.Background(), uid)
|
||||
if rem != 6 {
|
||||
t.Errorf("after 4 min: remaining=%d, want 6", rem)
|
||||
if rem != 16 {
|
||||
t.Errorf("after 4 min: remaining=%d, want 16", rem)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,7 +350,7 @@ func TestIntQuotaFreeExhausted(t *testing.T) {
|
||||
svc := usage.NewService(store, nil, fakeVerifier{ok: true}, time.Hour)
|
||||
|
||||
uid := createUser(t, db, "dp-q3")
|
||||
store.MarkAdUnlocked(context.Background(), uid, time.Now().UTC())
|
||||
// Base 10 minutes fully consumed, no ad bonus → exhausted.
|
||||
store.AggregateUsage(context.Background(), uid, time.Now().UTC(), 0, 0, 10)
|
||||
|
||||
_, apiErr := svc.CheckFreeConnect(context.Background(), uid)
|
||||
@@ -386,7 +390,7 @@ func TestIntAdsUnlockForgedRejected(t *testing.T) {
|
||||
svc := usage.NewService(usage.NewStore(db), rdb, fakeVerifier{ok: false}, time.Hour)
|
||||
|
||||
uid := createUser(t, db, "dp-ad1")
|
||||
_, apiErr := svc.UnlockAd(context.Background(), uid, "device-1", "forged-token")
|
||||
_, _, apiErr := svc.UnlockAd(context.Background(), uid, "device-1", "forged-token")
|
||||
if apiErr == nil || apiErr.Code != "AD_VERIFY_FAILED" {
|
||||
t.Fatalf("expected AD_VERIFY_FAILED, got %v", apiErr)
|
||||
}
|
||||
@@ -398,33 +402,35 @@ func TestIntAdsUnlockReplayRejected(t *testing.T) {
|
||||
svc := usage.NewService(usage.NewStore(db), rdb, fakeVerifier{ok: true}, time.Hour)
|
||||
|
||||
uid := createUser(t, db, "dp-ad2")
|
||||
already, apiErr := svc.UnlockAd(context.Background(), uid, "device-1", "token-xyz")
|
||||
if apiErr != nil || already {
|
||||
t.Fatalf("first unlock: already=%v err=%v", already, apiErr)
|
||||
granted, _, apiErr := svc.UnlockAd(context.Background(), uid, "device-1", "token-xyz")
|
||||
if apiErr != nil || granted != 10 {
|
||||
t.Fatalf("first unlock: granted=%d err=%v, want granted=10", granted, apiErr)
|
||||
}
|
||||
// Same token again → replay.
|
||||
_, apiErr = svc.UnlockAd(context.Background(), uid, "device-1", "token-xyz")
|
||||
_, _, apiErr = svc.UnlockAd(context.Background(), uid, "device-1", "token-xyz")
|
||||
if apiErr == nil || apiErr.Code != "AD_TOKEN_REPLAY" {
|
||||
t.Fatalf("expected AD_TOKEN_REPLAY, got %v", apiErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntAdsUnlockSecondTimeIdempotent(t *testing.T) {
|
||||
func TestIntAdsUnlockAccumulates(t *testing.T) {
|
||||
db := setupMySQL(t)
|
||||
rdb := setupRedis(t)
|
||||
svc := usage.NewService(usage.NewStore(db), rdb, fakeVerifier{ok: true}, time.Hour)
|
||||
|
||||
uid := createUser(t, db, "dp-ad3")
|
||||
if _, apiErr := svc.UnlockAd(context.Background(), uid, "d", "tok-1"); apiErr != nil {
|
||||
t.Fatalf("first unlock: %v", apiErr)
|
||||
// 累加式:每次不同 token 各加 10 分钟,而非幂等。
|
||||
g1, _, apiErr := svc.UnlockAd(context.Background(), uid, "d", "tok-1")
|
||||
if apiErr != nil || g1 != 10 {
|
||||
t.Fatalf("first unlock: granted=%d err=%v, want 10", g1, apiErr)
|
||||
}
|
||||
// Different (valid) token, same day → idempotent success.
|
||||
already, apiErr := svc.UnlockAd(context.Background(), uid, "d", "tok-2")
|
||||
if apiErr != nil {
|
||||
t.Fatalf("second unlock err: %v", apiErr)
|
||||
g2, rem, apiErr := svc.UnlockAd(context.Background(), uid, "d", "tok-2")
|
||||
if apiErr != nil || g2 != 10 {
|
||||
t.Fatalf("second unlock: granted=%d err=%v, want 10", g2, apiErr)
|
||||
}
|
||||
if !already {
|
||||
t.Error("expected already-unlocked idempotent success")
|
||||
// allowance = 10 base + 20 bonus, used 0 → remaining 30.
|
||||
if rem != 30 {
|
||||
t.Errorf("remaining after 2 ads=%d, want 30", rem)
|
||||
}
|
||||
|
||||
// Exactly one unlock timestamp.
|
||||
@@ -505,17 +511,22 @@ func TestIntTodaySummary(t *testing.T) {
|
||||
store := usage.NewStore(db)
|
||||
svc := usage.NewService(store, nil, nil, time.Hour)
|
||||
|
||||
// Free user: limited + ad flag.
|
||||
// Free user: base 10 + ad bonus 10 = cap 20; used 3 → remaining 17.
|
||||
uFree := createUser(t, db, "dp-sf")
|
||||
store.MarkAdUnlocked(context.Background(), uFree, time.Now().UTC())
|
||||
if _, _, err := store.AddAdBonusMinutes(context.Background(), uFree, time.Now().UTC(), 10, 120); err != nil {
|
||||
t.Fatalf("add bonus: %v", err)
|
||||
}
|
||||
store.AggregateUsage(context.Background(), uFree, time.Now().UTC(), 0, 0, 3)
|
||||
|
||||
sum, apiErr := svc.TodaySummary(context.Background(), uFree)
|
||||
if apiErr != nil {
|
||||
t.Fatalf("summary: %v", apiErr)
|
||||
}
|
||||
if sum.MinutesUsed != 3 || sum.MinutesRemaining == nil || *sum.MinutesRemaining != 7 || !sum.AdUnlocked {
|
||||
t.Errorf("free summary wrong: %+v (remaining=%v)", sum, sum.MinutesRemaining)
|
||||
if sum.MinutesUsed != 3 ||
|
||||
sum.MinutesCap == nil || *sum.MinutesCap != 20 ||
|
||||
sum.MinutesRemaining == nil || *sum.MinutesRemaining != 17 ||
|
||||
sum.AdBonusMinutes != 10 || !sum.AdUnlocked {
|
||||
t.Errorf("free summary wrong: %+v (cap=%v remaining=%v)", sum, sum.MinutesCap, sum.MinutesRemaining)
|
||||
}
|
||||
|
||||
// Pro user: unlimited (nil remaining).
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE usage_daily DROP COLUMN ad_bonus_minutes;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- 免费版累加式看广告加时:当日通过看激励视频额外解锁的分钟数(与 minutes_used 相对)。
|
||||
-- 当日免费额度 = plans.daily_minutes + usage_daily.ad_bonus_minutes;剩余 = 额度 − minutes_used。
|
||||
-- 历史列 ad_unlocked_at(布尔式当日解锁)保留但不再用于卡控。
|
||||
ALTER TABLE usage_daily ADD COLUMN ad_bonus_minutes INT NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE usage_daily DROP COLUMN ad_bonus_minutes;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- 免费版累加式看广告加时:当日通过看激励视频额外解锁的分钟数(与 minutes_used 相对)。
|
||||
-- 当日免费额度 = plans.daily_minutes + usage_daily.ad_bonus_minutes;剩余 = 额度 − minutes_used。
|
||||
-- 历史列 ad_unlocked_at(布尔式当日解锁)保留但不再用于卡控。
|
||||
ALTER TABLE usage_daily ADD COLUMN ad_bonus_minutes INTEGER NOT NULL DEFAULT 0;
|
||||
Reference in New Issue
Block a user