cleaning up
This commit is contained in:
1 parent
c1ec77a075
commit
75cf59f22c
12 files changed
+214
-322
No files matched your search
@@ -7,12 +7,7 @@ import 'package:revoltvpn/logic/crypto_service.dart';
|
||||
import 'package:revoltvpn/logic/hivemind_service.dart';
|
||||
import 'package:revoltvpn/logic/app_config.dart';
|
||||
|
||||
/// AdManager manages the lifecycle of rewarded video ads.
|
||||
///
|
||||
/// When [adsEnabled] is false (pre-launch mode) all ad operations are
|
||||
/// silently skipped — the app connects without any ad requirement.
|
||||
class AdManager extends ChangeNotifier {
|
||||
/// Flip to `true` after Google Play launch when real ads are wired up.
|
||||
static const bool adsEnabled = false;
|
||||
|
||||
RewardedAd? _rewardedAd;
|
||||
@@ -32,15 +27,9 @@ class AdManager extends ChangeNotifier {
|
||||
if (adsEnabled) preloadAd();
|
||||
}
|
||||
|
||||
/// Loads a rewarded ad in the background and returns a Future when ready.
|
||||
/// Safe to call multiple times — re-entrant calls wait on the same load.
|
||||
/// No-op when [adsEnabled] is false.
|
||||
Future<bool> preloadAd() async {
|
||||
if (!adsEnabled) return true;
|
||||
// If already loaded, return instantly
|
||||
if (_isAdLoaded) return true;
|
||||
|
||||
// If we're already loading one right now, wait for that same request to finish
|
||||
if (_isAdLoading) return _loadCompleter?.future ?? Future.value(false);
|
||||
|
||||
_isAdLoading = true;
|
||||
@@ -84,12 +73,9 @@ class AdManager extends ChangeNotifier {
|
||||
return _loadCompleter!.future;
|
||||
}
|
||||
|
||||
/// Displays the rewarded video ad to the user.
|
||||
/// Returns false immediately when [adsEnabled] is false.
|
||||
Future<bool> showAd(String adType) async {
|
||||
if (!adsEnabled) return false;
|
||||
|
||||
// 1. Ensure the ad is fully loaded before trying to show it
|
||||
if (!_isAdLoaded || _rewardedAd == null) {
|
||||
final loaded = await preloadAd();
|
||||
if (!loaded || _rewardedAd == null) {
|
||||
@@ -98,16 +84,12 @@ class AdManager extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fetch device ID for Server-Side Verification (SSV)
|
||||
final deviceId = await CryptoService.getDeviceId();
|
||||
|
||||
// 3. Generate a connect nonce so the subsequent poll can verify
|
||||
// it's talking to the session created by *this* ad.
|
||||
final nonce = '${Random().nextInt(0x7FFFFFFF)}-${DateTime.now().millisecondsSinceEpoch}';
|
||||
HivemindService.setExpectedNonce(nonce);
|
||||
debugPrint('[AdManager] Ad nonce: $nonce');
|
||||
|
||||
// 4. Build SSV options to send to our Hivemind server via Google's callback
|
||||
final ssvOptions = ServerSideVerificationOptions(
|
||||
customData: jsonEncode({
|
||||
'device_id': deviceId,
|
||||
@@ -118,7 +100,6 @@ class AdManager extends ChangeNotifier {
|
||||
|
||||
Completer<bool> rewardCompleter = Completer<bool>();
|
||||
|
||||
// 4. Setup full screen callbacks to handle dismissal and errors
|
||||
_rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
|
||||
onAdShowedFullScreenContent: (ad) => debugPrint('[AdManager] Ad showing.'),
|
||||
onAdDismissedFullScreenContent: (ad) {
|
||||
@@ -126,10 +107,9 @@ class AdManager extends ChangeNotifier {
|
||||
ad.dispose();
|
||||
_isAdLoaded = false;
|
||||
_rewardedAd = null;
|
||||
// Start loading the next ad immediately
|
||||
preloadAd();
|
||||
if (!rewardCompleter.isCompleted) {
|
||||
rewardCompleter.complete(false); // User closed before earning reward
|
||||
rewardCompleter.complete(false);
|
||||
}
|
||||
},
|
||||
onAdFailedToShowFullScreenContent: (ad, error) {
|
||||
@@ -143,13 +123,11 @@ class AdManager extends ChangeNotifier {
|
||||
},
|
||||
);
|
||||
|
||||
// 5. Show the ad with SSV options
|
||||
// Show with SSV options
|
||||
_rewardedAd!.setServerSideOptions(ssvOptions);
|
||||
await _rewardedAd!.show(
|
||||
onUserEarnedReward: (AdWithoutView ad, RewardItem reward) {
|
||||
debugPrint('[AdManager] Reward earned: ${reward.amount} ${reward.type}');
|
||||
// The SSV callback will hit our server independently. We just need to signal the UI
|
||||
// that the ad was successfully completed.
|
||||
if (!rewardCompleter.isCompleted) {
|
||||
rewardCompleter.complete(true);
|
||||
}
|
||||
|
||||
@@ -10,18 +10,14 @@ class HivemindService {
|
||||
static String? _expectedNonce;
|
||||
static int _currentCallId = 0;
|
||||
|
||||
/// Call this from disconnect to abort any in-progress polling.
|
||||
static void cancel() {
|
||||
_currentCallId++; // bump — any running loop sees a stale ID and exits
|
||||
_currentCallId++;
|
||||
}
|
||||
|
||||
static void setExpectedNonce(String nonce) {
|
||||
_expectedNonce = nonce;
|
||||
}
|
||||
|
||||
/// Tries to fetch the VLESS config from the server.
|
||||
/// Only polls a few times — by the time the ad finishes, the SSV callback
|
||||
/// has usually already fired.
|
||||
static Future<String> fetchConfigWithPolling({
|
||||
void Function(int attempt, int total)? onAttempt,
|
||||
bool skipAdBypass = false,
|
||||
@@ -36,7 +32,7 @@ class HivemindService {
|
||||
|
||||
final url = _url('/session/status?device_id=$deviceId');
|
||||
|
||||
// ── AD BYPASS (debug only) ────────────────────────────────────────
|
||||
// Dev: fake ad callback when running in debug mode.
|
||||
if (kDebugMode && !skipAdBypass) {
|
||||
try {
|
||||
final customData = jsonEncode({'device_id': deviceId, 'nonce': nonce});
|
||||
@@ -77,10 +73,8 @@ class HivemindService {
|
||||
final fp = data['reality_fp'] ?? AppConfig.realityFp;
|
||||
final xhttpPath = data['xhttp_path'] ?? AppConfig.vlessPath;
|
||||
|
||||
// host is intentionally omitted per XHTTP docs:
|
||||
// "建议没事别设" — the server doesn't set host, so it won't check.
|
||||
// Host header not set — server doesn't require it.
|
||||
// Client falls through: host → serverName (SNI) → address.
|
||||
// With Reality SNI = github.com, the Host header blends naturally.
|
||||
final vlessUrl = 'vless://$vlessUuid@$vlessIp:$vlessPort'
|
||||
'?security=${AppConfig.vlessSecurity}'
|
||||
'&type=${AppConfig.vlessType}'
|
||||
@@ -140,7 +134,6 @@ class HivemindService {
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// Builds a URI pointing directly at the server IP — no domain involved.
|
||||
static Uri _url(String path) {
|
||||
return Uri.parse('${AppConfig.hivemindApiBase}$path');
|
||||
}
|
||||
|
||||
@@ -218,7 +218,7 @@ class SessionTimer extends ChangeNotifier {
|
||||
_lastUsedBytes = _usedBytes;
|
||||
|
||||
|
||||
// ── Detect port change (throttle engage / disengage) ──────
|
||||
// Port change — throttle engaged or disengaged
|
||||
final serverPort = data['vless_port'];
|
||||
if (serverPort != null &&
|
||||
_currentPort != null &&
|
||||
|
||||
+86
-210
@@ -8,33 +8,9 @@ import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:revoltvpn/logic/app_config.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
|
||||
/// Result of a manual version check.
|
||||
enum UpdateStatus {
|
||||
upToDate,
|
||||
updateAvailable,
|
||||
checkFailed,
|
||||
}
|
||||
enum UpdateStatus { upToDate, updateAvailable, checkFailed }
|
||||
|
||||
/// How the user installed this app — determines which store link we open.
|
||||
enum InstallSource {
|
||||
playStore,
|
||||
sideload,
|
||||
}
|
||||
|
||||
|
||||
// ##############################################################################
|
||||
// #
|
||||
// APPROACH #1 #
|
||||
// GOOGLE PLAY STORE LINK #
|
||||
// #
|
||||
// Opens the Play Store listing. User taps "Update" in Play Store like #
|
||||
// any normal app. No background downloads, no in-app update package, #
|
||||
// no permissions. Just a URL. #
|
||||
// #
|
||||
// The Play Store page is built from the applicationId: #
|
||||
// https://play.google.com/store/apps/details?id=com.paladinvpn.app #
|
||||
// #
|
||||
// ##############################################################################
|
||||
enum InstallSource { playStore, sideload }
|
||||
|
||||
class PlayStoreUpdater {
|
||||
PlayStoreUpdater._();
|
||||
@@ -42,10 +18,10 @@ class PlayStoreUpdater {
|
||||
static String get _url =>
|
||||
'https://play.google.com/store/apps/details?id=${AppConfig.applicationId}';
|
||||
|
||||
/// Opens the Play Store listing in the Play Store app (or browser fallback).
|
||||
static Future<bool> open() async {
|
||||
try {
|
||||
return await launchUrl(Uri.parse(_url), mode: LaunchMode.externalApplication);
|
||||
return await launchUrl(Uri.parse(_url),
|
||||
mode: LaunchMode.externalApplication);
|
||||
} catch (e) {
|
||||
debugPrint('[Updater] Failed to open Play Store: $e');
|
||||
return false;
|
||||
@@ -53,38 +29,19 @@ class PlayStoreUpdater {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ##############################################################################
|
||||
// #
|
||||
// APPROACH #2 #
|
||||
// GITHUB RELEASES DIRECT #
|
||||
// #
|
||||
// Opens the GitHub releases page. User downloads the APK and Android's #
|
||||
// package installer handles the rest. No permissions, no self-hosting. #
|
||||
// #
|
||||
// The GitHub Releases API (free, public, no auth) is also used as the #
|
||||
// single source of truth for "what is the latest version?" for both paths. #
|
||||
// #
|
||||
// API: GET https://api.github.com/repos/{owner}/{repo}/releases/latest #
|
||||
// #
|
||||
// ##############################################################################
|
||||
|
||||
class GitHubUpdater {
|
||||
GitHubUpdater._();
|
||||
|
||||
static String? _cachedDownloadUrl;
|
||||
|
||||
/// Fetches the latest release tag from GitHub.
|
||||
/// Returns the version string (e.g. "1.0.7") or null on failure.
|
||||
///
|
||||
/// Tags should follow semver with an optional "v" prefix:
|
||||
/// git tag v1.0.7 && git push origin v1.0.7
|
||||
static Future<String?> fetchLatestVersion() async {
|
||||
final url = 'https://api.github.com/repos/${AppConfig.githubOwner}/${AppConfig.githubRepo}/releases/latest';
|
||||
final url =
|
||||
'https://api.github.com/repos/${AppConfig.githubOwner}/${AppConfig.githubRepo}/releases/latest';
|
||||
|
||||
try {
|
||||
final response = await http
|
||||
.get(Uri.parse(url), headers: {'Accept': 'application/vnd.github+json'})
|
||||
.get(Uri.parse(url),
|
||||
headers: {'Accept': 'application/vnd.github+json'})
|
||||
.timeout(const Duration(seconds: 8));
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
@@ -103,11 +60,11 @@ class GitHubUpdater {
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the GitHub releases page for the latest release.
|
||||
static Future<bool> open() async {
|
||||
final url = _cachedDownloadUrl ?? AppConfig.githubReleasesUrl;
|
||||
try {
|
||||
return await launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication);
|
||||
return await launchUrl(Uri.parse(url),
|
||||
mode: LaunchMode.externalApplication);
|
||||
} catch (e) {
|
||||
debugPrint('[Updater] Failed to open GitHub: $e');
|
||||
return false;
|
||||
@@ -115,200 +72,119 @@ class GitHubUpdater {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ##############################################################################
|
||||
// #
|
||||
// SHARED LOGIC #
|
||||
// VERSION CHECK & GLUE #
|
||||
// #
|
||||
// Updater.check(context) — call from the sidebar button. It: #
|
||||
// #
|
||||
// 1. Fetches the latest version from GitHub Releases API #
|
||||
// 2. Compares to the local version from the app bundle #
|
||||
// 3. Up to date? → green snackbar #
|
||||
// 4. Update available? → dialog, then redirects to Play Store or GitHub #
|
||||
// #
|
||||
// ##############################################################################
|
||||
|
||||
class Updater {
|
||||
Updater._();
|
||||
|
||||
static InstallSource? _cachedSource;
|
||||
|
||||
/// Detects where this app was installed from.
|
||||
///
|
||||
/// • com.android.vending → Play Store
|
||||
/// • anything else / null → sideloaded (GitHub APK, etc.)
|
||||
static Future<InstallSource> get installSource async {
|
||||
if (_cachedSource != null) return _cachedSource!;
|
||||
|
||||
if (kIsWeb || !Platform.isAndroid) {
|
||||
_cachedSource = InstallSource.sideload;
|
||||
return _cachedSource!;
|
||||
}
|
||||
|
||||
// In debug mode the app isn't signed with a Play Console certificate,
|
||||
// so we default to the sideload path.
|
||||
if (kDebugMode) {
|
||||
debugPrint('[Updater] Debug mode — treating install source as sideload.');
|
||||
_cachedSource = InstallSource.sideload;
|
||||
return _cachedSource!;
|
||||
}
|
||||
|
||||
try {
|
||||
final source = await _detectInstallerSource();
|
||||
_cachedSource = source;
|
||||
debugPrint('[Updater] Install source: ${source.name}');
|
||||
return source;
|
||||
final result = await MethodChannel('com.revoltvpn.app/installer')
|
||||
.invokeMethod<String>('getInstallerPackage');
|
||||
_cachedSource = (result == 'com.android.vending')
|
||||
? InstallSource.playStore
|
||||
: InstallSource.sideload;
|
||||
} catch (e) {
|
||||
debugPrint('[Updater] Installer detection failed, assuming sideload: $e');
|
||||
debugPrint('[Updater] Installer check failed: $e');
|
||||
_cachedSource = InstallSource.sideload;
|
||||
return _cachedSource!;
|
||||
}
|
||||
|
||||
return _cachedSource!;
|
||||
}
|
||||
|
||||
static Future<InstallSource> _detectInstallerSource() async {
|
||||
// Install source detection is stubbed until the native method channel
|
||||
// is wired in MainActivity.kt. Without it, all users default to the
|
||||
// GitHub update path — which works, but Play Store users should ideally
|
||||
// be sent to the Play Store listing instead.
|
||||
//
|
||||
// To wire: add a MethodChannel named "com.revoltvpn.app/installer" in
|
||||
// MainActivity.kt that calls PackageManager.getInstallerPackageName().
|
||||
// If it returns "com.android.vending", return InstallSource.playStore.
|
||||
// Then uncomment the 7 lines below and delete the fallback return.
|
||||
//
|
||||
// const channel = MethodChannel('com.revoltvpn.app/installer');
|
||||
// final installer = await channel.invokeMethod<String>('getInstallerPackage');
|
||||
// if (installer == 'com.android.vending') {
|
||||
// return InstallSource.playStore;
|
||||
// }
|
||||
// return InstallSource.sideload;
|
||||
return InstallSource.sideload; // Stubbed — see above.
|
||||
}
|
||||
|
||||
/// Compares two semver strings. Positive = a > b, negative = a < b, 0 = equal.
|
||||
static int _compareVersions(String a, String b) {
|
||||
final aParts = a.split('.').map((p) => int.tryParse(p) ?? 0).toList();
|
||||
final bParts = b.split('.').map((p) => int.tryParse(p) ?? 0).toList();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
final av = i < aParts.length ? aParts[i] : 0;
|
||||
final bv = i < bParts.length ? bParts[i] : 0;
|
||||
if (av != bv) return av - bv;
|
||||
final diff = (aParts.length > i ? aParts[i] : 0) -
|
||||
(bParts.length > i ? bParts[i] : 0);
|
||||
if (diff != 0) return diff;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// Call this from the sidebar "Check for updates" button.
|
||||
///
|
||||
/// Returns the [UpdateStatus] for programmatic use, but the UI
|
||||
/// (snackbar or dialog) is already handled.
|
||||
static Future<UpdateStatus> check(BuildContext context) async {
|
||||
// 1. Local version from the app bundle.
|
||||
final localVersion = (await PackageInfo.fromPlatform()).version;
|
||||
debugPrint('[Updater] Local version: $localVersion');
|
||||
static String _versionLabel(String v, bool isLocal) {
|
||||
final prefix = v.startsWith('v') ? '' : 'v';
|
||||
return '$prefix$v${isLocal ? ' (installed)' : ''}';
|
||||
}
|
||||
|
||||
static Future<void> check(BuildContext context) async {
|
||||
final localVersion = ReVoltApp.appVersion;
|
||||
if (localVersion.isEmpty) {
|
||||
_showSnackBar(context, 'Could not determine app version',
|
||||
isError: true);
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Latest version from GitHub (single source of truth for both paths).
|
||||
final latestVersion = await GitHubUpdater.fetchLatestVersion();
|
||||
if (latestVersion == null) {
|
||||
debugPrint('[Updater] Could not determine latest version.');
|
||||
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Could not check for updates. Try again later.'),
|
||||
backgroundColor: AppColors.bgCard,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
duration: Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
return UpdateStatus.checkFailed;
|
||||
_showSnackBar(context, 'Could not reach GitHub', isError: true);
|
||||
return;
|
||||
}
|
||||
|
||||
debugPrint('[Updater] Latest version: $latestVersion');
|
||||
|
||||
// 3. Compare.
|
||||
if (_compareVersions(localVersion, latestVersion) >= 0) {
|
||||
debugPrint('[Updater] App is up to date.');
|
||||
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('✓ Up to date (v$localVersion)'),
|
||||
backgroundColor: AppColors.bgCard,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
return UpdateStatus.upToDate;
|
||||
_showSnackBar(context, 'Up to date');
|
||||
return;
|
||||
}
|
||||
|
||||
// 4. Update available — open the store immediately, no dialog.
|
||||
debugPrint('[Updater] Update available: $localVersion → $latestVersion');
|
||||
|
||||
final source = await installSource;
|
||||
final isPlayStore = source == InstallSource.playStore;
|
||||
final storeName = source == InstallSource.playStore ? 'Play Store' : 'GitHub';
|
||||
if (!context.mounted) return;
|
||||
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Opening ${isPlayStore ? 'Play Store' : 'GitHub'}…'),
|
||||
backgroundColor: AppColors.bgCard,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
duration: const Duration(seconds: 2),
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
backgroundColor: AppColors.bgCard,
|
||||
title: const Text('Update available',
|
||||
style: TextStyle(color: AppColors.textWhite)),
|
||||
content: Text(
|
||||
'${_versionLabel(latestVersion, false)} is available on $storeName.\n'
|
||||
'You have ${_versionLabel(localVersion, true)}.',
|
||||
style: const TextStyle(color: AppColors.slate70),
|
||||
),
|
||||
);
|
||||
}
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('Later',
|
||||
style: TextStyle(color: AppColors.slate70)),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(ctx);
|
||||
source == InstallSource.playStore
|
||||
? PlayStoreUpdater.open()
|
||||
: GitHubUpdater.open();
|
||||
},
|
||||
child: Text('Open $storeName',
|
||||
style: const TextStyle(color: AppColors.accent)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (isPlayStore) {
|
||||
await PlayStoreUpdater.open();
|
||||
} else {
|
||||
await GitHubUpdater.open();
|
||||
}
|
||||
return UpdateStatus.updateAvailable;
|
||||
static void _showSnackBar(BuildContext context, String message,
|
||||
{bool isError = false}) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(isError ? Icons.error_outline : Icons.check_circle,
|
||||
color: isError ? AppColors.red400 : AppColors.green400,
|
||||
size: 18),
|
||||
const SizedBox(width: 8),
|
||||
Text(message),
|
||||
],
|
||||
),
|
||||
backgroundColor: AppColors.bgCard,
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ##############################################################################
|
||||
// #
|
||||
// INTEGRATION GUIDE #
|
||||
// #
|
||||
// 1. pubspec.yaml — add: #
|
||||
// #
|
||||
// package_info_plus: ^6.0.0 #
|
||||
// #
|
||||
// 2. app_config.dart — add these constants: #
|
||||
// #
|
||||
// static const String applicationId = 'com.paladinvpn.app'; #
|
||||
// static const String githubOwner = 'revoltvpn'; #
|
||||
// static const String githubRepo = 'revoltvpn'; #
|
||||
// #
|
||||
// 3. Android native — add to MainActivity.kt for install source detection: #
|
||||
// #
|
||||
// override fun configureFlutterEngine(flutterEngine: FlutterEngine) { #
|
||||
// super.configureFlutterEngine(flutterEngine) #
|
||||
// MethodChannel( #
|
||||
// flutterEngine.dartExecutor.binaryMessenger, #
|
||||
// "com.revoltvpn.app/installer" #
|
||||
// ).setMethodCallHandler { call, result -> #
|
||||
// if (call.method == "getInstallerPackage") { #
|
||||
// val installer = packageManager #
|
||||
// .getInstallerPackageName(packageName) #
|
||||
// result.success(installer) #
|
||||
// } else { #
|
||||
// result.notImplemented() #
|
||||
// } #
|
||||
// } #
|
||||
// } #
|
||||
// #
|
||||
// 4. Already wired — sidebar button calls Updater.check(context). #
|
||||
// #
|
||||
// 5. Tag releases with semver on GitHub: #
|
||||
// #
|
||||
// git tag v1.0.7 #
|
||||
// git push origin v1.0.7 #
|
||||
// #
|
||||
// ##############################################################################
|
||||
Reference in new issue
Block a user