Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a89af3c62 | ||
|
|
62104d5730 | ||
|
|
4eb1fca666 | ||
|
|
71468f7594 | ||
|
|
6adf03f920 | ||
|
|
5642b0b811 | ||
|
|
096fbf5a97 | ||
|
|
6c137245fd | ||
|
|
cc819abc41 | ||
|
|
d696bda63f | ||
|
|
61c72b2200 | ||
|
|
54f949ca8e | ||
|
|
cf50c3a01b | ||
|
|
04ec8ac5d1 | ||
|
|
56ea53e73b | ||
|
|
143f5f4eff | ||
|
|
abcb41fb06 | ||
|
|
e2359419bc | ||
|
|
2d0628c5bb | ||
|
|
4fde4a9217 | ||
|
|
75cf59f22c | ||
|
|
c1ec77a075 | ||
|
|
1b8a67cecb | ||
|
|
c5148e138d | ||
|
|
832c2d0a2d | ||
|
|
7f40a82997 | ||
|
|
fd6b358929 | ||
|
|
4555911ee8 | ||
|
|
54609a3119 | ||
|
|
e1c5d5b106 | ||
|
|
adf6de5dc0 | ||
|
|
81d0387612 | ||
|
|
33522dfeaf | ||
|
|
f8abda9323 | ||
|
|
f01a610182 | ||
|
|
d6c56e8345 | ||
|
|
96584082cf | ||
|
|
66e89d8d28 |
No files matched your search
@@ -0,0 +1,10 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
|
*.bat text eol=crlf
|
||||||
|
*.ps1 text eol=crlf
|
||||||
|
*.png binary
|
||||||
|
*.jpg binary
|
||||||
|
*.jpeg binary
|
||||||
|
*.webp binary
|
||||||
|
*.jks binary
|
||||||
|
*.keystore binary
|
||||||
|
*.jar binary
|
||||||
@@ -1,38 +1,62 @@
|
|||||||
# Miscellaneous
|
# =============================================================================
|
||||||
*.class
|
# ReVoltVPN — .gitignore
|
||||||
*.log
|
#
|
||||||
*.pyc
|
# Type-based by design. This repo ships Dart, Kotlin, XML and image assets;
|
||||||
*.swp
|
# everything else is excluded by extension or directory rather than by being
|
||||||
.DS_Store
|
# listed individually. A new file is therefore ignored by default instead of
|
||||||
.atom/
|
# needing to be named here, and this file does not enumerate what it protects.
|
||||||
.buildlog/
|
|
||||||
.history
|
|
||||||
.svn/
|
|
||||||
.java-version
|
|
||||||
|
|
||||||
# IntelliJ related
|
# =============================================================================
|
||||||
*.iml
|
|
||||||
*.ipr
|
|
||||||
*.iws
|
|
||||||
.idea/
|
|
||||||
|
|
||||||
# The .vscode folder contains configure files for the Visual Studio Code
|
# ── Secrets ────────────────────────────────────────────────────────────────
|
||||||
# editor. Although we may keep it, we often ignore it.
|
*.keystore
|
||||||
.vscode/
|
*.jks
|
||||||
|
android/key.properties
|
||||||
|
android/admob.properties
|
||||||
|
|
||||||
# Python cache & User files
|
# Real IPs and IDs. app_config.example.dart is the committed template.
|
||||||
TECHNICAL_DEBT.md
|
|
||||||
RUNNING.md
|
|
||||||
__pycache__/
|
|
||||||
*.pyc
|
|
||||||
|
|
||||||
# App Config (Hide real IPs/IDs from GitHub)
|
|
||||||
lib/logic/app_config.dart
|
lib/logic/app_config.dart
|
||||||
|
|
||||||
# Flutter/Dart/Pub related
|
# ── File types the shipped app does not contain ────────────────────────────
|
||||||
**/doc/api/
|
# Server code, infrastructure configs, captures, archives, dumps and logs.
|
||||||
**/ios/Flutter/.last_build_id
|
# None of these extensions are tracked, so a blanket rule is safe and stays
|
||||||
|
# safe — it covers files that do not exist yet.
|
||||||
|
*.py
|
||||||
|
*.pyc
|
||||||
|
*.json
|
||||||
|
*.conf
|
||||||
|
*.sh
|
||||||
|
*.txt
|
||||||
|
*.html
|
||||||
|
*.zip
|
||||||
|
*.log
|
||||||
|
*.class
|
||||||
|
|
||||||
|
# ── Documentation ──────────────────────────────────────────────────────────
|
||||||
|
# The published set is allow-listed; anything else, at any depth, is not.
|
||||||
|
# Leading slashes anchor these to the repo root so a same-named file in a
|
||||||
|
# subdirectory is NOT re-included by the negation.
|
||||||
|
*.md
|
||||||
|
!/README.md
|
||||||
|
!/CHANGELOG.md
|
||||||
|
!/CONTRIBUTING.md
|
||||||
|
!/PRIVACY_POLICY.md
|
||||||
|
|
||||||
|
# ── Working directories ────────────────────────────────────────────────────
|
||||||
|
# Material that is not part of the app. These need directory rules rather
|
||||||
|
# than type rules, because they can hold source-file types the rules above
|
||||||
|
# deliberately do not cover.
|
||||||
|
.local/
|
||||||
|
internal/
|
||||||
|
hivemind/
|
||||||
|
scraped/
|
||||||
|
backup/
|
||||||
|
backups/
|
||||||
|
lib/logic/backup/
|
||||||
|
|
||||||
|
# ── Flutter / Dart build output ────────────────────────────────────────────
|
||||||
.dart_tool/
|
.dart_tool/
|
||||||
|
*.dart_tool/
|
||||||
.flutter-plugins
|
.flutter-plugins
|
||||||
.flutter-plugins-dependencies
|
.flutter-plugins-dependencies
|
||||||
.pub-cache/
|
.pub-cache/
|
||||||
@@ -41,50 +65,35 @@ build/
|
|||||||
**/build/
|
**/build/
|
||||||
local_packages/*/build/
|
local_packages/*/build/
|
||||||
local_packages/*/.dart_tool/
|
local_packages/*/.dart_tool/
|
||||||
*.dart_tool/
|
**/doc/api/
|
||||||
|
**/ios/Flutter/.last_build_id
|
||||||
|
|
||||||
# Android related
|
# ── Android build output ───────────────────────────────────────────────────
|
||||||
**/android/**/gradle-wrapper.jar
|
|
||||||
**/android/.gradle
|
**/android/.gradle
|
||||||
|
**/android/.cxx/
|
||||||
|
**/android/app/build/
|
||||||
**/android/captures/
|
**/android/captures/
|
||||||
**/android/gradlew
|
**/android/gradlew
|
||||||
**/android/gradlew.bat
|
**/android/gradlew.bat
|
||||||
**/android/local.properties
|
**/android/local.properties
|
||||||
|
**/android/**/gradle-wrapper.jar
|
||||||
**/android/**/GeneratedPluginRegistrant.java
|
**/android/**/GeneratedPluginRegistrant.java
|
||||||
**/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
|
**/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
|
||||||
**/android/.cxx/
|
|
||||||
**/android/app/build/
|
|
||||||
|
|
||||||
# Keystore files
|
|
||||||
*.keystore
|
|
||||||
*.jks
|
|
||||||
|
|
||||||
# Crashlytics cache
|
|
||||||
**/android/app/crashlytics-build.properties
|
**/android/app/crashlytics-build.properties
|
||||||
|
|
||||||
# Shell scripts (dev only, not for public)
|
# ── Editors, tooling & OS ──────────────────────────────────────────────────
|
||||||
server_picture.sh
|
.claude/
|
||||||
XRAY_CONFIG_REFERENCE.md
|
.codewhale/
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
.atom/
|
||||||
|
.history
|
||||||
|
.svn/
|
||||||
|
.java-version
|
||||||
|
.DS_Store
|
||||||
|
*.swp
|
||||||
|
__pycache__/
|
||||||
|
devtools_options.yaml
|
||||||
|
|
||||||
# Secrets
|
#why are you even looking at this file? it's a secret. go away.
|
||||||
android/key.properties
|
whatsthis
|
||||||
android/admob.properties
|
|
||||||
SECURITY_HARDENING.md
|
|
||||||
VLESS_APP_CONTRACT.md
|
|
||||||
AGENTS.md
|
|
||||||
SERVER_NOTES.md
|
|
||||||
lib/logic/backup/
|
|
||||||
00-FULL-REPORT.md
|
|
||||||
server full picture.txt
|
|
||||||
technical_debt_*.md
|
|
||||||
server_full_picture_2.txt
|
|
||||||
hivemind_backup.py
|
|
||||||
UI_POSITIONING.md
|
|
||||||
SERVER_SETUP.md
|
|
||||||
REALITY_MIGRATION_PLAN.md
|
|
||||||
xray_config_reality.json
|
|
||||||
SERVER_DEPLOYMENT.md
|
|
||||||
swarm_watch.py
|
|
||||||
nginx_hivemind_reality.conf
|
|
||||||
nginx_hivemind_reality.conf
|
|
||||||
nginx_hivemind_reality.conf
|
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to the ReVoltVPN Flutter app.
|
||||||
|
Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [3.3.0] — 2026-08-30
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Session countdown in the VPN notification, updated each second while connected.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Session-expiry desync** — the app could show "Online" with no internet after
|
||||||
|
the server ended the session. The countdown no longer freezes when a poll fails.
|
||||||
|
- **Notification Disconnect button** disappeared a second after connecting.
|
||||||
|
Re-posting the foreground notification replaces it wholesale, so the action,
|
||||||
|
colour and tap-intent flutter_vless sets are now rebuilt rather than dropped.
|
||||||
|
- **Speed readout** divided the byte delta by the nominal poll interval instead of
|
||||||
|
the real time between polls — wrong by up to 6x around every background switch.
|
||||||
|
- **Settings toggles** now apply at launch. Rain, lightning and haptics were only
|
||||||
|
read from disk when Settings mounted, so an effect turned off came back — ticker
|
||||||
|
and all — on every relaunch, and haptic feedback did nothing until Settings had
|
||||||
|
been opened at least once.
|
||||||
|
- **Haptic feedback** now fires `mediumImpact()` instead of `lightImpact()` (which
|
||||||
|
is imperceptible on many Android devices), wrapped best-effort so a platform
|
||||||
|
vibration failure cannot fail a connect/disconnect, with a preview tap when the
|
||||||
|
toggle is switched on.
|
||||||
|
- First-launch disclosure dialog said data was linked to "your account". It is
|
||||||
|
linked to a randomly generated device ID, and the policy is in the sidebar, not
|
||||||
|
on a website.
|
||||||
|
- Sidebar "Settings" and "Check for updates" used the drawer's context after
|
||||||
|
`Navigator.pop()` — a defunct context. They now capture the root navigator (and
|
||||||
|
messenger) before closing the drawer. *(Fix ported from Naveax's review.)*
|
||||||
|
|
||||||
|
### Performance
|
||||||
|
- Rain overlay ticks only while enabled, repaints through a scoped `Listenable`
|
||||||
|
instead of rebuilding every frame, and precomputes drop colours.
|
||||||
|
- Lightning no longer fires strikes while disabled.
|
||||||
|
- Connect button pulse pauses when backgrounded; brand image hoisted out of the
|
||||||
|
per-frame rebuild.
|
||||||
|
- Server poll drops to 30 s while backgrounded (5 s foreground), with an immediate
|
||||||
|
re-sync on resume. The 1 s countdown keeps running.
|
||||||
|
- Health probe runs only while disconnected, and pauses in the background.
|
||||||
|
- Speed and support widgets rebuild on value change instead of every second.
|
||||||
|
- Notification channel is created once per process, not once per second.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- VLESS engine initializes under the splash screen; the intro waits on
|
||||||
|
`VpnConnection.ready` (8 s cap) before showing the main screen.
|
||||||
|
- AdMob SDK init moved off the blocking pre-`runApp()` path so startup cannot hang
|
||||||
|
on an unreachable Google endpoint.
|
||||||
|
- `app_config.example.dart` drops the dead bootstrap fields and documents
|
||||||
|
`hivemindApiPublic` in their place.
|
||||||
|
- `.gitignore` reorganized around type and directory rules; the enumerated
|
||||||
|
filename list is gone (redundant with the type rules) and `.claude/` is now
|
||||||
|
ignored.
|
||||||
|
|
||||||
|
### Security
|
||||||
|
- Update checker pins the release URL to this repo's path on `github.com`, not just
|
||||||
|
the host. Anything else falls back to the releases page.
|
||||||
|
- Notification timer updates are gated on a live tunnel, so a late tick cannot leave
|
||||||
|
an ongoing notification with no foreground service behind it.
|
||||||
|
- Dropped `READ_EXTERNAL_STORAGE`, which `flutter_vless` pulls in but the app never uses
|
||||||
|
(least privilege).
|
||||||
|
- Pinned the Gradle 8.14 distribution SHA-256; `validateDistributionUrl` enabled
|
||||||
|
(supply-chain integrity).
|
||||||
|
|
||||||
|
### Build & tooling (ported from Naveax)
|
||||||
|
- Removed the deprecated `android.enableR8` flag.
|
||||||
|
- Added `analysis_options.yaml` (flutter_lints, `local_packages/**` excluded, `avoid_print`).
|
||||||
|
- Added `.gitattributes` to pin LF line endings repo-wide.
|
||||||
|
- Credit: reviewed and ported from **Naveax**.
|
||||||
|
|
||||||
|
### Docs
|
||||||
|
- Privacy policy: disclosed that the server sees the connecting IP, corrected the
|
||||||
|
"stored in memory" claim, and documented consent being changeable from the sidebar.
|
||||||
|
|
||||||
|
## [3.2.2] — 2026-08-08
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Updated Discord invite link.
|
||||||
|
|
||||||
|
## [3.2.1] — 2026-08-08
|
||||||
|
|
||||||
|
### Google Play compliance
|
||||||
|
- Added first-launch data disclosure dialog ("Before you connect") explaining
|
||||||
|
that connection duration and data usage are logged for quota enforcement, and
|
||||||
|
that traffic content is never monitored.
|
||||||
|
|
||||||
|
## [3.2.0] — 2026-08-08
|
||||||
|
|
||||||
|
### DPI hardening
|
||||||
|
- Spoof Chrome-on-Android User-Agent on all API calls instead of `Dart/3.x`.
|
||||||
|
- Renamed domain from `getrevolt.app` to `userevolt.app`.
|
||||||
|
|
||||||
|
### Branding
|
||||||
|
- App name changed from "REVOLT VPN" to "Revolt VPN" across manifest, splash,
|
||||||
|
notification, and VLESS URL remark.
|
||||||
|
|
||||||
|
### Notification
|
||||||
|
- Removed duplicate `flutter_local_notifications` notification. Only the
|
||||||
|
Android VPN foreground-service notification remains — non-swipeable.
|
||||||
|
- Patched `flutter_vless` native code to use custom notification icon
|
||||||
|
(`@drawable/notification_icon`) with dark background (`#0D1117`).
|
||||||
|
|
||||||
|
### Connection reliability
|
||||||
|
- Merged five separate disconnect paths into a single idempotent
|
||||||
|
`_doDisconnect()` gate. Eliminated race between timer ticks and VPN
|
||||||
|
teardown where the countdown could briefly show -1.
|
||||||
|
- `stopVless()` timeout (5 s) now correctly shows an error instead of
|
||||||
|
silently pretending the VPN disconnected while the tunnel was still alive.
|
||||||
|
|
||||||
|
### AdMob bypass
|
||||||
|
- `kDebugMode` guard removed — the debug AdMob callback now fires in release
|
||||||
|
builds so release APKs can create sessions without real ads during testing.
|
||||||
|
The real gate is `ADMOB_BYPASS` on the server.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Notification icon:** Replaced five density-specific `ic_launcher.png`
|
||||||
|
files with `notification_icon.png`, then reverted to avoid changing the
|
||||||
|
home-screen icon. The custom icon is now injected through flutter_vless's
|
||||||
|
`initializeVless()` parameters.
|
||||||
|
|
||||||
|
## [3.1.0] — 2026-08-06
|
||||||
|
|
||||||
|
### Architecture — domain-free client
|
||||||
|
- **Zero domain strings in APK.** RKN has nothing to DNS-block. API calls go
|
||||||
|
through the Reality tunnel to `10.254.254.1:5000`, redirected to Flask by
|
||||||
|
Xray's `api` freedom outbound (`redirect: 127.0.0.1:5000`).
|
||||||
|
- **Bootstrap tunnel.** Bundled Reality config in APK → connect → fetch real
|
||||||
|
per-session VLESS URL from inside the tunnel → reconnect. Bootstrap client
|
||||||
|
permanently in `xray_config_reality.json`, restricted by Xray routing to
|
||||||
|
internal API only.
|
||||||
|
- `serverDomain` removed from `AppConfig`. `fetchConfigThroughTunnel()`
|
||||||
|
replaces `fetchConfigWithPolling()`. `connect()` rewritten.
|
||||||
|
|
||||||
|
### Protocol — TCP to XHTTP
|
||||||
|
- Transport: TCP → XHTTP (H2 stream-up with Reality). No more XTLS-Vision,
|
||||||
|
no `flow` field. Path-hidden behind `/revolt`.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **RenderFlex overflow** — status bar text wrapped in `Flexible` with
|
||||||
|
`TextOverflow.ellipsis` to prevent overflow on narrow screens (≤360dp).
|
||||||
|
- **Circular import** — removed `import 'package:revoltvpn/main.dart'` from
|
||||||
|
`sidebar_drawer.dart`. `SidebarDrawer` converted to `StatefulWidget`;
|
||||||
|
version footer loaded via `PackageInfo.fromPlatform()`.
|
||||||
|
- Client hot-reload was silently broken — `xray api adi` no-op. Fixed:
|
||||||
|
`adu`/`rmu` commands per Xray HandlerService spec.
|
||||||
|
- Missing XHTTP `path` param in VLESS URL — now reads `xhttp_path` from
|
||||||
|
`/session/status`.
|
||||||
|
- `providerBundleIdentifier` was `com.revoltvpn.app` — must match
|
||||||
|
`com.paladinvpn.app` for VPN service registration.
|
||||||
|
- Reality keypair generated (was placeholder). Throttle `uplinkOnly`/`downlinkOnly`
|
||||||
|
corrected (seconds, not bytes/sec). Fallback rate limits removed (fingerprint).
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Settings screen** — reached from a new sidebar row (between Website and
|
||||||
|
Check for updates). Slide-from-right navigation via `PageRouteBuilder`.
|
||||||
|
Folder: `lib/screens/settings/` with one file per feature in `in_settings/`.
|
||||||
|
- **Haptic feedback toggle** — on/off switch in Settings for `lightImpact()`
|
||||||
|
vibration on successful connect/disconnect. Default: off. Uses sync-bool
|
||||||
|
pattern (no await on tap, no SharedPreferences in connect button).
|
||||||
|
- **Rain/Lightning effect toggles** — two switches in Settings to control
|
||||||
|
the animated background effects. Default: on. Effects detect the toggle
|
||||||
|
within one frame (no Provider/notifier needed).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Timer box spinner removed** — the "Connecting…"/"Syncing…" spinner under
|
||||||
|
the countdown was redundant with the connect button's spinner. Timer card
|
||||||
|
is now a clean countdown only (gray '00:00:00' when idle).
|
||||||
|
- **Sidebar** now has 7 rows (added Settings). `FRONTEND_POLISH_REVIEW.md`
|
||||||
|
fully triaged: 4 items fixed, 11 skipped.
|
||||||
|
|
||||||
|
### Server
|
||||||
|
- `api` outbound + 3 routing rules in `xray_config_reality.json` (bootstrap
|
||||||
|
isolation + API routing). Permanent bootstrap client. Hivemind unchanged.
|
||||||
|
- `xhttp_path` in `/session/status` response.
|
||||||
|
- Full deployment guide: `SERVER_DEPLOYMENT.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [2.0.7] — 2026-07-31
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Notification bug** — `SessionTimer.stop()` now cancels the persistent
|
||||||
|
Android notification on user-initiated disconnect.
|
||||||
|
- **Concurrent sync guard** — `_syncInProgress` flag prevents duplicate
|
||||||
|
HTTP requests from overlapping in `_syncWithHivemind()`.
|
||||||
|
- **Debug bypass gate** — `AppConfig.enableAdBypass` replaces `kDebugMode`
|
||||||
|
for fake AdMob callback. Tree-shaken in release builds.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Responsive layout** — main screen uses `LayoutBuilder` with proportional
|
||||||
|
fractions. Scales to any screen size.
|
||||||
|
- **Dynamic version** — sidebar footer reads from `PackageInfo` instead of
|
||||||
|
hardcoded string.
|
||||||
|
- **Swarm/log blocked** — nginx returns 404 for `/api/swarm` and `/api/log`.
|
||||||
|
Monitoring runs locally via `swarm_watch.py`.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Update checker** in sidebar — polls GitHub Releases API.
|
||||||
|
- **Website button** in sidebar → opens `https://userevolt.app`.
|
||||||
|
- **Timer syncing indicator** — spinner during handshake.
|
||||||
|
- Dependency: `package_info_plus`.
|
||||||
|
|
||||||
|
### Server
|
||||||
|
- `/session/stop` fetches stats BEFORE popping session (race fix).
|
||||||
|
- `XrayManager._stats_lock` for diagnostic counter thread safety.
|
||||||
|
- `ManagementLoop._start_lock` prevents TOCTOU on daemon startup.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [1.0.6] — 2026-06
|
||||||
|
|
||||||
|
- Initial VLESS + Xray Reality tunnel
|
||||||
|
- 60 min session, 4 GB throttle, support top-up
|
||||||
|
- Server health dot, speed display, countdown timer
|
||||||
|
- Persistent Android notification
|
||||||
|
- Glass-morphism dark UI with yellow accent
|
||||||
|
- Right-edge sidebar with Ad Consent, Privacy, About, Discord
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# Contributing to ReVoltVPN
|
||||||
|
|
||||||
|
We would love for you to contribute to ReVoltVPN and help make it even better than it is today!
|
||||||
|
As a contributor, here are the guidelines we would like you to follow:
|
||||||
|
|
||||||
|
## <a name="commit"></a> Commit Message Format
|
||||||
|
|
||||||
|
*This specification is inspired by the Angular commit message format.*
|
||||||
|
|
||||||
|
#### <a name="commit-header"></a>Commit Message Header
|
||||||
|
|
||||||
|
```
|
||||||
|
<type>(<scope>): <short summary>
|
||||||
|
│ │ │
|
||||||
|
│ │ └─⫸ Summary in present tense. Not capitalized. No period at the end.
|
||||||
|
│ │
|
||||||
|
│ └─⫸ Commit Scope: app|server|xray|nginx|docs|config
|
||||||
|
│
|
||||||
|
└─⫸ Commit Type: build|ci|docs|feat|fix|perf|refactor|test
|
||||||
|
```
|
||||||
|
|
||||||
|
The `<type>` and `<summary>` fields are mandatory, the `(<scope>)` field is optional.
|
||||||
|
|
||||||
|
##### Type
|
||||||
|
|
||||||
|
Must be one of the following:
|
||||||
|
|
||||||
|
* **build**: Changes that affect the build system or external dependencies (example: Flutter, pub, Gradle)
|
||||||
|
* **ci**: Changes to CI configuration files and scripts
|
||||||
|
* **docs**: Documentation only changes (README, AGENTS.md, comments)
|
||||||
|
* **feat**: A new feature
|
||||||
|
* **fix**: A bug fix
|
||||||
|
* **perf**: A code change that improves performance
|
||||||
|
* **refactor**: A code change that neither fixes a bug nor adds a feature
|
||||||
|
* **test**: Adding missing tests or correcting existing tests
|
||||||
|
* **style**: Changes that do not affect the meaning of the code (formatting, whitespace)
|
||||||
|
|
||||||
|
##### Scope
|
||||||
|
|
||||||
|
The scope should be the part of the project affected:
|
||||||
|
|
||||||
|
* `app` — Flutter client (screens, components, logic)
|
||||||
|
* `server` — Python Hivemind backend
|
||||||
|
* `xray` — Xray Reality config or tunnel behavior
|
||||||
|
* `nginx` — nginx routing, SSL, auth
|
||||||
|
* `docs` — documentation files
|
||||||
|
* `config` — app_config, .gitignore, pubspec
|
||||||
|
|
||||||
|
##### Summary
|
||||||
|
|
||||||
|
Use the summary field to provide a succinct description of the change:
|
||||||
|
|
||||||
|
* use the imperative, present tense: "change" not "changed" nor "changes"
|
||||||
|
* don't capitalize the first letter
|
||||||
|
* no dot (.) at the end
|
||||||
|
|
||||||
|
|
||||||
|
#### <a name="commit-body"></a>Commit Message Body
|
||||||
|
|
||||||
|
Just as in the summary, use the imperative, present tense: "fix" not "fixed" nor "fixes".
|
||||||
|
|
||||||
|
Explain the motivation for the change in the commit message body. This commit message should explain _why_ you are making the change.
|
||||||
|
You can include a comparison of the previous behavior with the new behavior in order to illustrate the impact of the change.
|
||||||
|
|
||||||
|
#### Examples
|
||||||
|
|
||||||
|
```
|
||||||
|
feat(server): add swarm monitoring endpoint
|
||||||
|
|
||||||
|
GET /api/swarm returns sorted drone list for the TUI dashboard.
|
||||||
|
Persistent total GB saved to swarm_total.json, survives restarts.
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
fix(app): remove dead _isThrottled field from session timer
|
||||||
|
|
||||||
|
Field was written but never read — throttle handled by port-swap now.
|
||||||
|
Also removed unreachable 404 branch in _syncWithHivemind.
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
docs: update README with correct quota and Reality protocol details
|
||||||
|
```
|
||||||
@@ -1,21 +1,690 @@
|
|||||||
MIT License
|
ReVoltVPN — Copyright (C) 2026 esef
|
||||||
|
|
||||||
Copyright (c) 2026 esef
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
This program is distributed in the hope that it will be useful,
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
in the Software without restriction, including without limitation the rights
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
GNU General Public License for more details.
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
You should have received a copy of the GNU General Public License
|
||||||
copies or substantial portions of the Software.
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
GNU GENERAL PUBLIC LICENSE
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
Version 3, 29 June 2007
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
SOFTWARE.
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
@@ -1,21 +1,49 @@
|
|||||||
Privacy Policy
|
# Privacy Policy
|
||||||
Last updated: July 2025
|
|
||||||
|
**Last updated:** August 2026
|
||||||
|
|
||||||
ReVoltVPN is a free VPN service built and operated by ReVolt Team.
|
ReVoltVPN is a free VPN service built and operated by ReVolt Team.
|
||||||
What we collect
|
|
||||||
|
## In-app disclosure
|
||||||
|
|
||||||
|
When you first open the app, we show a brief summary of this policy before you connect. You can review this full policy at any time from the sidebar menu.
|
||||||
|
|
||||||
|
## What we collect
|
||||||
|
|
||||||
We collect the minimum required to operate the service:
|
We collect the minimum required to operate the service:
|
||||||
|
|
||||||
A randomly generated device ID created on your phone. This is not linked to your identity in any way.
|
- A randomly generated device ID created on your phone. This is not linked to your identity in any way.
|
||||||
Your active session status and data usage for the current session only. Sessions last up to 1 hour, then expire. All session data is stored in memory and deleted permanently when your session ends.
|
- Your connection duration and data usage for the current session, linked to your device ID. This is used solely to enforce the per-session quota (see below).
|
||||||
|
|
||||||
What we do not collect
|
## What our server sees
|
||||||
|
|
||||||
We do not collect your name, email, or any personal information.
|
To start, check, or refresh your session, the app contacts our API directly rather than through the VPN tunnel. Our server therefore sees the IP address you are connecting from, alongside your device ID, for as long as the app is running. This is a necessary consequence of how sessions are issued and kept alive — it is separate from your browsing traffic, which is carried inside the tunnel and is described below.
|
||||||
We do not log your internet traffic or browsing history.
|
|
||||||
We do not sell or share any data with third parties.
|
|
||||||
|
|
||||||
Ads & Consent
|
## Session quotas
|
||||||
ReVoltVPN uses Google AdMob to display rewarded video ads. On first launch, users in the European Economic Area (EEA) and United Kingdom are shown a consent dialog (provided by Google's User Messaging Platform) that lets them choose whether to allow personalized ads. This consent choice is stored on your device and can be changed at any time by reinstalling the app. Google may collect data as part of ad delivery. Please refer to Google's Privacy Policy for details.
|
|
||||||
Your traffic
|
Each session lasts up to **2 hours** or **10 GB** of data — whichever comes first. When your session expires or hits the data cap, the tunnel disconnects. You can start a new session by watching another ad. Session records (duration and bytes transferred) are held on our server for the life of your session and removed when it ends.
|
||||||
Your internet traffic is routed through our server located in Finland. We do not inspect, log, or store your traffic.
|
|
||||||
Contact
|
Support ads (the "Support us" button) extend an active session by 30 minutes and add extra data allowance.
|
||||||
If you have any questions, open an issue on the GitHub repository.
|
|
||||||
|
## Operational logs
|
||||||
|
|
||||||
|
We keep a short in-memory log buffer (last 200 lines) for debugging and server health monitoring. These logs include truncated device IDs (first 8 characters only), session start/stop events, and error messages. Logs never leave the server, are not retained after a server restart, and are only accessible to the server operator via local console. We also maintain an aggregate total of all data ever transferred (in GB) for capacity planning — this counter is not tied to any individual device.
|
||||||
|
|
||||||
|
## What we do not collect
|
||||||
|
|
||||||
|
- We do not collect your name, email, or any personal information.
|
||||||
|
- We do not log your internet traffic, browsing history, DNS queries, or destination IPs.
|
||||||
|
- We do not inspect or store the content of your traffic.
|
||||||
|
- We do not sell or share any data with third parties.
|
||||||
|
|
||||||
|
## Ads & Consent
|
||||||
|
|
||||||
|
ReVoltVPN uses Google AdMob to display rewarded video ads. Where required — for users in the European Economic Area (EEA) and United Kingdom — a consent dialog provided by Google's User Messaging Platform is shown before the first ad is requested, letting you choose whether to allow personalized ads. This choice is stored on your device and can be reviewed at any time from the "Ad Consent" entry in the sidebar menu. Google may collect data as part of ad delivery. Please refer to Google's Privacy Policy for details.
|
||||||
|
|
||||||
|
## Your traffic
|
||||||
|
|
||||||
|
Your internet traffic is routed through our server located in Finland. We do not inspect, log, or store your traffic. We only track total bytes transferred per session for quota enforcement — no packet contents, no destination IPs, no DNS queries.
|
||||||
|
|
||||||
|
## Contact
|
||||||
|
|
||||||
|
If you have any questions, open an issue on the GitHub repository or join the Discord server.
|
||||||
@@ -1,56 +1,60 @@
|
|||||||
---
|
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="screenshots/feature_graphic.png" alt="ReVoltVPN banner" width="100%"/>
|
<img src="screenshots/feature_graphic.png" alt="ReVoltVPN banner" width="100%"/>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
# ReVoltVPN
|
# ReVoltVPN
|
||||||
A free VPN app built from scratch. I handle the Flutter app, Hivemind backend, and AdMob integration — the ReVolt team manages server security and VLESS/Xray infrastructure.
|
|
||||||
|
|
||||||
There are hundreds of free VPN apps on the Play Store. Most of them are fine honestly — some are genuinely good. But a lot of them are vague about how they work, who runs them, and what happens to your traffic. I wanted to build something where the answer to all of those questions is just... public.
|
A free VPN app for Android. Open-source client, transparent infrastructure. Watch an ad, get 2 hours of full-speed traffic — no accounts, no logs, no subscriptions.
|
||||||
|
|
||||||
So here it is.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## How it works
|
## How it works
|
||||||
You watch a short ad. You get 60 minutes and 4 GB of full-speed traffic. That's it. The ad pays for the server (actually not even enough). No accounts, no emails, no subscriptions.
|
|
||||||
|
|
||||||
When your data runs out you get throttled to 1.5 Mbps instead of getting cut off. A second Reality inbound on a different port handles throttled traffic — your client reconnects automatically, no ad required.
|
1. Watch a short rewarded ad
|
||||||
|
2. Server creates a temporary VLESS session (2 hours / 10 GB)
|
||||||
|
3. Your traffic routes through a single server in Finland at full speed
|
||||||
|
4. When time or data runs out, session ends — watch another ad to continue
|
||||||
|
5. No throttling, no slow lane, no mid-session punishment
|
||||||
|
|
||||||
|
No email. No password. No payment. The ad pays for the server.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## The stack
|
## Protocol
|
||||||
- **App** — Flutter (Android only for now)
|
|
||||||
- **Server** — A single Debian box rented from Hetzner, located in Finland
|
- **Transport** — VLESS over XHTTP (HTTP/2 multiplexed, path-hidden behind `/revolt`)
|
||||||
- **VPN protocol** — VLESS + Xray Reality (XTLS-Vision). Spoofs real TLS certificates (e.g. www.microsoft.com) so your tunnel looks like regular HTTPS. Great for bypassing DPI in countries that are aggressive with it.
|
- **Obfuscation** — Xray Reality spoofs `some website's` TLS. To any DPI box, your tunnel looks like a browser visiting that website
|
||||||
- **Backend** — Hivemind, a Python Flask server I wrote that manages sessions, data quotas, throttling, and live swarm monitoring. Entire server is open source — in this repo.
|
- **Encryption** — TLS 1.3 with borrowed certificate (Reality). No certbot, no domain ownership required
|
||||||
- **Ads** — Google AdMob rewarded ads, verified server-side so fake callbacks don't work
|
- **API** — Standard HTTPS to a separate domain. Tunnel destination is IP-pinned — domain compromise is DoS only
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Limitations (being honest)
|
## Stack
|
||||||
- One server, one location (Finland). That's all I can afford right now (planning to escalate further)
|
|
||||||
- 2 cores and 4GB RAM. It will not handle thousands of concurrent users
|
| Layer | Technology |
|
||||||
- iOS is not supported and probably won't be for a while
|
|-------|-----------|
|
||||||
- The app is built by me in my free time — expect rough edges
|
| App | Flutter (Android) |
|
||||||
|
| VPN | VLESS + Xray Reality + XHTTP |
|
||||||
|
| Backend | Python Flask ("Hivemind") — session management, quotas, stats |
|
||||||
|
| Ads | Google AdMob rewarded, verified server-side |
|
||||||
|
| Server | Debian, single Hetzner box in Finland |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Why I built this
|
## Limitations
|
||||||
Free time project. I wanted to learn how VPNs actually work under the hood. Ended up building the whole thing from scratch — the Flutter app, Hivemind backend, and AdMob integration are made by me, while server security and VLESS/Xray setup are handled by the ReVolt team. It took way longer than expected.
|
|
||||||
|
- One server, one location (Finland)
|
||||||
|
- 2 vCPU / 4 GB RAM — not built for thousands of concurrent users
|
||||||
|
- Android only
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Privacy
|
## Privacy
|
||||||
Your traffic goes through my server in Finland. I don't log it, I don't sell it, I have no reason to. The session manager (Hivemind) only tracks whether your session is active and how much data you've used — nothing else.
|
|
||||||
|
|
||||||
Internet privacy at the cost of watching an ad. Honest business.
|
Your traffic routes through Finland. We don't log it, inspect it, or sell it. Hivemind tracks only session liveness and byte counters for quota enforcement — no packet contents, no destination IPs, no DNS queries.
|
||||||
|
|
||||||
You can read the server code yourself, it's in this repo.
|
Full privacy policy: [`PRIVACY_POLICY.md`](PRIVACY_POLICY.md)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
*ReVoltVPN is not affiliated with any VPN company.*
|
*ReVoltVPN is not affiliated with any VPN company.*
|
||||||
|
|
||||||
---
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
include: package:flutter_lints/flutter.yaml
|
||||||
|
|
||||||
|
analyzer:
|
||||||
|
exclude:
|
||||||
|
- local_packages/**
|
||||||
|
- whatsthis/**
|
||||||
|
|
||||||
|
linter:
|
||||||
|
rules:
|
||||||
|
avoid_print: true
|
||||||
@@ -7,7 +7,7 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = "com.revoltvpn.app"
|
namespace = "com.paladinvpn.app"
|
||||||
compileSdk = flutter.compileSdkVersion
|
compileSdk = flutter.compileSdkVersion
|
||||||
ndkVersion = flutter.ndkVersion
|
ndkVersion = flutter.ndkVersion
|
||||||
|
|
||||||
@@ -34,7 +34,7 @@ android {
|
|||||||
}
|
}
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "com.revoltvpn.app"
|
applicationId = "com.paladinvpn.app"
|
||||||
minSdk = flutter.minSdkVersion
|
minSdk = flutter.minSdkVersion
|
||||||
targetSdk = flutter.targetSdkVersion
|
targetSdk = flutter.targetSdkVersion
|
||||||
versionCode = flutter.versionCode
|
versionCode = flutter.versionCode
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.INTERNET"/>
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||||
<!-- VpnService provides its own system notification; SPECIAL_USE is not needed -->
|
<uses-permission android:name="android.permission.VIBRATE"/>
|
||||||
<!-- Required by url_launcher on Android 11+ to open external browser -->
|
|
||||||
|
<!-- flutter_vless 1.1.5 declares this legacy permission. ReVolt never needs it. -->
|
||||||
|
<uses-permission
|
||||||
|
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||||
|
tools:node="remove"/>
|
||||||
|
|
||||||
<queries>
|
<queries>
|
||||||
<intent>
|
<intent>
|
||||||
<action android:name="android.intent.action.VIEW"/>
|
<action android:name="android.intent.action.VIEW"/>
|
||||||
@@ -14,13 +20,13 @@
|
|||||||
</queries>
|
</queries>
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:label="REVOLT VPN"
|
android:label="Revolt VPN"
|
||||||
android:name="${applicationName}"
|
android:name="${applicationName}"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:usesCleartextTraffic="false"
|
android:usesCleartextTraffic="false"
|
||||||
android:allowBackup="false">
|
android:allowBackup="false"
|
||||||
|
android:extractNativeLibs="true">
|
||||||
|
|
||||||
<!-- AdMob App ID — injected at build time from android/admob.properties -->
|
|
||||||
<meta-data
|
<meta-data
|
||||||
android:name="com.google.android.gms.ads.APPLICATION_ID"
|
android:name="com.google.android.gms.ads.APPLICATION_ID"
|
||||||
android:value="${ADMOB_APP_ID}"/>
|
android:value="${ADMOB_APP_ID}"/>
|
||||||
@@ -35,16 +41,15 @@
|
|||||||
android:windowSoftInputMode="adjustResize">
|
android:windowSoftInputMode="adjustResize">
|
||||||
<meta-data
|
<meta-data
|
||||||
android:name="io.flutter.embedding.android.NormalTheme"
|
android:name="io.flutter.embedding.android.NormalTheme"
|
||||||
android:resource="@style/NormalTheme"
|
android:resource="@style/NormalTheme"/>
|
||||||
/>
|
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.MAIN"/>
|
<action android:name="android.intent.action.MAIN"/>
|
||||||
<category android:name="android.intent.category.LAUNCHER"/>
|
<category android:name="android.intent.category.LAUNCHER"/>
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
<meta-data
|
<meta-data
|
||||||
android:name="flutterEmbedding"
|
android:name="flutterEmbedding"
|
||||||
android:value="2"/>
|
android:value="2"/>
|
||||||
</application>
|
</application>
|
||||||
</manifest>
|
</manifest>
|
||||||
|
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
package com.paladinvpn.app
|
||||||
|
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import androidx.core.app.NotificationManagerCompat
|
||||||
|
import com.github.tfox.flutter_vless.xray.service.XrayVPNService
|
||||||
|
import com.github.tfox.flutter_vless.xray.utils.AppConfigs
|
||||||
|
import io.flutter.embedding.android.FlutterActivity
|
||||||
|
import io.flutter.embedding.engine.FlutterEngine
|
||||||
|
import io.flutter.plugin.common.MethodChannel
|
||||||
|
|
||||||
|
class MainActivity : FlutterActivity() {
|
||||||
|
|
||||||
|
// Channel id only — not the application id, which is com.paladinvpn.app.
|
||||||
|
// Must match the string in lib/logic/updater.dart.
|
||||||
|
private val installerChannel = "com.revoltvpn.app/installer"
|
||||||
|
|
||||||
|
// Must match lib/logic/notification_service.dart.
|
||||||
|
private val notificationChannel = "com.revoltvpn.app/notification"
|
||||||
|
|
||||||
|
private var notificationChannelReady = false
|
||||||
|
|
||||||
|
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||||
|
super.configureFlutterEngine(flutterEngine)
|
||||||
|
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, installerChannel)
|
||||||
|
.setMethodCallHandler { call, result ->
|
||||||
|
if (call.method == "getInstallerPackage") {
|
||||||
|
result.success(installerPackage())
|
||||||
|
} else {
|
||||||
|
result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, notificationChannel)
|
||||||
|
.setMethodCallHandler { call, result ->
|
||||||
|
if (call.method == "updateNotificationText") {
|
||||||
|
val text = call.argument<String>("text") ?: ""
|
||||||
|
val title = call.argument<String>("title") ?: "Revolt VPN"
|
||||||
|
val action = call.argument<String>("disconnectLabel") ?: "Disconnect"
|
||||||
|
updateVpnNotification(title, text, action)
|
||||||
|
result.success(null)
|
||||||
|
} else {
|
||||||
|
result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the session countdown as the VPN notification's content text.
|
||||||
|
*
|
||||||
|
* notify() is per-package, so re-posting flutter_vless's notification id
|
||||||
|
* replaces it wholesale — every field the plugin set has to be rebuilt
|
||||||
|
* here or it is dropped, the Disconnect action most of all. Keep in sync
|
||||||
|
* with XrayCoreManager.showNotification().
|
||||||
|
*/
|
||||||
|
private fun updateVpnNotification(title: String, text: String, actionLabel: String) {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||||
|
checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) !=
|
||||||
|
PackageManager.PERMISSION_GRANTED
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureNotificationChannel()
|
||||||
|
|
||||||
|
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
|
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||||
|
} else {
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same intent shape as the plugin, so a tap brings the running task
|
||||||
|
// forward instead of starting a second one.
|
||||||
|
val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
|
||||||
|
launchIntent?.action = "FROM_DISCONNECT_BTN"
|
||||||
|
launchIntent?.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or
|
||||||
|
Intent.FLAG_ACTIVITY_CLEAR_TOP or
|
||||||
|
Intent.FLAG_ACTIVITY_NEW_TASK
|
||||||
|
|
||||||
|
// Tapping "Disconnect" stops the tunnel without opening the app.
|
||||||
|
val stopIntent = Intent(this, XrayVPNService::class.java)
|
||||||
|
stopIntent.putExtra(
|
||||||
|
"COMMAND",
|
||||||
|
AppConfigs.V2RAY_SERVICE_COMMANDS.STOP_SERVICE
|
||||||
|
)
|
||||||
|
val stopPendingIntent = PendingIntent.getService(this, 0, stopIntent, flags)
|
||||||
|
|
||||||
|
val builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
|
||||||
|
.setSmallIcon(R.drawable.notification_icon)
|
||||||
|
.setContentTitle(title)
|
||||||
|
.setContentText(text)
|
||||||
|
.addAction(0, actionLabel, stopPendingIntent)
|
||||||
|
.setColorized(true)
|
||||||
|
.setColor(0xFF0D1117.toInt())
|
||||||
|
.setOngoing(true)
|
||||||
|
.setOnlyAlertOnce(true)
|
||||||
|
.setSilent(true)
|
||||||
|
.setShowWhen(false)
|
||||||
|
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||||
|
|
||||||
|
if (launchIntent != null) {
|
||||||
|
builder.setContentIntent(
|
||||||
|
PendingIntent.getActivity(this, 0, launchIntent, flags)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, builder.build())
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// The foreground notification may not be up yet — the update is cosmetic.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A binder round-trip, and the caller runs once a second — so, once per process. */
|
||||||
|
private fun ensureNotificationChannel() {
|
||||||
|
if (notificationChannelReady) return
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
val manager =
|
||||||
|
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
val channel = NotificationChannel(
|
||||||
|
NOTIFICATION_CHANNEL_ID,
|
||||||
|
"Revolt VPN Background Service",
|
||||||
|
NotificationManager.IMPORTANCE_LOW
|
||||||
|
)
|
||||||
|
channel.setShowBadge(false)
|
||||||
|
manager.createNotificationChannel(channel)
|
||||||
|
}
|
||||||
|
notificationChannelReady = true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Package name of whatever installed us ("com.android.vending" for Play
|
||||||
|
* Store), or null when unknown. Without this the Dart side always falls
|
||||||
|
* back to sideload and points every user at GitHub releases.
|
||||||
|
*/
|
||||||
|
private fun installerPackage(): String? = try {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
|
packageManager.getInstallSourceInfo(packageName).installingPackageName
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
packageManager.getInstallerPackageName(packageName)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
// Must match flutter_vless's XrayCoreManager.
|
||||||
|
private const val NOTIFICATION_ID = 1
|
||||||
|
private const val NOTIFICATION_CHANNEL_ID = "XRAY_SERVICE_CHANNEL"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package com.revoltvpn.app
|
|
||||||
|
|
||||||
import io.flutter.embedding.android.FlutterActivity
|
|
||||||
|
|
||||||
class MainActivity : FlutterActivity()
|
|
||||||
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 64 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 114 KiB |
|
Before Width: | Height: | Size: 172 KiB After Width: | Height: | Size: 174 KiB |
@@ -1,5 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
android:shape="rectangle">
|
android:shape="rectangle">
|
||||||
<solid android:color="#0d1017" />
|
<solid android:color="@color/splash_bg" />
|
||||||
</shape>
|
</shape>
|
||||||
|
After Width: | Height: | Size: 144 KiB |
@@ -0,0 +1,16 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||||
|
<item name="android:windowSplashScreenBackground">@color/splash_bg</item>
|
||||||
|
<item name="android:windowBackground">@color/splash_bg</item>
|
||||||
|
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
|
||||||
|
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||||
|
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||||
|
</style>
|
||||||
|
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||||
|
<item name="android:windowBackground">@color/splash_bg</item>
|
||||||
|
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
|
||||||
|
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||||
|
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
||||||
@@ -1,18 +1,15 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
|
|
||||||
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||||
<!-- Show a splash screen on the activity. Automatically removed when
|
|
||||||
the Flutter engine draws its first frame -->
|
|
||||||
<item name="android:windowBackground">@drawable/launch_background</item>
|
<item name="android:windowBackground">@drawable/launch_background</item>
|
||||||
|
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
|
||||||
|
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||||
|
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||||
</style>
|
</style>
|
||||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
|
||||||
This theme determines the color of the Android Window while your
|
|
||||||
Flutter UI initializes, as well as behind your Flutter UI while its
|
|
||||||
running.
|
|
||||||
|
|
||||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
|
||||||
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||||
<item name="android:windowBackground">?android:colorBackground</item>
|
<item name="android:windowBackground">@color/splash_bg</item>
|
||||||
|
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
|
||||||
|
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||||
|
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||||
</style>
|
</style>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||||
|
<item name="android:windowSplashScreenBackground">@color/splash_bg</item>
|
||||||
|
<item name="android:windowBackground">@color/splash_bg</item>
|
||||||
|
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
|
||||||
|
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||||
|
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||||
|
</style>
|
||||||
|
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||||
|
<item name="android:windowBackground">@color/splash_bg</item>
|
||||||
|
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
|
||||||
|
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||||
|
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<color name="splash_bg">#0d1017</color>
|
<color name="splash_bg">#0D1117</color>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1,18 +1,15 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<!-- Theme applied to the Android Window while the process is starting -->
|
|
||||||
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||||
<!-- Show a splash screen on the activity. Automatically removed when
|
|
||||||
Flutter draws its first frame -->
|
|
||||||
<item name="android:windowBackground">@drawable/launch_background</item>
|
<item name="android:windowBackground">@drawable/launch_background</item>
|
||||||
|
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
|
||||||
|
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||||
|
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||||
</style>
|
</style>
|
||||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
|
||||||
This theme determines the color of the Android Window while your
|
|
||||||
Flutter UI initializes, as well as behind your Flutter UI while its
|
|
||||||
running.
|
|
||||||
|
|
||||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
|
||||||
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||||
<item name="android:windowBackground">@color/splash_bg</item>
|
<item name="android:windowBackground">@color/splash_bg</item>
|
||||||
|
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
|
||||||
|
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||||
|
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||||
</style>
|
</style>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1,8 +1,5 @@
|
|||||||
org.gradle.jvmargs=-Xmx1536M
|
org.gradle.jvmargs=-Xmx1536M
|
||||||
android.enableR8=true
|
|
||||||
android.useAndroidX=true
|
android.useAndroidX=true
|
||||||
android.enableJetifier=true
|
android.enableJetifier=true
|
||||||
# This builtInKotlin flag was added automatically by Flutter migrator
|
|
||||||
android.builtInKotlin=false
|
android.builtInKotlin=false
|
||||||
# This newDsl flag was added automatically by Flutter migrator
|
|
||||||
android.newDsl=false
|
android.newDsl=false
|
||||||
@@ -3,3 +3,6 @@ distributionPath=wrapper/dists
|
|||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip
|
||||||
|
distributionSha256Sum=efe9a3d147d948d7528a9887fa35abcf24ca1a43ad06439996490f77569b02d1
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
// =============================================================================
|
|
||||||
// clock_display.dart — EDUCATIONAL REFERENCE (not used in production)
|
|
||||||
// =============================================================================
|
|
||||||
//
|
|
||||||
// This widget was the original combined timer + speed + syncing display.
|
|
||||||
// It was replaced by the separate TimerBox and SpeedBox widgets in the
|
|
||||||
// Reality-era UI refactor.
|
|
||||||
//
|
|
||||||
// What's worth studying here:
|
|
||||||
//
|
|
||||||
// 1. TEXT GLOW EFFECT — the yellow glow around the countdown timer:
|
|
||||||
// ```
|
|
||||||
// shadows: [Shadow(color: AppColors.accent50, blurRadius: 16)]
|
|
||||||
// ```
|
|
||||||
// This exact effect was ported to timer_box.dart and is what gives
|
|
||||||
// the countdown its signature pulsing-yellow look.
|
|
||||||
//
|
|
||||||
// 2. SYNCING PLACEHOLDER — conditional spinner + label when the first
|
|
||||||
// server poll hasn't returned yet. Shows "Syncing…" with a small
|
|
||||||
// CircularProgressIndicator instead of flashing 00:00:00.
|
|
||||||
//
|
|
||||||
// 3. COMBINED DISPLAY — clock + speed stacked in a Column inside a
|
|
||||||
// fixed 200×200 SizedBox. The modern UI split these into separate
|
|
||||||
// boxes for the stacked layout, but the stacking approach here is
|
|
||||||
// a good reference for compact combined displays.
|
|
||||||
//
|
|
||||||
// Kept in the repo for reference. Safe to delete if you're pruning.
|
|
||||||
// =============================================================================
|
|
||||||
|
|
||||||
// import 'package:flutter/material.dart';
|
|
||||||
// import 'package:provider/provider.dart';
|
|
||||||
// import 'package:revoltvpn/logic/app_colors.dart';
|
|
||||||
// import 'package:revoltvpn/logic/session_timer.dart';
|
|
||||||
|
|
||||||
// class ClockDisplay extends StatelessWidget {
|
|
||||||
// const ClockDisplay({super.key});
|
|
||||||
|
|
||||||
// @override
|
|
||||||
// Widget build(BuildContext context) {
|
|
||||||
// return Consumer<SessionTimer>(
|
|
||||||
// builder: (context, timer, _) {
|
|
||||||
// final bool showSyncing = !timer.hasSyncedOnce;
|
|
||||||
|
|
||||||
// return SizedBox(
|
|
||||||
// width: 200,
|
|
||||||
// height: 200,
|
|
||||||
// child: Stack(
|
|
||||||
// alignment: Alignment.center,
|
|
||||||
// children: [
|
|
||||||
// Column(
|
|
||||||
// mainAxisSize: MainAxisSize.min,
|
|
||||||
// children: [
|
|
||||||
// if (showSyncing) ...[
|
|
||||||
// const SizedBox(
|
|
||||||
// width: 32,
|
|
||||||
// height: 32,
|
|
||||||
// child: CircularProgressIndicator(
|
|
||||||
// strokeWidth: 2,
|
|
||||||
// color: AppColors.accent50,
|
|
||||||
// ),
|
|
||||||
// ),
|
|
||||||
// const SizedBox(height: 10),
|
|
||||||
// const Text(
|
|
||||||
// 'Syncing…',
|
|
||||||
// style: TextStyle(
|
|
||||||
// fontSize: 16,
|
|
||||||
// fontWeight: FontWeight.w600,
|
|
||||||
// color: AppColors.accent60,
|
|
||||||
// letterSpacing: 1.5,
|
|
||||||
// ),
|
|
||||||
// ),
|
|
||||||
// ] else ...[
|
|
||||||
// Text(
|
|
||||||
// timer.formatted,
|
|
||||||
// style: const TextStyle(
|
|
||||||
// fontSize: 40,
|
|
||||||
// fontWeight: FontWeight.w800,
|
|
||||||
// color: AppColors.textWhite,
|
|
||||||
// letterSpacing: 2,
|
|
||||||
// shadows: [
|
|
||||||
// Shadow(
|
|
||||||
// color: AppColors.accent50,
|
|
||||||
// blurRadius: 16,
|
|
||||||
// ),
|
|
||||||
// ],
|
|
||||||
// ),
|
|
||||||
// ),
|
|
||||||
// const SizedBox(height: 6),
|
|
||||||
// Row(
|
|
||||||
// mainAxisSize: MainAxisSize.min,
|
|
||||||
// children: [
|
|
||||||
// const Icon(Icons.speed, color: AppColors.textDim, size: 14),
|
|
||||||
// const SizedBox(width: 4),
|
|
||||||
// Text(
|
|
||||||
// timer.currentSpeedKBps > 0.5
|
|
||||||
// ? '${timer.currentSpeedKBps.toStringAsFixed(1)} KB/s'
|
|
||||||
// : 'Idle',
|
|
||||||
// style: const TextStyle(
|
|
||||||
// fontSize: 12,
|
|
||||||
// color: AppColors.textDim,
|
|
||||||
// fontWeight: FontWeight.w500,
|
|
||||||
// ),
|
|
||||||
// ),
|
|
||||||
// ],
|
|
||||||
// ),
|
|
||||||
// ],
|
|
||||||
// ],
|
|
||||||
// ),
|
|
||||||
// ],
|
|
||||||
// ),
|
|
||||||
// );
|
|
||||||
// },
|
|
||||||
// );
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
|
import 'dart:async';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
import 'package:revoltvpn/logic/app_colors.dart';
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
import 'package:revoltvpn/logic/vpn_connection.dart';
|
import 'package:revoltvpn/logic/vpn_connection.dart';
|
||||||
import 'package:revoltvpn/logic/session_timer.dart';
|
import 'package:revoltvpn/logic/session_timer.dart';
|
||||||
import 'package:revoltvpn/logic/ad_manager.dart';
|
import 'package:revoltvpn/logic/ad_manager.dart';
|
||||||
|
import 'package:revoltvpn/screens/settings/in_settings/haptic.dart';
|
||||||
|
|
||||||
class ConnectButton extends StatefulWidget {
|
class ConnectButton extends StatefulWidget {
|
||||||
const ConnectButton({super.key});
|
const ConnectButton({super.key});
|
||||||
@@ -14,7 +15,7 @@ class ConnectButton extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _ConnectButtonState extends State<ConnectButton>
|
class _ConnectButtonState extends State<ConnectButton>
|
||||||
with SingleTickerProviderStateMixin {
|
with SingleTickerProviderStateMixin, WidgetsBindingObserver {
|
||||||
bool _busy = false;
|
bool _busy = false;
|
||||||
DateTime _lastTap = DateTime.now();
|
DateTime _lastTap = DateTime.now();
|
||||||
AnimationController? _pulse;
|
AnimationController? _pulse;
|
||||||
@@ -28,6 +29,7 @@ class _ConnectButtonState extends State<ConnectButton>
|
|||||||
final pulse = AnimationController(vsync: this, duration: const Duration(milliseconds: 2000));
|
final pulse = AnimationController(vsync: this, duration: const Duration(milliseconds: 2000));
|
||||||
_pulse = pulse;
|
_pulse = pulse;
|
||||||
_pulseAnim = Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(parent: pulse, curve: Curves.easeInOut));
|
_pulseAnim = Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(parent: pulse, curve: Curves.easeInOut));
|
||||||
|
WidgetsBinding.instance.addObserver(this);
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
context.read<VpnConnection>().addListener(_onVpnChanged);
|
context.read<VpnConnection>().addListener(_onVpnChanged);
|
||||||
});
|
});
|
||||||
@@ -35,6 +37,7 @@ class _ConnectButtonState extends State<ConnectButton>
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
WidgetsBinding.instance.removeObserver(this);
|
||||||
context.read<VpnConnection>().removeListener(_onVpnChanged);
|
context.read<VpnConnection>().removeListener(_onVpnChanged);
|
||||||
_pulse?.dispose();
|
_pulse?.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
@@ -50,14 +53,26 @@ class _ConnectButtonState extends State<ConnectButton>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||||
|
if (!mounted) return;
|
||||||
|
if (state == AppLifecycleState.paused ||
|
||||||
|
state == AppLifecycleState.detached) {
|
||||||
|
_pulse?.stop();
|
||||||
|
} else if (state == AppLifecycleState.resumed) {
|
||||||
|
final vpn = context.read<VpnConnection>();
|
||||||
|
if (vpn.status == VpnStatus.connected) {
|
||||||
|
_pulse?.repeat(reverse: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _handleTap() async {
|
Future<void> _handleTap() async {
|
||||||
|
|
||||||
final now = DateTime.now();
|
final now = DateTime.now();
|
||||||
if (now.difference(_lastTap).inMilliseconds < 1000) return;
|
if (now.difference(_lastTap).inMilliseconds < 1000) return;
|
||||||
_lastTap = now;
|
_lastTap = now;
|
||||||
|
|
||||||
HapticFeedback.lightImpact();
|
|
||||||
|
|
||||||
final vpn = context.read<VpnConnection>();
|
final vpn = context.read<VpnConnection>();
|
||||||
final timer = context.read<SessionTimer>();
|
final timer = context.read<SessionTimer>();
|
||||||
final ad = context.read<AdManager>();
|
final ad = context.read<AdManager>();
|
||||||
@@ -65,8 +80,8 @@ class _ConnectButtonState extends State<ConnectButton>
|
|||||||
|
|
||||||
if (vpn.status == VpnStatus.connected || vpn.status == VpnStatus.connecting) {
|
if (vpn.status == VpnStatus.connected || vpn.status == VpnStatus.connecting) {
|
||||||
_busy = false;
|
_busy = false;
|
||||||
timer.stop(); // MUST stop timer BEFORE disconnect — prevents auto-reconnect
|
await timer.disconnect();
|
||||||
await vpn.disconnect();
|
unawaited(Haptics.connectionChanged());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,7 +99,10 @@ class _ConnectButtonState extends State<ConnectButton>
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final ok = await vpn.connect();
|
final ok = await vpn.connect();
|
||||||
if (ok) timer.start();
|
if (ok) {
|
||||||
|
timer.start();
|
||||||
|
unawaited(Haptics.connectionChanged());
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (mounted) setState(() => _busy = false);
|
if (mounted) setState(() => _busy = false);
|
||||||
}
|
}
|
||||||
@@ -103,20 +121,41 @@ class _ConnectButtonState extends State<ConnectButton>
|
|||||||
child: _pulseAnim != null
|
child: _pulseAnim != null
|
||||||
? AnimatedBuilder(
|
? AnimatedBuilder(
|
||||||
animation: _pulseAnim!,
|
animation: _pulseAnim!,
|
||||||
builder: (_, __) => _buildCircle(isConnected, spinning, _pulseValue),
|
child: _buildInner(spinning),
|
||||||
|
builder: (_, child) =>
|
||||||
|
_buildCircle(isConnected, _pulseValue, child),
|
||||||
)
|
)
|
||||||
: _buildCircle(isConnected, spinning, 0),
|
: _buildCircle(isConnected, 0, _buildInner(spinning)),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildCircle(bool isConnected, bool spinning, double pulse) {
|
Widget _buildInner(bool spinning) {
|
||||||
|
if (spinning) {
|
||||||
|
return const Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 36,
|
||||||
|
height: 36,
|
||||||
|
child: CircularProgressIndicator(
|
||||||
|
strokeWidth: 2.5,
|
||||||
|
color: AppColors.accent70,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.all(14),
|
||||||
|
child: Image.asset('assets/brand.png', fit: BoxFit.contain),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildCircle(bool isConnected, double pulse, Widget? child) {
|
||||||
final glowAlpha = isConnected ? ((0.3 + pulse * 0.25) * 255).round() : 0;
|
final glowAlpha = isConnected ? ((0.3 + pulse * 0.25) * 255).round() : 0;
|
||||||
final glowRadius = isConnected ? 18.0 + (pulse * 14) : 0.0;
|
final glowRadius = isConnected ? 18.0 + (pulse * 14) : 0.0;
|
||||||
|
|
||||||
return Container(
|
return Container(
|
||||||
width: 260, // <-- CHANGE ME: circle size
|
width: 260,
|
||||||
height: 260,
|
height: 260,
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
shape: BoxShape.circle,
|
shape: BoxShape.circle,
|
||||||
@@ -126,21 +165,17 @@ class _ConnectButtonState extends State<ConnectButton>
|
|||||||
width: isConnected ? 2.5 : 1.5,
|
width: isConnected ? 2.5 : 1.5,
|
||||||
),
|
),
|
||||||
boxShadow: isConnected
|
boxShadow: isConnected
|
||||||
? [BoxShadow(color: Color.fromARGB(glowAlpha, 255, 214, 0), blurRadius: glowRadius, spreadRadius: glowRadius * 0.3)]
|
? [
|
||||||
|
BoxShadow(
|
||||||
|
color: Color.fromARGB(glowAlpha, 255, 214, 0),
|
||||||
|
blurRadius: glowRadius,
|
||||||
|
spreadRadius: glowRadius * 0.3,
|
||||||
|
)
|
||||||
|
]
|
||||||
: [],
|
: [],
|
||||||
),
|
),
|
||||||
clipBehavior: Clip.hardEdge,
|
clipBehavior: Clip.hardEdge,
|
||||||
child: spinning
|
child: child,
|
||||||
? const Center(
|
|
||||||
child: SizedBox(
|
|
||||||
width: 36, height: 36,
|
|
||||||
child: CircularProgressIndicator(strokeWidth: 2.5, color: AppColors.accent70),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: Padding(
|
|
||||||
padding: const EdgeInsets.all(14), // <-- CHANGE ME: brand.png padding from edge
|
|
||||||
child: Image.asset('assets/brand.png', fit: BoxFit.contain),
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
// lib/components/data_disclosure_dialog.dart
|
||||||
|
// First-launch data disclosure dialog — Google Play Data safety section requirement.
|
||||||
|
// Shows once per install; preference persisted in SharedPreferences.
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
|
|
||||||
|
class DataDisclosureDialog {
|
||||||
|
DataDisclosureDialog._();
|
||||||
|
|
||||||
|
static const _key = 'data_disclosure_accepted';
|
||||||
|
|
||||||
|
/// Shows the disclosure dialog if the user hasn't accepted it yet.
|
||||||
|
/// Call once after the main screen is mounted (post-frame callback).
|
||||||
|
static Future<void> showIfFirstLaunch(BuildContext context) async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
if (prefs.getBool(_key) == true) return; // Already accepted.
|
||||||
|
|
||||||
|
if (!context.mounted) return;
|
||||||
|
|
||||||
|
await showDialog(
|
||||||
|
context: context,
|
||||||
|
barrierDismissible: false, // Must tap Continue — no tap-outside dismiss.
|
||||||
|
builder: (_) => _DisclosureDialog(
|
||||||
|
onContinue: () {
|
||||||
|
prefs.setBool(_key, true);
|
||||||
|
Navigator.of(context).pop(); // Dismiss the dialog.
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DisclosureDialog extends StatelessWidget {
|
||||||
|
final VoidCallback onContinue;
|
||||||
|
|
||||||
|
const _DisclosureDialog({required this.onContinue});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Dialog(
|
||||||
|
backgroundColor: AppColors.bgCard,
|
||||||
|
insetPadding: const EdgeInsets.symmetric(horizontal: 28, vertical: 40),
|
||||||
|
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(24, 28, 24, 20),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
// Title
|
||||||
|
const Text(
|
||||||
|
'Before you connect',
|
||||||
|
style: TextStyle(
|
||||||
|
color: AppColors.textWhite,
|
||||||
|
fontSize: 20,
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
|
||||||
|
// Body
|
||||||
|
const Text(
|
||||||
|
'Revolt VPN creates a secure VPN tunnel to protect your '
|
||||||
|
'traffic. To enforce your data/time quota, we log your '
|
||||||
|
'connection duration and data usage, linked to a randomly '
|
||||||
|
'generated device ID — not to your identity. We do not log '
|
||||||
|
'or monitor the content of your traffic. We do not share '
|
||||||
|
'your data with third parties. The full policy is in the '
|
||||||
|
'sidebar menu under "Privacy Policy".',
|
||||||
|
style: TextStyle(
|
||||||
|
color: AppColors.textMuted,
|
||||||
|
fontSize: 14,
|
||||||
|
height: 1.5,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
|
||||||
|
// Continue button — full-width, accent
|
||||||
|
SizedBox(
|
||||||
|
width: double.infinity,
|
||||||
|
child: ElevatedButton(
|
||||||
|
onPressed: onContinue,
|
||||||
|
style: ElevatedButton.styleFrom(
|
||||||
|
backgroundColor: AppColors.accent,
|
||||||
|
foregroundColor: AppColors.bgDeep,
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||||
|
shape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
),
|
||||||
|
textStyle: const TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: const Text('Continue'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:math';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
|
import 'package:revoltvpn/screens/settings/in_settings/lightning.dart';
|
||||||
|
|
||||||
|
/// 2D lightning bolt — a jagged yellow line from top to bottom with glow.
|
||||||
|
|
||||||
|
class LightningEffect extends StatefulWidget {
|
||||||
|
|
||||||
|
final int minIntervalSec;
|
||||||
|
|
||||||
|
final int maxIntervalSec;
|
||||||
|
|
||||||
|
final double doubleChance;
|
||||||
|
|
||||||
|
const LightningEffect({
|
||||||
|
super.key,
|
||||||
|
this.minIntervalSec = 2,
|
||||||
|
this.maxIntervalSec = 10,
|
||||||
|
this.doubleChance = 0.2,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<LightningEffect> createState() => _LightningEffectState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _LightningEffectState extends State<LightningEffect>
|
||||||
|
with SingleTickerProviderStateMixin {
|
||||||
|
late final AnimationController _ctrl;
|
||||||
|
Timer? _timer;
|
||||||
|
final _random = Random();
|
||||||
|
|
||||||
|
LightningBolt? _bolt;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_ctrl = AnimationController(vsync: this, duration: const Duration(milliseconds: 400));
|
||||||
|
lightningEnabled.addListener(_onEnabledChanged);
|
||||||
|
if (lightningEnabled.value) _scheduleNext();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onEnabledChanged() {
|
||||||
|
if (lightningEnabled.value) {
|
||||||
|
_scheduleNext();
|
||||||
|
} else {
|
||||||
|
_timer?.cancel();
|
||||||
|
_ctrl.stop();
|
||||||
|
_bolt = null;
|
||||||
|
}
|
||||||
|
if (mounted) setState(() {});
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
lightningEnabled.removeListener(_onEnabledChanged);
|
||||||
|
_timer?.cancel();
|
||||||
|
_ctrl.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scheduleNext() {
|
||||||
|
final secs = widget.minIntervalSec +
|
||||||
|
_random.nextInt(widget.maxIntervalSec - widget.minIntervalSec + 1);
|
||||||
|
_timer = Timer(Duration(seconds: secs), _strike);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _strike() {
|
||||||
|
if (!mounted || !lightningEnabled.value) return;
|
||||||
|
_bolt = LightningBolt.random(_random);
|
||||||
|
_ctrl.forward(from: 0.0);
|
||||||
|
|
||||||
|
if (_random.nextDouble() < widget.doubleChance) {
|
||||||
|
Future.delayed(const Duration(milliseconds: 120), () {
|
||||||
|
if (mounted && lightningEnabled.value) {
|
||||||
|
_bolt = LightningBolt.random(_random);
|
||||||
|
_ctrl.forward(from: 0.0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
_scheduleNext();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sharp flash curve: quick on, quick off. No slow fade.
|
||||||
|
double _opacity(double t) {
|
||||||
|
if (t < 0.08) return t / 0.08; // fast ramp
|
||||||
|
return 1.0 - ((t - 0.08) / 0.92); // linear decay
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (!lightningEnabled.value) return const SizedBox.shrink();
|
||||||
|
return AnimatedBuilder(
|
||||||
|
animation: _ctrl,
|
||||||
|
builder: (_, child) {
|
||||||
|
final raw = _opacity(_ctrl.value);
|
||||||
|
if (raw <= 0.02 || _bolt == null) return const SizedBox.shrink();
|
||||||
|
|
||||||
|
return IgnorePointer(
|
||||||
|
child: LayoutBuilder(
|
||||||
|
builder: (ctx, constraints) {
|
||||||
|
final sz = Size(constraints.maxWidth, constraints.maxHeight);
|
||||||
|
return CustomPaint(
|
||||||
|
size: sz,
|
||||||
|
painter: _LightningPainter(
|
||||||
|
bolt: _bolt!,
|
||||||
|
opacity: raw,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// A single bolt defined by a list of 2D points (0.0–1.0 in width×height space).
|
||||||
|
class LightningBolt {
|
||||||
|
final List<Offset> mainPath;
|
||||||
|
final List<List<Offset>> branches; // 0–2 forks off the main path
|
||||||
|
|
||||||
|
const LightningBolt({required this.mainPath, this.branches = const []});
|
||||||
|
|
||||||
|
/// Generate a random bolt. The path always starts near the top-center
|
||||||
|
/// and ends near the bottom, zigzagging left/right along the way.
|
||||||
|
factory LightningBolt.random(Random rng) {
|
||||||
|
final points = <Offset>[];
|
||||||
|
|
||||||
|
// Start: top, slight horizontal offset
|
||||||
|
double x = 0.5 + (rng.nextDouble() - 0.5) * 0.15;
|
||||||
|
points.add(Offset(x, 0.0));
|
||||||
|
|
||||||
|
// Zigzag down — 6–10 segments
|
||||||
|
final segments = 6 + rng.nextInt(5);
|
||||||
|
for (int i = 1; i < segments; i++) {
|
||||||
|
final y = i / segments;
|
||||||
|
// Random horizontal offset — each segment adds jitter
|
||||||
|
x += (rng.nextDouble() - 0.5) * 0.25;
|
||||||
|
x = x.clamp(0.05, 0.95); // stay on screen
|
||||||
|
points.add(Offset(x, y));
|
||||||
|
}
|
||||||
|
|
||||||
|
// End: bottom
|
||||||
|
points.add(Offset(x.clamp(0.1, 0.9), 1.0));
|
||||||
|
|
||||||
|
// Branches — 0–2 forks from random points along the main path
|
||||||
|
final branches = <List<Offset>>[];
|
||||||
|
final branchCount = rng.nextInt(3);
|
||||||
|
for (int b = 0; b < branchCount; b++) {
|
||||||
|
final branch = <Offset>[];
|
||||||
|
final startIdx = 1 + rng.nextInt(points.length - 2);
|
||||||
|
final start = points[startIdx];
|
||||||
|
branch.add(start);
|
||||||
|
|
||||||
|
double bx = start.dx;
|
||||||
|
double by = start.dy;
|
||||||
|
final branchLen = 2 + rng.nextInt(3);
|
||||||
|
for (int j = 0; j < branchLen; j++) {
|
||||||
|
by += (0.05 + rng.nextDouble() * 0.12);
|
||||||
|
bx += (rng.nextDouble() - 0.5) * 0.3;
|
||||||
|
bx = bx.clamp(0.02, 0.98);
|
||||||
|
by = by.clamp(0.0, 1.0);
|
||||||
|
branch.add(Offset(bx, by));
|
||||||
|
}
|
||||||
|
branches.add(branch);
|
||||||
|
}
|
||||||
|
|
||||||
|
return LightningBolt(mainPath: points, branches: branches);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class _LightningPainter extends CustomPainter {
|
||||||
|
final LightningBolt bolt;
|
||||||
|
final double opacity;
|
||||||
|
|
||||||
|
_LightningPainter({required this.bolt, required this.opacity});
|
||||||
|
|
||||||
|
@override
|
||||||
|
void paint(Canvas canvas, Size size) {
|
||||||
|
final toScreen = (Offset p) => Offset(p.dx * size.width, p.dy * size.height);
|
||||||
|
final scaledMain = bolt.mainPath.map(toScreen).toList();
|
||||||
|
final scaledBranches = bolt.branches
|
||||||
|
.map((b) => b.map(toScreen).toList())
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
final baseColor = AppColors.accent.withAlpha((opacity * 255).round());
|
||||||
|
final glowColor = AppColors.accent.withAlpha((opacity * 0.35 * 255).round());
|
||||||
|
|
||||||
|
// Glow
|
||||||
|
final glowPaint = Paint()
|
||||||
|
..color = glowColor
|
||||||
|
..strokeWidth = 18
|
||||||
|
..strokeCap = StrokeCap.round
|
||||||
|
..strokeJoin = StrokeJoin.round
|
||||||
|
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 8)
|
||||||
|
..style = PaintingStyle.stroke;
|
||||||
|
|
||||||
|
_drawPath(canvas, scaledMain, scaledBranches, glowPaint);
|
||||||
|
|
||||||
|
// Core
|
||||||
|
final corePaint = Paint()
|
||||||
|
..color = baseColor
|
||||||
|
..strokeWidth = 5
|
||||||
|
..strokeCap = StrokeCap.round
|
||||||
|
..strokeJoin = StrokeJoin.round
|
||||||
|
..style = PaintingStyle.stroke;
|
||||||
|
|
||||||
|
_drawPath(canvas, scaledMain, scaledBranches, corePaint);
|
||||||
|
|
||||||
|
// Hot center
|
||||||
|
if (opacity > 0.6) {
|
||||||
|
final hotPaint = Paint()
|
||||||
|
..color = Colors.white.withAlpha((opacity * 180).round())
|
||||||
|
..strokeWidth = 2
|
||||||
|
..strokeCap = StrokeCap.round
|
||||||
|
..strokeJoin = StrokeJoin.round
|
||||||
|
..style = PaintingStyle.stroke;
|
||||||
|
|
||||||
|
_drawPath(canvas, scaledMain, scaledBranches, hotPaint);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _drawPath(Canvas canvas, List<Offset> main,
|
||||||
|
List<List<Offset>> branches, Paint paint) {
|
||||||
|
final mainPath = Path()..moveTo(main.first.dx, main.first.dy);
|
||||||
|
for (int i = 1; i < main.length; i++) {
|
||||||
|
mainPath.lineTo(main[i].dx, main[i].dy);
|
||||||
|
}
|
||||||
|
canvas.drawPath(mainPath, paint);
|
||||||
|
|
||||||
|
for (final branch in branches) {
|
||||||
|
final bPath = Path()..moveTo(branch.first.dx, branch.first.dy);
|
||||||
|
for (int i = 1; i < branch.length; i++) {
|
||||||
|
bPath.lineTo(branch[i].dx, branch[i].dy);
|
||||||
|
}
|
||||||
|
canvas.drawPath(bPath, paint);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool shouldRepaint(covariant _LightningPainter old) =>
|
||||||
|
bolt != old.bolt || opacity != old.opacity;
|
||||||
|
}
|
||||||
@@ -1,10 +1,18 @@
|
|||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
import 'dart:ui' as ui;
|
||||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||||
|
|
||||||
class VpnNotificationManager {
|
class VpnNotificationManager {
|
||||||
static final FlutterLocalNotificationsPlugin _plugin =
|
static final FlutterLocalNotificationsPlugin _plugin =
|
||||||
FlutterLocalNotificationsPlugin();
|
FlutterLocalNotificationsPlugin();
|
||||||
static bool _initialized = false;
|
static bool _initialized = false;
|
||||||
|
static String? _lastTimeLeft;
|
||||||
|
static String? _lastSpeedKbps;
|
||||||
|
|
||||||
|
// Android channels are immutable — bump this if settings change.
|
||||||
|
static const _channelId = 'revolt_vpn_v4';
|
||||||
|
static const _channelName = 'Revolt VPN';
|
||||||
|
static const _notifId = 888;
|
||||||
|
|
||||||
static Future<void> init() async {
|
static Future<void> init() async {
|
||||||
if (_initialized) return;
|
if (_initialized) return;
|
||||||
@@ -15,7 +23,6 @@ class VpnNotificationManager {
|
|||||||
|
|
||||||
await _plugin.initialize(initSettings);
|
await _plugin.initialize(initSettings);
|
||||||
|
|
||||||
// Request POST_NOTIFICATIONS permission on Android 13+
|
|
||||||
if (Platform.isAndroid) {
|
if (Platform.isAndroid) {
|
||||||
final androidPlugin = _plugin
|
final androidPlugin = _plugin
|
||||||
.resolvePlatformSpecificImplementation<
|
.resolvePlatformSpecificImplementation<
|
||||||
@@ -26,77 +33,61 @@ class VpnNotificationManager {
|
|||||||
_initialized = true;
|
_initialized = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
static String? _lastTimeLeft;
|
|
||||||
static String? _lastSpeedKbps;
|
|
||||||
|
|
||||||
static Future<void> showOrUpdateStatus({
|
static Future<void> showOrUpdateStatus({
|
||||||
required String timeLeft,
|
required String timeLeft,
|
||||||
required String speedKbps,
|
required String speedKbps,
|
||||||
}) async {
|
}) async {
|
||||||
// Skip update if nothing changed — prevents notification flicker
|
|
||||||
// on Android skins that animate every notification update.
|
|
||||||
if (timeLeft == _lastTimeLeft && speedKbps == _lastSpeedKbps) return;
|
if (timeLeft == _lastTimeLeft && speedKbps == _lastSpeedKbps) return;
|
||||||
_lastTimeLeft = timeLeft;
|
_lastTimeLeft = timeLeft;
|
||||||
_lastSpeedKbps = speedKbps;
|
_lastSpeedKbps = speedKbps;
|
||||||
|
|
||||||
if (!_initialized) await init();
|
if (!_initialized) await init();
|
||||||
|
|
||||||
// NOTE: The channel ID includes 'v2' to force Android to create a fresh
|
final bodyText = 'Time: $timeLeft • $speedKbps';
|
||||||
// notification channel. Android channels are immutable once created — if
|
|
||||||
// the old channel was created without 'ongoing: true', users would be
|
final bigPictureStyle = BigPictureStyleInformation(
|
||||||
// stuck with a swipeable notification forever.
|
const DrawableResourceAndroidBitmap('notification_banner'),
|
||||||
const androidDetails = AndroidNotificationDetails(
|
largeIcon: const DrawableResourceAndroidBitmap('notification_icon'),
|
||||||
'revolt_vpn_status_v2',
|
contentTitle: 'Revolt VPN',
|
||||||
'VPN Status',
|
summaryText: bodyText,
|
||||||
channelDescription: 'Shown while VPN is active — non-dismissable',
|
htmlFormatContentTitle: false,
|
||||||
|
htmlFormatSummaryText: false,
|
||||||
|
);
|
||||||
|
|
||||||
|
final androidDetails = AndroidNotificationDetails(
|
||||||
|
_channelId,
|
||||||
|
_channelName,
|
||||||
|
channelDescription: 'Session timer and speed',
|
||||||
importance: Importance.low,
|
importance: Importance.low,
|
||||||
priority: Priority.low,
|
priority: Priority.low,
|
||||||
// Non-dismissable while VPN is running
|
|
||||||
ongoing: true,
|
ongoing: true,
|
||||||
autoCancel: false,
|
autoCancel: false,
|
||||||
// Silent updates — no sound or vibration each time stats refresh
|
|
||||||
playSound: false,
|
playSound: false,
|
||||||
enableVibration: false,
|
enableVibration: false,
|
||||||
onlyAlertOnce: true,
|
|
||||||
// Hide the auto-generated timestamp
|
|
||||||
showWhen: false,
|
showWhen: false,
|
||||||
// Show on lock screen
|
|
||||||
visibility: NotificationVisibility.public,
|
visibility: NotificationVisibility.public,
|
||||||
// Extra insurance against swipe-to-dismiss on aggressive Android skins
|
|
||||||
usesChronometer: false,
|
usesChronometer: false,
|
||||||
category: AndroidNotificationCategory.service,
|
category: AndroidNotificationCategory.service,
|
||||||
|
colorized: true,
|
||||||
|
color: const ui.Color(0xFF0D1117),
|
||||||
|
styleInformation: bigPictureStyle,
|
||||||
);
|
);
|
||||||
|
|
||||||
const notificationDetails = NotificationDetails(android: androidDetails);
|
final details = NotificationDetails(android: androidDetails);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await _plugin.show(
|
await _plugin.show(_notifId, _channelName, bodyText, details);
|
||||||
888, // Fixed ID — always updates the same notification
|
|
||||||
'REVOLT VPN Active',
|
|
||||||
'Time: $timeLeft • $speedKbps',
|
|
||||||
notificationDetails,
|
|
||||||
);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// If showing fails (e.g. permission revoked), try to recover by
|
|
||||||
// re-initializing and retrying once.
|
|
||||||
_initialized = false;
|
_initialized = false;
|
||||||
try {
|
try {
|
||||||
await init();
|
await init();
|
||||||
await _plugin.show(
|
await _plugin.show(_notifId, _channelName, bodyText, details);
|
||||||
888,
|
} catch (_) {}
|
||||||
'REVOLT VPN Active',
|
|
||||||
'Time: $timeLeft • $speedKbps',
|
|
||||||
notificationDetails,
|
|
||||||
);
|
|
||||||
} catch (_) {
|
|
||||||
// Give up — the VPN still works, just without the notification.
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static Future<void> cancel() async {
|
static Future<void> cancel() async {
|
||||||
if (!_initialized) return;
|
if (!_initialized) return;
|
||||||
await _plugin.cancel(888);
|
await _plugin.cancel(_notifId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
import 'dart:math';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/scheduler.dart';
|
||||||
|
import 'package:revoltvpn/screens/settings/in_settings/rain.dart';
|
||||||
|
|
||||||
|
/// Subtle animated rain effect — sits behind all UI as a full-screen overlay.
|
||||||
|
///
|
||||||
|
/// Usage (in a Stack, as the first child so it renders behind everything):
|
||||||
|
|
||||||
|
class RainEffect extends StatefulWidget {
|
||||||
|
final int dropCount;
|
||||||
|
|
||||||
|
final Color color;
|
||||||
|
|
||||||
|
final double minLength;
|
||||||
|
|
||||||
|
final double maxLength;
|
||||||
|
|
||||||
|
final double windDrift;
|
||||||
|
|
||||||
|
const RainEffect({
|
||||||
|
super.key,
|
||||||
|
this.dropCount = 150,
|
||||||
|
this.color = const Color(0xFFE8EAF6),
|
||||||
|
this.minLength = 12,
|
||||||
|
this.maxLength = 44,
|
||||||
|
this.windDrift = 4.0,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<RainEffect> createState() => _RainEffectState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RainEffectState extends State<RainEffect>
|
||||||
|
with SingleTickerProviderStateMixin {
|
||||||
|
late final Ticker _ticker;
|
||||||
|
final _drops = <_Drop>[];
|
||||||
|
final _random = Random();
|
||||||
|
final _repaint = ValueNotifier<int>(0);
|
||||||
|
Duration _last = Duration.zero;
|
||||||
|
|
||||||
|
// Lifecycle
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
for (int i = 0; i < widget.dropCount; i++) {
|
||||||
|
_drops.add(
|
||||||
|
_Drop.spawn(_random, widget.minLength, widget.maxLength, widget.color));
|
||||||
|
}
|
||||||
|
_ticker = createTicker(_onTick);
|
||||||
|
rainEnabled.addListener(_onEnabledChanged);
|
||||||
|
if (rainEnabled.value) _ticker.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
rainEnabled.removeListener(_onEnabledChanged);
|
||||||
|
_ticker.dispose();
|
||||||
|
_repaint.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onEnabledChanged() {
|
||||||
|
if (rainEnabled.value) {
|
||||||
|
// Ticker elapsed restarts at zero; a stale _last makes the first dt negative.
|
||||||
|
_last = Duration.zero;
|
||||||
|
_ticker.start();
|
||||||
|
} else {
|
||||||
|
_ticker.stop();
|
||||||
|
}
|
||||||
|
if (mounted) setState(() {});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tick
|
||||||
|
|
||||||
|
void _onTick(Duration now) {
|
||||||
|
double dt = 0.016; // ~60 fps fallback on first tick
|
||||||
|
if (_last != Duration.zero) {
|
||||||
|
dt = (now - _last).inMicroseconds / 1000000.0;
|
||||||
|
dt = dt.clamp(0.0, 0.1);
|
||||||
|
}
|
||||||
|
_last = now;
|
||||||
|
|
||||||
|
for (final d in _drops) {
|
||||||
|
d.y += d.speed * dt;
|
||||||
|
if (d.y > 1.08) {
|
||||||
|
d.spawn(_random, widget.minLength, widget.maxLength, widget.color);
|
||||||
|
d.y = -0.06 - _random.nextDouble() * 0.08;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_repaint.value++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (!rainEnabled.value) return const SizedBox.shrink();
|
||||||
|
return CustomPaint(
|
||||||
|
painter: _RainPainter(
|
||||||
|
drops: _drops,
|
||||||
|
windDrift: widget.windDrift,
|
||||||
|
repaint: _repaint,
|
||||||
|
),
|
||||||
|
size: Size.infinite,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
// Drop model
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class _Drop {
|
||||||
|
double x;
|
||||||
|
double y;
|
||||||
|
double speed;
|
||||||
|
double length;
|
||||||
|
Color color;
|
||||||
|
|
||||||
|
_Drop({
|
||||||
|
required this.x,
|
||||||
|
required this.y,
|
||||||
|
required this.speed,
|
||||||
|
required this.length,
|
||||||
|
required this.color,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Create a drop at a random position anywhere on screen.
|
||||||
|
factory _Drop.spawn(Random r, double minLen, double maxLen, Color base) {
|
||||||
|
return _Drop(
|
||||||
|
x: r.nextDouble(),
|
||||||
|
y: r.nextDouble(),
|
||||||
|
speed: 0.30 + r.nextDouble() * 0.55,
|
||||||
|
length: minLen + r.nextDouble() * (maxLen - minLen),
|
||||||
|
color: base.withAlpha(((0.05 + r.nextDouble() * 0.12) * 255).round()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-randomise all properties (call when recycling a drop to the top).
|
||||||
|
void spawn(Random r, double minLen, double maxLen, Color base) {
|
||||||
|
x = r.nextDouble();
|
||||||
|
speed = 0.30 + r.nextDouble() * 0.55;
|
||||||
|
length = minLen + r.nextDouble() * (maxLen - minLen);
|
||||||
|
color = base.withAlpha(((0.05 + r.nextDouble() * 0.12) * 255).round());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
// Painter
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class _RainPainter extends CustomPainter {
|
||||||
|
final List<_Drop> drops;
|
||||||
|
final double windDrift;
|
||||||
|
|
||||||
|
_RainPainter({
|
||||||
|
required this.drops,
|
||||||
|
required this.windDrift,
|
||||||
|
required Listenable repaint,
|
||||||
|
}) : super(repaint: repaint);
|
||||||
|
|
||||||
|
@override
|
||||||
|
void paint(Canvas canvas, Size size) {
|
||||||
|
final paint = Paint()
|
||||||
|
..strokeCap = StrokeCap.round
|
||||||
|
..strokeWidth = 1.5;
|
||||||
|
|
||||||
|
for (final d in drops) {
|
||||||
|
final sx = d.x * size.width;
|
||||||
|
final sy = d.y * size.height;
|
||||||
|
final ex = sx - windDrift; // slight leftward slant
|
||||||
|
final ey = sy + d.length;
|
||||||
|
|
||||||
|
paint.color = d.color;
|
||||||
|
canvas.drawLine(Offset(sx, sy), Offset(ex, ey), paint);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool shouldRepaint(_RainPainter old) => false; // repaint listenable drives frames
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ class DiscordLinkButton extends StatelessWidget {
|
|||||||
const DiscordLinkButton({super.key});
|
const DiscordLinkButton({super.key});
|
||||||
|
|
||||||
static Future<void> launchDiscord() async {
|
static Future<void> launchDiscord() async {
|
||||||
final Uri url = Uri.parse('https://discord.gg/revoltvpn');
|
final Uri url = Uri.parse('https://discord.gg/y7SXpjr2ff');
|
||||||
if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
|
if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
|
||||||
debugPrint('Could not launch $url');
|
debugPrint('Could not launch $url');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
|
import 'package:revoltvpn/screens/settings/settings_screen.dart';
|
||||||
|
|
||||||
|
// ── lib/components/sidebar_contents/settings.dart ────────────────────────────
|
||||||
|
// Thin sidebar row — taps navigate to the full SettingsScreen.
|
||||||
|
// The actual settings UI lives in lib/screens/settings/ (separate folder,
|
||||||
|
// one file per feature).
|
||||||
|
|
||||||
|
class SettingsButton extends StatelessWidget {
|
||||||
|
const SettingsButton({super.key});
|
||||||
|
|
||||||
|
// Opens the settings page sliding in from the right — matches the
|
||||||
|
// sidebar end-drawer animation so it feels like one continuous motion.
|
||||||
|
static PageRoute<void> _route() => PageRouteBuilder<void>(
|
||||||
|
transitionDuration: const Duration(milliseconds: 300),
|
||||||
|
reverseTransitionDuration: const Duration(milliseconds: 250),
|
||||||
|
pageBuilder: (_, __, ___) => const SettingsScreen(),
|
||||||
|
transitionsBuilder: (_, animation, __, child) {
|
||||||
|
return SlideTransition(
|
||||||
|
position: Tween<Offset>(
|
||||||
|
begin: const Offset(1.0, 0.0),
|
||||||
|
end: Offset.zero,
|
||||||
|
).animate(
|
||||||
|
CurvedAnimation(parent: animation, curve: Curves.easeOut),
|
||||||
|
),
|
||||||
|
child: child,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
static void openWithNavigator(NavigatorState navigator) {
|
||||||
|
if (!navigator.mounted) return;
|
||||||
|
navigator.push(_route());
|
||||||
|
}
|
||||||
|
|
||||||
|
static void open(BuildContext context) {
|
||||||
|
openWithNavigator(Navigator.of(context, rootNavigator: true));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return IconButton(
|
||||||
|
icon: const Icon(Icons.settings, color: AppColors.textWhite, size: 28),
|
||||||
|
onPressed: () => open(context),
|
||||||
|
tooltip: 'Settings',
|
||||||
|
splashRadius: 24,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:url_launcher/url_launcher.dart';
|
||||||
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
|
|
||||||
|
class WebsiteButton extends StatelessWidget {
|
||||||
|
const WebsiteButton({super.key});
|
||||||
|
|
||||||
|
static Future<void> launchWebsite() async {
|
||||||
|
final Uri url = Uri.parse('https://userevolt.app');
|
||||||
|
if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
|
||||||
|
debugPrint('Could not launch $url');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return IconButton(
|
||||||
|
icon: const Icon(Icons.language, color: AppColors.textWhite, size: 28),
|
||||||
|
onPressed: launchWebsite,
|
||||||
|
tooltip: 'Website',
|
||||||
|
splashRadius: 24,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,43 @@
|
|||||||
|
import 'dart:async';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:package_info_plus/package_info_plus.dart';
|
||||||
import 'package:revoltvpn/logic/app_colors.dart';
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
import 'package:revoltvpn/components/sidebar_contents/gdpr_button.dart';
|
import 'package:revoltvpn/components/sidebar_contents/gdpr_button.dart';
|
||||||
import 'package:revoltvpn/components/sidebar_contents/privacy_policy_button.dart';
|
import 'package:revoltvpn/components/sidebar_contents/privacy_policy_button.dart';
|
||||||
import 'package:revoltvpn/components/sidebar_contents/info_button.dart';
|
import 'package:revoltvpn/components/sidebar_contents/info_button.dart';
|
||||||
import 'package:revoltvpn/components/sidebar_contents/discord_link_button.dart';
|
import 'package:revoltvpn/components/sidebar_contents/discord_link_button.dart';
|
||||||
|
import 'package:revoltvpn/components/sidebar_contents/website_button.dart';
|
||||||
|
import 'package:revoltvpn/components/sidebar_contents/settings.dart';
|
||||||
|
import 'package:revoltvpn/logic/updater.dart';
|
||||||
|
|
||||||
class SidebarDrawer extends StatelessWidget {
|
class SidebarDrawer extends StatefulWidget {
|
||||||
const SidebarDrawer({super.key});
|
const SidebarDrawer({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<SidebarDrawer> createState() => _SidebarDrawerState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _SidebarDrawerState extends State<SidebarDrawer> {
|
||||||
|
String _version = '';
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_loadVersion();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _loadVersion() async {
|
||||||
|
try {
|
||||||
|
final info = await PackageInfo.fromPlatform();
|
||||||
|
debugPrint('[Sidebar] PackageInfo version: ${info.version} '
|
||||||
|
'(build: ${info.buildNumber})');
|
||||||
|
if (mounted) setState(() => _version = info.version);
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[Sidebar] PackageInfo failed: $e');
|
||||||
|
if (mounted) setState(() => _version = '?.?.?');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Drawer(
|
return Drawer(
|
||||||
@@ -84,12 +114,44 @@ class SidebarDrawer extends StatelessWidget {
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
|
||||||
|
_Row(
|
||||||
|
icon: Icons.language,
|
||||||
|
label: 'Website',
|
||||||
|
onTap: () {
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
WebsiteButton.launchWebsite();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
|
_Row(
|
||||||
|
icon: Icons.settings,
|
||||||
|
label: 'Settings',
|
||||||
|
onTap: () {
|
||||||
|
final navigator = Navigator.of(context, rootNavigator: true);
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
SettingsButton.openWithNavigator(navigator);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
|
_Row(
|
||||||
|
icon: Icons.system_update_alt,
|
||||||
|
label: 'Check for updates',
|
||||||
|
onTap: () {
|
||||||
|
final navigator = Navigator.of(context, rootNavigator: true);
|
||||||
|
final messenger = ScaffoldMessenger.of(context);
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
unawaited(
|
||||||
|
Updater.check(navigator: navigator, messenger: messenger),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
const Spacer(),
|
const Spacer(),
|
||||||
|
|
||||||
const Padding(
|
Padding(
|
||||||
padding: EdgeInsets.all(20),
|
padding: const EdgeInsets.all(20),
|
||||||
child: Text('ReVoltVPN · v1.0.6', textAlign: TextAlign.center,
|
child: Text('ReVoltVPN · v$_version', textAlign: TextAlign.center,
|
||||||
style: TextStyle(color: AppColors.slate, fontSize: 11, letterSpacing: 1),
|
style: const TextStyle(color: AppColors.slate, fontSize: 11, letterSpacing: 1),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -8,10 +8,11 @@ class SpeedBox extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Consumer<SessionTimer>(
|
return Selector<SessionTimer, double>(
|
||||||
builder: (context, timer, _) {
|
selector: (_, timer) => timer.currentSpeedKBps,
|
||||||
final speed = timer.currentSpeedKBps > 0.5
|
builder: (context, speedKBps, _) {
|
||||||
? '${timer.currentSpeedKBps.toStringAsFixed(1)} KB/s'
|
final speed = speedKBps > 0.5
|
||||||
|
? '${speedKBps.toStringAsFixed(1)} KB/s'
|
||||||
: 'Idle';
|
: 'Idle';
|
||||||
|
|
||||||
return Container(
|
return Container(
|
||||||
|
|||||||
@@ -3,7 +3,19 @@ import 'package:provider/provider.dart';
|
|||||||
import 'package:revoltvpn/logic/app_colors.dart';
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
import 'package:revoltvpn/logic/vpn_connection.dart';
|
import 'package:revoltvpn/logic/vpn_connection.dart';
|
||||||
import 'package:revoltvpn/logic/session_timer.dart';
|
import 'package:revoltvpn/logic/session_timer.dart';
|
||||||
|
import 'package:revoltvpn/logic/server_list.dart';
|
||||||
import 'package:revoltvpn/components/online_dot.dart';
|
import 'package:revoltvpn/components/online_dot.dart';
|
||||||
|
import 'package:revoltvpn/screens/server_selector/selection_screen.dart';
|
||||||
|
|
||||||
|
// ── lib/components/status_bar.dart ──────────────────────────────────────────
|
||||||
|
// Two-card layout at the bottom of the main screen.
|
||||||
|
//
|
||||||
|
// Top card: server location from ServerList provider (flag + city).
|
||||||
|
// Tappable → opens server selector. Always visible.
|
||||||
|
// Bottom card: connection status (health dot + label + lock icon).
|
||||||
|
//
|
||||||
|
// Separated into two rows — no more RenderFlex overflow and ready for
|
||||||
|
// multi-server picker.
|
||||||
|
|
||||||
class StatusBar extends StatelessWidget {
|
class StatusBar extends StatelessWidget {
|
||||||
const StatusBar({super.key});
|
const StatusBar({super.key});
|
||||||
@@ -14,11 +26,49 @@ class StatusBar extends StatelessWidget {
|
|||||||
builder: (context, vpn, timer, _) {
|
builder: (context, vpn, timer, _) {
|
||||||
final isConnected = vpn.status == VpnStatus.connected;
|
final isConnected = vpn.status == VpnStatus.connected;
|
||||||
final isConnecting = vpn.status == VpnStatus.connecting;
|
final isConnecting = vpn.status == VpnStatus.connecting;
|
||||||
final serverHealthy = vpn.serverReachable || (isConnected && timer.hasSyncedOnce);
|
final serverHealthy =
|
||||||
|
vpn.serverReachable || (isConnected && timer.hasSyncedOnce);
|
||||||
|
|
||||||
return Container(
|
final statusLabel = isConnected
|
||||||
margin: const EdgeInsets.symmetric(horizontal: 24),
|
? (timer.hasSyncedOnce ? 'Online' : 'Syncing…')
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
: (isConnecting
|
||||||
|
? 'Connecting…'
|
||||||
|
: (vpn.serverReachable ? 'Ready' : 'Offline'));
|
||||||
|
|
||||||
|
// Read from the ServerList provider — the source of truth for
|
||||||
|
// which server is selected and what it looks like.
|
||||||
|
final server = context.watch<ServerList>().selected;
|
||||||
|
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
// ── Server location ──────────────────────────────────────────
|
||||||
|
GestureDetector(
|
||||||
|
onTap: () {
|
||||||
|
Navigator.of(context).push(
|
||||||
|
PageRouteBuilder(
|
||||||
|
transitionDuration: const Duration(milliseconds: 300),
|
||||||
|
pageBuilder: (_, __, ___) => const SelectionScreen(),
|
||||||
|
transitionsBuilder: (_, animation, __, child) {
|
||||||
|
return SlideTransition(
|
||||||
|
position: Tween<Offset>(
|
||||||
|
begin: const Offset(1.0, 0.0),
|
||||||
|
end: Offset.zero,
|
||||||
|
).animate(CurvedAnimation(
|
||||||
|
parent: animation,
|
||||||
|
curve: Curves.easeOut,
|
||||||
|
)),
|
||||||
|
child: child,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
child: Container(
|
||||||
|
padding:
|
||||||
|
const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: AppColors.bgCard,
|
color: AppColors.bgCard,
|
||||||
borderRadius: BorderRadius.circular(16),
|
borderRadius: BorderRadius.circular(16),
|
||||||
@@ -26,38 +76,47 @@ class StatusBar extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
// ── Connection status (left) ─────────────────────────────
|
Image.asset(server.flagAsset, width: 20, height: 20),
|
||||||
if (isConnected) ...[
|
|
||||||
Image.asset('assets/finland_flag_256.png', width: 20, height: 20),
|
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
const Text('Helsinki, Finland', style: TextStyle(
|
Expanded(
|
||||||
color: AppColors.accent, fontWeight: FontWeight.w600,
|
child: Text(server.name,
|
||||||
fontSize: 13, letterSpacing: 0.5,
|
style: const TextStyle(
|
||||||
|
color: AppColors.accent,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
fontSize: 13,
|
||||||
|
letterSpacing: 0.5,
|
||||||
)),
|
)),
|
||||||
] else ...[
|
|
||||||
Icon(
|
|
||||||
isConnecting ? Icons.sync : Icons.shield_outlined,
|
|
||||||
size: 18,
|
|
||||||
color: isConnecting ? AppColors.accent : AppColors.slate70,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(
|
|
||||||
vpn.statusMessage.toUpperCase(),
|
|
||||||
style: TextStyle(
|
|
||||||
color: isConnecting ? AppColors.accent : AppColors.slate70,
|
|
||||||
fontWeight: FontWeight.w600, fontSize: 13, letterSpacing: 1,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
|
const Icon(Icons.chevron_right,
|
||||||
|
color: AppColors.textDim, size: 20),
|
||||||
],
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
const Spacer(),
|
const SizedBox(height: 8),
|
||||||
|
|
||||||
// ── Server health dot (right) ────────────────────────────
|
// ── Connection status ────────────────────────────────────────
|
||||||
|
Container(
|
||||||
|
padding:
|
||||||
|
const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: AppColors.bgCard,
|
||||||
|
borderRadius: BorderRadius.circular(16),
|
||||||
|
border: Border.all(color: AppColors.slate15),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
OnlineDot(
|
OnlineDot(
|
||||||
isOnline: serverHealthy,
|
isOnline: serverHealthy,
|
||||||
label: isConnected
|
label: statusLabel,
|
||||||
? (timer.hasSyncedOnce ? 'Online' : 'Syncing…')
|
),
|
||||||
: (vpn.serverReachable ? 'Ready' : 'Offline'),
|
const Spacer(),
|
||||||
|
if (isConnected)
|
||||||
|
const Icon(Icons.lock,
|
||||||
|
color: AppColors.green50, size: 14),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -34,9 +34,10 @@ class _SupportButtonState extends State<SupportButton> {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Consumer<SessionTimer>(
|
return Selector<SessionTimer, bool>(
|
||||||
builder: (context, timer, _) {
|
selector: (_, timer) => timer.isRunning || timer.hasSyncedOnce,
|
||||||
if (!timer.isRunning && !timer.hasSyncedOnce) {
|
builder: (context, visible, _) {
|
||||||
|
if (!visible) {
|
||||||
return const SizedBox.shrink();
|
return const SizedBox.shrink();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,17 +19,21 @@ class TimerBox extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
child: Text(
|
child: Text(
|
||||||
timer.hasSyncedOnce ? timer.formatted : '00:00:00',
|
timer.hasSyncedOnce ? timer.formatted : '00:00:00',
|
||||||
style: const TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 32,
|
fontSize: 32,
|
||||||
fontWeight: FontWeight.w700,
|
fontWeight: FontWeight.w700,
|
||||||
color: AppColors.textWhite,
|
color: timer.hasSyncedOnce
|
||||||
|
? AppColors.textWhite
|
||||||
|
: AppColors.slate70,
|
||||||
letterSpacing: 2,
|
letterSpacing: 2,
|
||||||
shadows: [
|
shadows: timer.hasSyncedOnce
|
||||||
|
? const [
|
||||||
Shadow(
|
Shadow(
|
||||||
color: AppColors.accent50,
|
color: AppColors.accent50,
|
||||||
blurRadius: 16,
|
blurRadius: 16,
|
||||||
),
|
),
|
||||||
],
|
]
|
||||||
|
: [],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,13 +6,9 @@ import 'package:google_mobile_ads/google_mobile_ads.dart';
|
|||||||
import 'package:revoltvpn/logic/crypto_service.dart';
|
import 'package:revoltvpn/logic/crypto_service.dart';
|
||||||
import 'package:revoltvpn/logic/hivemind_service.dart';
|
import 'package:revoltvpn/logic/hivemind_service.dart';
|
||||||
import 'package:revoltvpn/logic/app_config.dart';
|
import 'package:revoltvpn/logic/app_config.dart';
|
||||||
|
import 'package:revoltvpn/logic/consent_manager.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 {
|
class AdManager extends ChangeNotifier {
|
||||||
/// Flip to `true` after Google Play launch when real ads are wired up.
|
|
||||||
static const bool adsEnabled = false;
|
static const bool adsEnabled = false;
|
||||||
|
|
||||||
RewardedAd? _rewardedAd;
|
RewardedAd? _rewardedAd;
|
||||||
@@ -32,15 +28,30 @@ class AdManager extends ChangeNotifier {
|
|||||||
if (adsEnabled) preloadAd();
|
if (adsEnabled) preloadAd();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Loads a rewarded ad in the background and returns a Future when ready.
|
static Future<void>? _sdkInit;
|
||||||
/// Safe to call multiple times — re-entrant calls wait on the same load.
|
static Future<void> ensureSdkInitialized() {
|
||||||
/// No-op when [adsEnabled] is false.
|
if (!adsEnabled) return Future.value();
|
||||||
|
return _sdkInit ??= _initSdk();
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<void> _initSdk() async {
|
||||||
|
try {
|
||||||
|
await ConsentManager.requestConsentIfNeeded()
|
||||||
|
.timeout(const Duration(seconds: 5));
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[AdManager] Consent init skipped: $e');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await MobileAds.instance.initialize().timeout(const Duration(seconds: 5));
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[AdManager] MobileAds init skipped: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<bool> preloadAd() async {
|
Future<bool> preloadAd() async {
|
||||||
if (!adsEnabled) return true;
|
if (!adsEnabled) return true;
|
||||||
// If already loaded, return instantly
|
await ensureSdkInitialized();
|
||||||
if (_isAdLoaded) return true;
|
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);
|
if (_isAdLoading) return _loadCompleter?.future ?? Future.value(false);
|
||||||
|
|
||||||
_isAdLoading = true;
|
_isAdLoading = true;
|
||||||
@@ -84,12 +95,36 @@ class AdManager extends ChangeNotifier {
|
|||||||
return _loadCompleter!.future;
|
return _loadCompleter!.future;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Displays the rewarded video ad to the user.
|
// ── Show ad (or debug bypass) ─────────────────────────────────────
|
||||||
/// Returns false immediately when [adsEnabled] is false.
|
|
||||||
Future<bool> showAd(String adType) async {
|
Future<bool> showAd(String adType) async {
|
||||||
|
// Debug bypass: fire fake AdMob callback so support ads work in dev.
|
||||||
|
// The server's ADMOB_BYPASS must be True for this to succeed.
|
||||||
|
if (!adsEnabled && kDebugMode) {
|
||||||
|
final deviceId = await CryptoService.getDeviceId();
|
||||||
|
final nonce = '${Random().nextInt(0x7FFFFFFF)}-${DateTime.now().millisecondsSinceEpoch}';
|
||||||
|
HivemindService.setExpectedNonce(nonce);
|
||||||
|
try {
|
||||||
|
final customData = jsonEncode({
|
||||||
|
'device_id': deviceId,
|
||||||
|
'ad_type': adType,
|
||||||
|
'nonce': nonce,
|
||||||
|
});
|
||||||
|
final fakeUrl = Uri.parse(
|
||||||
|
'${AppConfig.hivemindApiPublic}/admob/callback'
|
||||||
|
'?signature=test&key_id=test'
|
||||||
|
'&custom_data=${Uri.encodeComponent(customData)}');
|
||||||
|
await HivemindService.directGet(fakeUrl, timeout: const Duration(seconds: 8));
|
||||||
|
return true;
|
||||||
|
} catch (_) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!adsEnabled) return false;
|
if (!adsEnabled) return false;
|
||||||
|
|
||||||
// 1. Ensure the ad is fully loaded before trying to show it
|
await ensureSdkInitialized();
|
||||||
|
|
||||||
if (!_isAdLoaded || _rewardedAd == null) {
|
if (!_isAdLoaded || _rewardedAd == null) {
|
||||||
final loaded = await preloadAd();
|
final loaded = await preloadAd();
|
||||||
if (!loaded || _rewardedAd == null) {
|
if (!loaded || _rewardedAd == null) {
|
||||||
@@ -98,16 +133,12 @@ class AdManager extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Fetch device ID for Server-Side Verification (SSV)
|
|
||||||
final deviceId = await CryptoService.getDeviceId();
|
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}';
|
final nonce = '${Random().nextInt(0x7FFFFFFF)}-${DateTime.now().millisecondsSinceEpoch}';
|
||||||
HivemindService.setExpectedNonce(nonce);
|
HivemindService.setExpectedNonce(nonce);
|
||||||
debugPrint('[AdManager] Ad nonce: $nonce');
|
debugPrint('[AdManager] Ad nonce: $nonce');
|
||||||
|
|
||||||
// 4. Build SSV options to send to our Hivemind server via Google's callback
|
|
||||||
final ssvOptions = ServerSideVerificationOptions(
|
final ssvOptions = ServerSideVerificationOptions(
|
||||||
customData: jsonEncode({
|
customData: jsonEncode({
|
||||||
'device_id': deviceId,
|
'device_id': deviceId,
|
||||||
@@ -118,7 +149,6 @@ class AdManager extends ChangeNotifier {
|
|||||||
|
|
||||||
Completer<bool> rewardCompleter = Completer<bool>();
|
Completer<bool> rewardCompleter = Completer<bool>();
|
||||||
|
|
||||||
// 4. Setup full screen callbacks to handle dismissal and errors
|
|
||||||
_rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
|
_rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
|
||||||
onAdShowedFullScreenContent: (ad) => debugPrint('[AdManager] Ad showing.'),
|
onAdShowedFullScreenContent: (ad) => debugPrint('[AdManager] Ad showing.'),
|
||||||
onAdDismissedFullScreenContent: (ad) {
|
onAdDismissedFullScreenContent: (ad) {
|
||||||
@@ -126,10 +156,9 @@ class AdManager extends ChangeNotifier {
|
|||||||
ad.dispose();
|
ad.dispose();
|
||||||
_isAdLoaded = false;
|
_isAdLoaded = false;
|
||||||
_rewardedAd = null;
|
_rewardedAd = null;
|
||||||
// Start loading the next ad immediately
|
|
||||||
preloadAd();
|
preloadAd();
|
||||||
if (!rewardCompleter.isCompleted) {
|
if (!rewardCompleter.isCompleted) {
|
||||||
rewardCompleter.complete(false); // User closed before earning reward
|
rewardCompleter.complete(false);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onAdFailedToShowFullScreenContent: (ad, error) {
|
onAdFailedToShowFullScreenContent: (ad, error) {
|
||||||
@@ -143,13 +172,10 @@ class AdManager extends ChangeNotifier {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// 5. Show the ad with SSV options
|
|
||||||
_rewardedAd!.setServerSideOptions(ssvOptions);
|
_rewardedAd!.setServerSideOptions(ssvOptions);
|
||||||
await _rewardedAd!.show(
|
await _rewardedAd!.show(
|
||||||
onUserEarnedReward: (AdWithoutView ad, RewardItem reward) {
|
onUserEarnedReward: (AdWithoutView ad, RewardItem reward) {
|
||||||
debugPrint('[AdManager] Reward earned: ${reward.amount} ${reward.type}');
|
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) {
|
if (!rewardCompleter.isCompleted) {
|
||||||
rewardCompleter.complete(true);
|
rewardCompleter.complete(true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,39 @@
|
|||||||
// =============================================================================
|
// =============================================================================
|
||||||
// app_config.example.dart — TEMPLATE FOR SERVER SETTINGS
|
// app_config.example.dart — TEMPLATE FOR SERVER SETTINGS
|
||||||
// ─────────────────────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
// Rename this file to `app_config.dart` and fill in your real values.
|
|
||||||
// Do not commit your real `app_config.dart` to GitHub!
|
|
||||||
//
|
|
||||||
// Most Reality tunnel fields (vless_ip, vless_port, reality_pbk, reality_sid,
|
|
||||||
// reality_sni, reality_fp) come from the server's /session/status response.
|
|
||||||
// The constants below are fallbacks — the server is the source of truth.
|
|
||||||
// =============================================================================
|
|
||||||
|
|
||||||
abstract final class AppConfig {
|
abstract final class AppConfig {
|
||||||
AppConfig._();
|
AppConfig._(); // static members only
|
||||||
|
|
||||||
// ── Server (API) ──────────────────────────────────────────────────────
|
// ── Server ───────────────────────────────────────────────────────────
|
||||||
static const String serverDomain = 'yourdomain.com'; // ◄── REPLACE
|
/// Your server's public IP. The VPN tunnel is pinned to this.
|
||||||
|
static const String serverIp = '0.0.0.0'; // ◄── REPLACE
|
||||||
static String get hivemindApiBase => 'https://$serverDomain/api';
|
static const String hivemindApiPublic = 'https://YOUR_DOMAIN/api'; // ◄── REPLACE
|
||||||
|
|
||||||
// ── Reality (VPN tunnel) ──────────────────────────────────────────────
|
// ── Reality (VPN tunnel) ──────────────────────────────────────────────
|
||||||
// These are fallbacks — normally overridden by /session/status response.
|
// Credentials (public key, shortId) come from /session/status, not from
|
||||||
static const String realitySni = 'www.microsoft.com';
|
// here. Only the transport parameters below are compiled in.
|
||||||
|
/// The server picks a random SNI per session from REALITY_SNI_POOL.
|
||||||
|
/// The client does NOT hardcode one — server is always the source of truth.
|
||||||
|
|
||||||
|
/// TLS fingerprint: chrome | firefox | safari | random
|
||||||
static const String realityFp = 'chrome';
|
static const String realityFp = 'chrome';
|
||||||
|
|
||||||
// These are authoritative — never sent by the server.
|
// These are normally overridden by /session/status response fields.
|
||||||
static const String vlessSecurity = 'reality';
|
static const String vlessSecurity = 'reality';
|
||||||
static const String vlessType = 'tcp';
|
static const String vlessType = 'xhttp';
|
||||||
static const String vlessFlow = 'xtls-rprx-vision';
|
|
||||||
|
/// XHTTP path — must match xray_config_reality.json xhttpSettings.path.
|
||||||
|
static const String vlessPath = '/revolt';
|
||||||
|
|
||||||
|
// ── Updates ────────────────────────────────────────────────────────────
|
||||||
|
/// Used by the updater.
|
||||||
|
static const String applicationId = 'com.paladinvpn.app'; // ◄── REPLACE
|
||||||
|
static const String githubOwner = 'YOUR_USERNAME'; // ◄── REPLACE
|
||||||
|
static const String githubRepo = 'revoltvpn'; // ◄── REPLACE
|
||||||
|
|
||||||
|
/// Fallback URL if the GitHub API call fails.
|
||||||
|
static const String githubReleasesUrl = 'https://github.com/$githubOwner/$githubRepo/releases/latest';
|
||||||
|
|
||||||
// ── AdMob ──────────────────────────────────────────────────────────────
|
// ── AdMob ──────────────────────────────────────────────────────────────
|
||||||
static const String adUnitId = 'ca-app-pub-0000000000000000/0000000000'; // REPLACE
|
static const String adUnitId = 'ca-app-pub-0000000000000000/0000000000'; // REPLACE
|
||||||
|
|||||||
@@ -10,22 +10,24 @@ class HivemindService {
|
|||||||
static String? _expectedNonce;
|
static String? _expectedNonce;
|
||||||
static int _currentCallId = 0;
|
static int _currentCallId = 0;
|
||||||
|
|
||||||
/// Call this from disconnect to abort any in-progress polling.
|
static const _ua = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 '
|
||||||
|
'(KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36';
|
||||||
|
|
||||||
|
static Future<http.Response> directGet(Uri uri, {Duration timeout = const Duration(seconds: 5)}) {
|
||||||
|
return http.get(uri, headers: {'User-Agent': _ua}).timeout(timeout);
|
||||||
|
}
|
||||||
|
|
||||||
static void cancel() {
|
static void cancel() {
|
||||||
_currentCallId++; // bump — any running loop sees a stale ID and exits
|
_currentCallId++;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void setExpectedNonce(String nonce) {
|
static void setExpectedNonce(String nonce) {
|
||||||
_expectedNonce = nonce;
|
_expectedNonce = nonce;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tries to fetch the VLESS config from the server.
|
static Future<String> fetchConfigDirectly({
|
||||||
/// 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,
|
void Function(int attempt, int total)? onAttempt,
|
||||||
bool skipAdBypass = false,
|
bool skipAdBypass = false,
|
||||||
bool quickReconnect = false,
|
|
||||||
}) async {
|
}) async {
|
||||||
final deviceId = await CryptoService.getDeviceId();
|
final deviceId = await CryptoService.getDeviceId();
|
||||||
|
|
||||||
@@ -34,25 +36,24 @@ class HivemindService {
|
|||||||
_expectedNonce = nonce;
|
_expectedNonce = nonce;
|
||||||
debugPrint('[HivemindService] Call #$callId — nonce: $nonce');
|
debugPrint('[HivemindService] Call #$callId — nonce: $nonce');
|
||||||
|
|
||||||
final url = Uri.parse('${AppConfig.hivemindApiBase}/session/status?device_id=$deviceId');
|
final url = _publicUrl('/session/status?device_id=$deviceId');
|
||||||
|
|
||||||
// ── AD BYPASS (debug only) ────────────────────────────────────────
|
if (!skipAdBypass) {
|
||||||
if (kDebugMode && !skipAdBypass) {
|
|
||||||
try {
|
try {
|
||||||
final customData = jsonEncode({'device_id': deviceId, 'nonce': nonce});
|
final customData = jsonEncode({'device_id': deviceId, 'nonce': nonce});
|
||||||
final fakeUrl = Uri.parse(
|
final fakeUrl = _publicUrl(
|
||||||
'${AppConfig.hivemindApiBase}/admob/callback?signature=test&key_id=test&custom_data=${Uri.encodeComponent(customData)}');
|
'/admob/callback?signature=test&key_id=test&custom_data=${Uri.encodeComponent(customData)}');
|
||||||
await http.get(fakeUrl).timeout(const Duration(seconds: 8));
|
await directGet(fakeUrl, timeout: const Duration(seconds: 8));
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
final maxAttempts = quickReconnect ? 1 : 5;
|
const maxAttempts = 5;
|
||||||
for (int i = 1; i <= maxAttempts; i++) {
|
for (int i = 1; i <= maxAttempts; i++) {
|
||||||
if (_currentCallId != callId) throw Exception('Cancelled');
|
if (_currentCallId != callId) throw Exception('Cancelled');
|
||||||
|
|
||||||
onAttempt?.call(i, maxAttempts);
|
onAttempt?.call(i, maxAttempts);
|
||||||
try {
|
try {
|
||||||
final response = await http.get(url).timeout(const Duration(seconds: 5));
|
final response = await directGet(url);
|
||||||
if (response.statusCode == 200) {
|
if (response.statusCode == 200) {
|
||||||
final data = jsonDecode(response.body);
|
final data = jsonDecode(response.body);
|
||||||
|
|
||||||
@@ -61,24 +62,24 @@ class HivemindService {
|
|||||||
debugPrint('[HivemindService] Nonce mismatch — retrying…');
|
debugPrint('[HivemindService] Nonce mismatch — retrying…');
|
||||||
} else if (data['active'] == true && data['vless_uuid'] != null) {
|
} else if (data['active'] == true && data['vless_uuid'] != null) {
|
||||||
final vlessUuid = data['vless_uuid'];
|
final vlessUuid = data['vless_uuid'];
|
||||||
|
final vlessIp = data['vless_ip'] ?? AppConfig.serverIp;
|
||||||
// Reality tunnel fields — server is source of truth, AppConfig is fallback.
|
final vlessPort = data['vless_port'] ?? 443;
|
||||||
final vlessIp = data['vless_ip'] ?? AppConfig.serverDomain;
|
|
||||||
final vlessPort = data['vless_port'] ?? 8443;
|
|
||||||
final pbk = data['reality_pbk'] ?? '';
|
final pbk = data['reality_pbk'] ?? '';
|
||||||
final sid = data['reality_sid'] ?? '';
|
final sid = data['reality_sid'] ?? '';
|
||||||
final sni = data['reality_sni'] ?? AppConfig.realitySni;
|
final sni = data['reality_sni'];
|
||||||
|
if (sni == null) throw Exception('Server did not provide reality_sni');
|
||||||
final fp = data['reality_fp'] ?? AppConfig.realityFp;
|
final fp = data['reality_fp'] ?? AppConfig.realityFp;
|
||||||
|
final xhttpPath = data['xhttp_path'] ?? AppConfig.vlessPath;
|
||||||
|
|
||||||
final vlessUrl = 'vless://$vlessUuid@$vlessIp:$vlessPort'
|
final vlessUrl = 'vless://$vlessUuid@$vlessIp:$vlessPort'
|
||||||
'?security=${AppConfig.vlessSecurity}'
|
'?security=${AppConfig.vlessSecurity}'
|
||||||
'&type=${AppConfig.vlessType}'
|
'&type=${AppConfig.vlessType}'
|
||||||
'&flow=${AppConfig.vlessFlow}'
|
'&path=$xhttpPath'
|
||||||
'&pbk=${Uri.encodeComponent(pbk)}'
|
'&pbk=${Uri.encodeComponent(pbk)}'
|
||||||
'&sni=${Uri.encodeComponent(sni)}'
|
'&sni=${Uri.encodeComponent(sni)}'
|
||||||
'&sid=${Uri.encodeComponent(sid)}'
|
'&sid=${Uri.encodeComponent(sid)}'
|
||||||
'&fp=${Uri.encodeComponent(fp)}'
|
'&fp=${Uri.encodeComponent(fp)}'
|
||||||
'#ReVoltVPN';
|
'#Revolt VPN';
|
||||||
_expectedNonce = null;
|
_expectedNonce = null;
|
||||||
return vlessUrl;
|
return vlessUrl;
|
||||||
}
|
}
|
||||||
@@ -96,36 +97,16 @@ class HivemindService {
|
|||||||
|
|
||||||
static Future<bool> checkHealth() async {
|
static Future<bool> checkHealth() async {
|
||||||
try {
|
try {
|
||||||
final url = Uri.parse('${AppConfig.hivemindApiBase}/health');
|
final url = Uri.parse('${AppConfig.hivemindApiPublic}/health');
|
||||||
final response = await http.get(url).timeout(const Duration(seconds: 3));
|
final response = await directGet(url, timeout: const Duration(seconds: 3));
|
||||||
return response.statusCode == 200;
|
return response.statusCode == 200;
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static Future<bool> verifySession() async {
|
// ── URL builders ──────────────────────────────────────────────────
|
||||||
try {
|
|
||||||
final deviceId = await CryptoService.getDeviceId();
|
|
||||||
final url = Uri.parse('${AppConfig.hivemindApiBase}/session/status?device_id=$deviceId');
|
|
||||||
final response = await http.get(url).timeout(const Duration(seconds: 5));
|
|
||||||
if (response.statusCode == 200) {
|
|
||||||
final data = jsonDecode(response.body);
|
|
||||||
return data['active'] == true;
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
static Future<void> disconnectAndCleanup() async {
|
static Uri _publicUrl(String path) =>
|
||||||
final deviceId = await CryptoService.getDeviceId();
|
Uri.parse('${AppConfig.hivemindApiPublic}$path');
|
||||||
final url = Uri.parse('${AppConfig.hivemindApiBase}/session/stop');
|
|
||||||
try {
|
|
||||||
await http.post(
|
|
||||||
url,
|
|
||||||
headers: {'Content-Type': 'application/json'},
|
|
||||||
body: jsonEncode({'device_id': deviceId}),
|
|
||||||
).timeout(const Duration(seconds: 3));
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
|
// ── lib/logic/notification_service.dart ─────────────────────────────────────
|
||||||
|
// Bridge to the native VPN notification, which flutter_vless owns. This only
|
||||||
|
// refreshes its content text with the session countdown, so a failure here is
|
||||||
|
// never worth propagating to the session timer.
|
||||||
|
|
||||||
|
class NotificationService {
|
||||||
|
NotificationService._();
|
||||||
|
|
||||||
|
static const MethodChannel _channel =
|
||||||
|
MethodChannel('com.revoltvpn.app/notification');
|
||||||
|
|
||||||
|
static String? _lastText;
|
||||||
|
|
||||||
|
/// Sets the notification's content text to [text].
|
||||||
|
///
|
||||||
|
/// The native side rebuilds the whole notification, so skip the round-trip
|
||||||
|
/// when the text has not changed.
|
||||||
|
static Future<void> updateTimer(String text) async {
|
||||||
|
if (text == _lastText) return;
|
||||||
|
_lastText = text;
|
||||||
|
try {
|
||||||
|
await _channel.invokeMethod<void>('updateNotificationText', {
|
||||||
|
'title': 'Revolt VPN',
|
||||||
|
'text': text,
|
||||||
|
'disconnectLabel': 'Disconnect',
|
||||||
|
});
|
||||||
|
} catch (_) {
|
||||||
|
// Cosmetic.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forces the next connect to re-post even if the countdown resumes on the
|
||||||
|
/// same value.
|
||||||
|
static void reset() => _lastText = null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
// ── lib/logic/server_list.dart ──────────────────────────────────────────────
|
||||||
|
// Server data model and ChangeNotifier — shared by StatusBar (shows current
|
||||||
|
// server name/flag) and SelectionScreen (lets user pick a server).
|
||||||
|
//
|
||||||
|
// Each server is defined by its tunnel IP/port. Reality credentials (public
|
||||||
|
// key, shortId) come from /session/status per session; only the transport
|
||||||
|
// parameters live in AppConfig.
|
||||||
|
//
|
||||||
|
// When multi-server ships:
|
||||||
|
// - _all becomes a fetched list (from /api/servers or bundled config)
|
||||||
|
// - SelectionScreen shows multiple rows
|
||||||
|
// - select() triggers a disconnect/reconnect cycle if the tunnel is active
|
||||||
|
|
||||||
|
class ServerInfo {
|
||||||
|
final String id;
|
||||||
|
final String name;
|
||||||
|
final String flagAsset;
|
||||||
|
final String ip;
|
||||||
|
final int port;
|
||||||
|
|
||||||
|
const ServerInfo({
|
||||||
|
required this.id,
|
||||||
|
required this.name,
|
||||||
|
required this.flagAsset,
|
||||||
|
required this.ip,
|
||||||
|
required this.port,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
class ServerList extends ChangeNotifier {
|
||||||
|
static const _all = [
|
||||||
|
ServerInfo(
|
||||||
|
id: 'finland',
|
||||||
|
name: 'Helsinki, Finland',
|
||||||
|
flagAsset: 'assets/finland_flag_256.png',
|
||||||
|
ip: '204.168.246.88',
|
||||||
|
port: 443,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
int _selectedIndex = 0;
|
||||||
|
|
||||||
|
List<ServerInfo> get all => _all;
|
||||||
|
int get selectedIndex => _selectedIndex;
|
||||||
|
ServerInfo get selected => _all[_selectedIndex];
|
||||||
|
|
||||||
|
// Loads persisted selection from SharedPreferences.
|
||||||
|
// Fire-and-forget — UI starts with default, updates when prefs load.
|
||||||
|
Future<void> init() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final saved = prefs.getInt('selected_server_index') ?? 0;
|
||||||
|
if (saved >= 0 && saved < _all.length && saved != _selectedIndex) {
|
||||||
|
_selectedIndex = saved;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Switches to a different server. Persists the choice.
|
||||||
|
Future<void> select(int index) async {
|
||||||
|
if (index == _selectedIndex || index < 0 || index >= _all.length) return;
|
||||||
|
_selectedIndex = index;
|
||||||
|
notifyListeners();
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setInt('selected_server_index', index);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,15 +1,16 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/widgets.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:revoltvpn/logic/hivemind_service.dart';
|
||||||
import 'package:revoltvpn/logic/app_config.dart';
|
import 'package:revoltvpn/logic/app_config.dart';
|
||||||
import 'package:revoltvpn/logic/vpn_connection.dart';
|
import 'package:revoltvpn/logic/vpn_connection.dart';
|
||||||
import 'package:revoltvpn/logic/crypto_service.dart';
|
import 'package:revoltvpn/logic/crypto_service.dart';
|
||||||
import 'package:revoltvpn/components/notification.dart';
|
import 'package:revoltvpn/logic/notification_service.dart';
|
||||||
|
|
||||||
class SessionTimer extends ChangeNotifier {
|
class SessionTimer extends ChangeNotifier with WidgetsBindingObserver {
|
||||||
Timer? _timer;
|
Timer? _timer;
|
||||||
int _tickCount = 0;
|
int _tickCount = 0;
|
||||||
|
bool _appBackgrounded = false;
|
||||||
|
|
||||||
final VpnConnection vpnConnection;
|
final VpnConnection vpnConnection;
|
||||||
|
|
||||||
@@ -19,26 +20,21 @@ class SessionTimer extends ChangeNotifier {
|
|||||||
bool _hasSyncedOnce = false;
|
bool _hasSyncedOnce = false;
|
||||||
int _consecutiveFailures = 0;
|
int _consecutiveFailures = 0;
|
||||||
bool _isDisconnecting = false;
|
bool _isDisconnecting = false;
|
||||||
bool _userInitiatedStop = false;
|
bool _syncInProgress = false;
|
||||||
|
|
||||||
|
|
||||||
int? _currentPort;
|
|
||||||
bool _portSwitchInProgress = false;
|
|
||||||
|
|
||||||
static const int _maxConsecutiveFailures = 3;
|
static const int _maxConsecutiveFailures = 3;
|
||||||
|
|
||||||
static const int _maxOfflineSeconds = 120;
|
static const int _maxOfflineSeconds = 120;
|
||||||
int _offlineSeconds = 0;
|
int _offlineSeconds = 0;
|
||||||
|
|
||||||
static const int _pollIntervalSeconds = 5;
|
static const int _pollIntervalSeconds = 5;
|
||||||
|
static const int _backgroundPollIntervalSeconds = 30;
|
||||||
|
|
||||||
int _lastUsedBytes = 0;
|
int _lastUsedBytes = 0;
|
||||||
double _currentSpeedKBps = 0.0;
|
double _currentSpeedKBps = 0.0;
|
||||||
|
DateTime? _lastSyncAt;
|
||||||
String _lastNotifTime = '';
|
|
||||||
String _lastNotifSpeed = '';
|
|
||||||
|
|
||||||
SessionTimer({required this.vpnConnection}) {
|
SessionTimer({required this.vpnConnection}) {
|
||||||
|
WidgetsBinding.instance.addObserver(this);
|
||||||
vpnConnection.addListener(_onVpnConnectionChanged);
|
vpnConnection.addListener(_onVpnConnectionChanged);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,11 +53,8 @@ class SessionTimer extends ChangeNotifier {
|
|||||||
return '$h:$m:$s';
|
return '$h:$m:$s';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lifecycle
|
|
||||||
|
|
||||||
/// Fires whenever VpnConnection state changes.
|
|
||||||
void _onVpnConnectionChanged() {
|
void _onVpnConnectionChanged() {
|
||||||
|
// Restore timer if VPN was already running at app launch.
|
||||||
if (vpnConnection.status == VpnStatus.connected &&
|
if (vpnConnection.status == VpnStatus.connected &&
|
||||||
!isRunning &&
|
!isRunning &&
|
||||||
vpnConnection.isStartupRestoration) {
|
vpnConnection.isStartupRestoration) {
|
||||||
@@ -69,21 +62,18 @@ class SessionTimer extends ChangeNotifier {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Resume after brief tunnel disconnection.
|
||||||
// The underlying VLESS tunnel may briefly flap. If we weren't
|
|
||||||
// explicitly stopped by the user, resume where we left off.
|
|
||||||
if (vpnConnection.status == VpnStatus.connected &&
|
if (vpnConnection.status == VpnStatus.connected &&
|
||||||
!isRunning &&
|
!isRunning &&
|
||||||
!_userInitiatedStop &&
|
!_isDisconnecting &&
|
||||||
_hasSyncedOnce) {
|
_hasSyncedOnce) {
|
||||||
debugPrint('[Timer] VPN reconnected after blip — resuming.');
|
debugPrint('[Timer] VPN reconnected after blip — resuming.');
|
||||||
_resumeTicking();
|
_resumeTicking();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (vpnConnection.status == VpnStatus.disconnected && !_isDisconnecting) {
|
||||||
if (vpnConnection.status == VpnStatus.disconnected && isRunning) {
|
_doDisconnect('VPN tunnel dropped');
|
||||||
_stopInternal();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,155 +82,132 @@ class SessionTimer extends ChangeNotifier {
|
|||||||
_usedBytes = 0;
|
_usedBytes = 0;
|
||||||
_lastUsedBytes = 0;
|
_lastUsedBytes = 0;
|
||||||
_currentSpeedKBps = 0.0;
|
_currentSpeedKBps = 0.0;
|
||||||
|
_lastSyncAt = null;
|
||||||
|
NotificationService.reset();
|
||||||
_tickCount = 0;
|
_tickCount = 0;
|
||||||
_hasSyncedOnce = false;
|
_hasSyncedOnce = false;
|
||||||
_consecutiveFailures = 0;
|
_consecutiveFailures = 0;
|
||||||
_offlineSeconds = 0;
|
_offlineSeconds = 0;
|
||||||
_isDisconnecting = false;
|
_isDisconnecting = false;
|
||||||
_userInitiatedStop = false;
|
_appBackgrounded = false;
|
||||||
_currentPort = null;
|
|
||||||
_portSwitchInProgress = false;
|
|
||||||
|
|
||||||
_timer?.cancel();
|
_timer?.cancel();
|
||||||
_timer = Timer.periodic(const Duration(seconds: 1), _tick);
|
_timer = Timer.periodic(const Duration(seconds: 1), _tick);
|
||||||
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
// Kick off the first sync — the UI will show real data as soon as it lands.
|
|
||||||
_syncWithHivemind();
|
_syncWithHivemind();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _tick(Timer t) {
|
void _tick(Timer t) {
|
||||||
|
if (_isDisconnecting) return;
|
||||||
// Decrement the local clock as long as we're not in a network blackout.
|
// A local clock: poll failures are about the network, not the clock.
|
||||||
if (_hasSyncedOnce && _consecutiveFailures < _maxConsecutiveFailures) {
|
if (_hasSyncedOnce && _remainingSeconds > 0) {
|
||||||
if (_remainingSeconds > 0) {
|
|
||||||
_remainingSeconds--;
|
_remainingSeconds--;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// If the server has been unreachable for too long, kill the VPN.
|
|
||||||
// Don't let an orphaned tunnel keep running forever.
|
|
||||||
if (_consecutiveFailures >= _maxConsecutiveFailures) {
|
if (_consecutiveFailures >= _maxConsecutiveFailures) {
|
||||||
_offlineSeconds++;
|
_offlineSeconds++;
|
||||||
if (_offlineSeconds >= _maxOfflineSeconds) {
|
if (_offlineSeconds >= _maxOfflineSeconds) {
|
||||||
debugPrint('[Timer] Offline for $_maxOfflineSeconds s — forcing disconnect.');
|
_doDisconnect('Server unreachable');
|
||||||
_forceDisconnect('Session lost — server unreachable');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// When our clock hits zero, disconnect immediately. Don't wait for the
|
|
||||||
// next server poll — the session is over and the user expects the VPN
|
|
||||||
// to drop right now.
|
|
||||||
if (_hasSyncedOnce && _remainingSeconds <= 0) {
|
if (_hasSyncedOnce && _remainingSeconds <= 0) {
|
||||||
debugPrint('[Timer] Local countdown expired — disconnecting.');
|
_doDisconnect('Session expired');
|
||||||
_forceDisconnect('Session expired');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_tickCount++;
|
_tickCount++;
|
||||||
if (_tickCount % _pollIntervalSeconds == 0) {
|
final pollInterval = _appBackgrounded
|
||||||
|
? _backgroundPollIntervalSeconds
|
||||||
|
: _pollIntervalSeconds;
|
||||||
|
if (_tickCount % pollInterval == 0) {
|
||||||
_syncWithHivemind();
|
_syncWithHivemind();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Uses the locally-decremented time so the notification stays in sync
|
|
||||||
// with the in-app display, not gated behind the 5 s server poll.
|
|
||||||
if (_hasSyncedOnce) {
|
|
||||||
final speedText = _currentSpeedKBps > 0.5
|
|
||||||
? '${_currentSpeedKBps.toStringAsFixed(1)} KB/s'
|
|
||||||
: 'Idle';
|
|
||||||
if (formatted != _lastNotifTime || speedText != _lastNotifSpeed) {
|
|
||||||
_lastNotifTime = formatted;
|
|
||||||
_lastNotifSpeed = speedText;
|
|
||||||
VpnNotificationManager.showOrUpdateStatus(
|
|
||||||
timeLeft: formatted,
|
|
||||||
speedKbps: speedText,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
|
// Gated on a live tunnel. The plugin cancels the notification when the
|
||||||
|
// service stops, and re-posting after that leaves an ongoing notification
|
||||||
|
// the user cannot swipe away below Android 14.
|
||||||
|
if (_hasSyncedOnce &&
|
||||||
|
vpnConnection.status == VpnStatus.connected) {
|
||||||
|
NotificationService.updateTimer(formatted);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _forceDisconnect(String reason) {
|
Future<void> disconnect({String reason = 'User requested'}) async {
|
||||||
if (_isDisconnecting) return; // Already tearing down
|
await _doDisconnect(reason);
|
||||||
debugPrint('[Timer] $reason — forcing disconnect.');
|
}
|
||||||
|
|
||||||
|
Future<void> _doDisconnect(String reason) async {
|
||||||
|
if (_isDisconnecting) return;
|
||||||
|
_isDisconnecting = true;
|
||||||
|
debugPrint('[Timer] Disconnecting: $reason');
|
||||||
|
|
||||||
_timer?.cancel();
|
_timer?.cancel();
|
||||||
_timer = null;
|
_timer = null;
|
||||||
_currentSpeedKBps = 0.0;
|
_currentSpeedKBps = 0.0;
|
||||||
_isDisconnecting = true;
|
_remainingSeconds = 0;
|
||||||
VpnNotificationManager.cancel();
|
_hasSyncedOnce = false;
|
||||||
|
_lastSyncAt = null;
|
||||||
|
NotificationService.reset();
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
await vpnConnection.disconnect();
|
||||||
|
|
||||||
|
if (!_isDisconnecting) return;
|
||||||
|
_isDisconnecting = false;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
// Await the disconnect so the tunnel is confirmed down before we
|
|
||||||
// consider the session fully cleaned up.
|
|
||||||
vpnConnection.disconnect();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Future<void> _syncWithHivemind() async {
|
Future<void> _syncWithHivemind() async {
|
||||||
// Never sync while the user is explicitly disconnecting.
|
if (_isDisconnecting || _syncInProgress) return;
|
||||||
if (_isDisconnecting) return;
|
_syncInProgress = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final deviceId = await CryptoService.getDeviceId();
|
final deviceId = await CryptoService.getDeviceId();
|
||||||
final url = Uri.parse(
|
final url = Uri.parse(
|
||||||
'${AppConfig.hivemindApiBase}/session/status?device_id=$deviceId');
|
'${AppConfig.hivemindApiPublic}/session/status?device_id=$deviceId');
|
||||||
final response = await http.get(url).timeout(const Duration(seconds: 5));
|
final response = await HivemindService.directGet(url);
|
||||||
|
|
||||||
if (response.statusCode == 200) {
|
if (response.statusCode == 200) {
|
||||||
final data = jsonDecode(response.body);
|
final data = jsonDecode(response.body);
|
||||||
|
|
||||||
final bool active = data['active'] ?? false;
|
final bool active = data['active'] ?? false;
|
||||||
if (!active) {
|
if (!active) {
|
||||||
// Server killed the session — tear down and wait for it.
|
await _doDisconnect('Server ended session');
|
||||||
stop();
|
|
||||||
await vpnConnection.disconnect();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_remainingSeconds = data['expires_in_seconds'] ?? _remainingSeconds;
|
_remainingSeconds = data['expires_in_seconds'] ?? _remainingSeconds;
|
||||||
_usedBytes = data['used_bytes'] ?? _usedBytes;
|
_usedBytes = data['used_bytes'] ?? _usedBytes;
|
||||||
|
|
||||||
|
// Measure the real gap between polls: the interval is 5 s in the
|
||||||
|
// foreground, 30 s in the background, and arbitrary on a resume sync.
|
||||||
|
final now = DateTime.now();
|
||||||
|
final lastSync = _lastSyncAt;
|
||||||
|
_lastSyncAt = now;
|
||||||
|
|
||||||
final int deltaBytes = _usedBytes - _lastUsedBytes;
|
final int deltaBytes = _usedBytes - _lastUsedBytes;
|
||||||
if (_hasSyncedOnce && deltaBytes > 0) {
|
if (_hasSyncedOnce && deltaBytes > 0 && lastSync != null) {
|
||||||
_currentSpeedKBps = (deltaBytes / _pollIntervalSeconds) / 1000;
|
final elapsed = now.difference(lastSync).inMilliseconds / 1000.0;
|
||||||
|
_currentSpeedKBps =
|
||||||
|
elapsed > 0 ? (deltaBytes / elapsed) / 1000 : _currentSpeedKBps;
|
||||||
} else if (!_hasSyncedOnce) {
|
} else if (!_hasSyncedOnce) {
|
||||||
_currentSpeedKBps = 0.0;
|
_currentSpeedKBps = 0.0;
|
||||||
}
|
}
|
||||||
_lastUsedBytes = _usedBytes;
|
_lastUsedBytes = _usedBytes;
|
||||||
|
|
||||||
|
final capExhausted = data['cap_exhausted'] ?? false;
|
||||||
// ── Detect port change (throttle engage / disengage) ──────
|
if (capExhausted) {
|
||||||
final serverPort = data['vless_port'];
|
await _doDisconnect('Data cap reached');
|
||||||
if (serverPort != null &&
|
|
||||||
_currentPort != null &&
|
|
||||||
serverPort != _currentPort &&
|
|
||||||
!_portSwitchInProgress) {
|
|
||||||
debugPrint('[Timer] Port changed $_currentPort → $serverPort — reconnecting…');
|
|
||||||
_currentPort = serverPort;
|
|
||||||
_portSwitchInProgress = true;
|
|
||||||
|
|
||||||
_timer?.cancel();
|
|
||||||
_isDisconnecting = true;
|
|
||||||
await vpnConnection.disconnect(skipCleanup: true);
|
|
||||||
await vpnConnection.connect(skipAdBypass: true, quickReconnect: true);
|
|
||||||
|
|
||||||
_resumeTicking();
|
|
||||||
_portSwitchInProgress = false;
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_currentPort = serverPort;
|
|
||||||
|
|
||||||
_consecutiveFailures = 0;
|
_consecutiveFailures = 0;
|
||||||
_offlineSeconds = 0;
|
_offlineSeconds = 0;
|
||||||
_hasSyncedOnce = true;
|
_hasSyncedOnce = true;
|
||||||
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
} else {
|
} else {
|
||||||
_markSyncFailure();
|
_markSyncFailure();
|
||||||
@@ -248,30 +215,20 @@ class SessionTimer extends ChangeNotifier {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('Hivemind sync error: $e');
|
debugPrint('Hivemind sync error: $e');
|
||||||
_markSyncFailure();
|
_markSyncFailure();
|
||||||
|
} finally {
|
||||||
|
_syncInProgress = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _markSyncFailure() {
|
void _markSyncFailure() {
|
||||||
_consecutiveFailures++;
|
_consecutiveFailures++;
|
||||||
if (_consecutiveFailures >= _maxConsecutiveFailures) {
|
if (_consecutiveFailures >= _maxConsecutiveFailures) {
|
||||||
notifyListeners(); // let the UI show "Reconnecting…"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
void stop() {
|
|
||||||
_userInitiatedStop = true;
|
|
||||||
_isDisconnecting = true;
|
|
||||||
_timer?.cancel();
|
|
||||||
_timer = null;
|
|
||||||
_currentSpeedKBps = 0.0;
|
|
||||||
_hasSyncedOnce = false;
|
|
||||||
_remainingSeconds = 0;
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void _resumeTicking() {
|
void _resumeTicking() {
|
||||||
|
_lastSyncAt = null;
|
||||||
_timer?.cancel();
|
_timer?.cancel();
|
||||||
_timer = Timer.periodic(const Duration(seconds: 1), _tick);
|
_timer = Timer.periodic(const Duration(seconds: 1), _tick);
|
||||||
_isDisconnecting = false;
|
_isDisconnecting = false;
|
||||||
@@ -279,21 +236,25 @@ class SessionTimer extends ChangeNotifier {
|
|||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _stopInternal() {
|
@override
|
||||||
_isDisconnecting = true;
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||||
_timer?.cancel();
|
if (state == AppLifecycleState.paused ||
|
||||||
_timer = null;
|
state == AppLifecycleState.detached) {
|
||||||
_currentSpeedKBps = 0.0;
|
// Keep ticking, but slow the poll — the 5 s one wakes the radio.
|
||||||
_hasSyncedOnce = false;
|
_appBackgrounded = true;
|
||||||
VpnNotificationManager.cancel();
|
} else if (state == AppLifecycleState.resumed) {
|
||||||
notifyListeners();
|
_appBackgrounded = false;
|
||||||
|
if (_timer != null && _timer!.isActive) {
|
||||||
|
_syncWithHivemind();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
WidgetsBinding.instance.removeObserver(this);
|
||||||
vpnConnection.removeListener(_onVpnConnectionChanged);
|
vpnConnection.removeListener(_onVpnConnectionChanged);
|
||||||
_timer?.cancel();
|
_timer?.cancel();
|
||||||
VpnNotificationManager.cancel();
|
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:package_info_plus/package_info_plus.dart';
|
||||||
|
import 'package:url_launcher/url_launcher.dart';
|
||||||
|
import 'package:revoltvpn/logic/app_config.dart';
|
||||||
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
|
|
||||||
|
enum UpdateStatus { upToDate, updateAvailable, checkFailed }
|
||||||
|
|
||||||
|
enum InstallSource { playStore, sideload }
|
||||||
|
|
||||||
|
class PlayStoreUpdater {
|
||||||
|
PlayStoreUpdater._();
|
||||||
|
|
||||||
|
static String get _url =>
|
||||||
|
'https://play.google.com/store/apps/details?id=${AppConfig.applicationId}';
|
||||||
|
|
||||||
|
static Future<bool> open() async {
|
||||||
|
try {
|
||||||
|
return await launchUrl(Uri.parse(_url),
|
||||||
|
mode: LaunchMode.externalApplication);
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[Updater] Failed to open Play Store: $e');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class GitHubUpdater {
|
||||||
|
GitHubUpdater._();
|
||||||
|
|
||||||
|
static String? _cachedDownloadUrl;
|
||||||
|
|
||||||
|
static Future<String?> fetchLatestVersion() async {
|
||||||
|
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'})
|
||||||
|
.timeout(const Duration(seconds: 8));
|
||||||
|
|
||||||
|
if (response.statusCode != 200) {
|
||||||
|
debugPrint('[Updater] GitHub API returned ${response.statusCode}');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final data = jsonDecode(response.body) as Map<String, dynamic>;
|
||||||
|
_cachedDownloadUrl = data['html_url'] as String?;
|
||||||
|
|
||||||
|
final tag = data['tag_name'] as String? ?? '0.0.0';
|
||||||
|
return tag.startsWith('v') ? tag.substring(1) : tag;
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[Updater] GitHub API error: $e');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool _isTrustedReleaseUrl(String url) {
|
||||||
|
final uri = Uri.tryParse(url);
|
||||||
|
if (uri == null || uri.scheme != 'https' || uri.host != 'github.com') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Host alone is not enough: anyone can host a release on github.com.
|
||||||
|
return uri.path
|
||||||
|
.startsWith('/${AppConfig.githubOwner}/${AppConfig.githubRepo}/');
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<bool> open() async {
|
||||||
|
final cached = _cachedDownloadUrl;
|
||||||
|
final url = (cached != null && _isTrustedReleaseUrl(cached))
|
||||||
|
? cached
|
||||||
|
: AppConfig.githubReleasesUrl;
|
||||||
|
if (cached != null && url != cached) {
|
||||||
|
debugPrint('[Updater] Rejected untrusted release URL: $cached');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await launchUrl(Uri.parse(url),
|
||||||
|
mode: LaunchMode.externalApplication);
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[Updater] Failed to open GitHub: $e');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Updater {
|
||||||
|
Updater._();
|
||||||
|
|
||||||
|
static InstallSource? _cachedSource;
|
||||||
|
|
||||||
|
static Future<InstallSource> get installSource async {
|
||||||
|
if (_cachedSource != null) return _cachedSource!;
|
||||||
|
if (kIsWeb || !Platform.isAndroid) {
|
||||||
|
_cachedSource = InstallSource.sideload;
|
||||||
|
return _cachedSource!;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
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 check failed: $e');
|
||||||
|
_cachedSource = InstallSource.sideload;
|
||||||
|
}
|
||||||
|
|
||||||
|
return _cachedSource!;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 diff = (aParts.length > i ? aParts[i] : 0) -
|
||||||
|
(bParts.length > i ? bParts[i] : 0);
|
||||||
|
if (diff != 0) return diff;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _versionLabel(String v, bool isLocal) {
|
||||||
|
final prefix = v.startsWith('v') ? '' : 'v';
|
||||||
|
return '$prefix$v${isLocal ? ' (installed)' : ''}';
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<void> check({
|
||||||
|
required NavigatorState navigator,
|
||||||
|
required ScaffoldMessengerState messenger,
|
||||||
|
}) async {
|
||||||
|
final info = await PackageInfo.fromPlatform();
|
||||||
|
final localVersion = info.version;
|
||||||
|
if (localVersion.isEmpty) {
|
||||||
|
_showSnackBar(messenger, 'Could not determine app version',
|
||||||
|
isError: true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final latestVersion = await GitHubUpdater.fetchLatestVersion();
|
||||||
|
if (latestVersion == null) {
|
||||||
|
_showSnackBar(messenger, 'Could not reach GitHub', isError: true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_compareVersions(localVersion, latestVersion) >= 0) {
|
||||||
|
_showSnackBar(messenger, 'Up to date');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final source = await installSource;
|
||||||
|
final storeName = source == InstallSource.playStore ? 'Play Store' : 'GitHub';
|
||||||
|
if (!navigator.mounted) return;
|
||||||
|
|
||||||
|
showDialog(
|
||||||
|
context: navigator.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)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void _showSnackBar(ScaffoldMessengerState messenger, String message,
|
||||||
|
{bool isError = false}) {
|
||||||
|
if (!messenger.mounted) return;
|
||||||
|
messenger.showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Row(
|
||||||
|
children: [
|
||||||
|
Icon(isError ? Icons.error_outline : Icons.check_circle,
|
||||||
|
color: isError ? AppColors.red : AppColors.green,
|
||||||
|
size: 18),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(message),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
backgroundColor: AppColors.bgCard,
|
||||||
|
duration: const Duration(seconds: 2),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter/widgets.dart';
|
||||||
import 'package:flutter_vless/flutter_vless.dart';
|
import 'package:flutter_vless/flutter_vless.dart';
|
||||||
import 'package:revoltvpn/logic/hivemind_service.dart';
|
import 'package:revoltvpn/logic/hivemind_service.dart';
|
||||||
|
|
||||||
@@ -11,7 +12,7 @@ enum VpnStatus {
|
|||||||
error,
|
error,
|
||||||
}
|
}
|
||||||
|
|
||||||
class VpnConnection extends ChangeNotifier {
|
class VpnConnection extends ChangeNotifier with WidgetsBindingObserver {
|
||||||
bool _cancelled = false;
|
bool _cancelled = false;
|
||||||
VpnStatus _status = VpnStatus.disconnected;
|
VpnStatus _status = VpnStatus.disconnected;
|
||||||
VpnStatus get status => _status;
|
VpnStatus get status => _status;
|
||||||
@@ -22,7 +23,6 @@ class VpnConnection extends ChangeNotifier {
|
|||||||
String? _errorMessage;
|
String? _errorMessage;
|
||||||
String? get errorMessage => _errorMessage;
|
String? get errorMessage => _errorMessage;
|
||||||
|
|
||||||
// True when the app was killed and reopened while the VPN was running.
|
|
||||||
bool _isStartupRestoration = false;
|
bool _isStartupRestoration = false;
|
||||||
bool get isStartupRestoration => _isStartupRestoration;
|
bool get isStartupRestoration => _isStartupRestoration;
|
||||||
|
|
||||||
@@ -33,12 +33,25 @@ class VpnConnection extends ChangeNotifier {
|
|||||||
|
|
||||||
late final FlutterVless _vless;
|
late final FlutterVless _vless;
|
||||||
bool _initialized = false;
|
bool _initialized = false;
|
||||||
|
final Completer<void> _readyCompleter = Completer<void>();
|
||||||
|
Future<void> get ready => _readyCompleter.future;
|
||||||
|
|
||||||
VpnConnection() {
|
VpnConnection() {
|
||||||
|
WidgetsBinding.instance.addObserver(this);
|
||||||
_init();
|
_init();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _init() async {
|
Future<void> _init() async {
|
||||||
|
try {
|
||||||
|
await _startEngine();
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[VPN] Engine init failed: $e');
|
||||||
|
} finally {
|
||||||
|
if (!_readyCompleter.isCompleted) _readyCompleter.complete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _startEngine() async {
|
||||||
if (kIsWeb) return;
|
if (kIsWeb) return;
|
||||||
|
|
||||||
_vless = FlutterVless(
|
_vless = FlutterVless(
|
||||||
@@ -51,18 +64,17 @@ class VpnConnection extends ChangeNotifier {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await _vless.initializeVless(
|
await _vless.initializeVless(
|
||||||
providerBundleIdentifier: 'com.revoltvpn.app',
|
providerBundleIdentifier: 'com.paladinvpn.app',
|
||||||
|
notificationIconResourceType: 'drawable',
|
||||||
|
notificationIconResourceName: 'notification_icon',
|
||||||
);
|
);
|
||||||
_initialized = true;
|
_initialized = true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('[VPN] VLESS init error (expected on emulator): $e');
|
debugPrint('[VPN] VLESS init error (expected on emulator): $e');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Periodic server health check
|
_startHealthPolling();
|
||||||
_checkHealth();
|
|
||||||
_healthTimer = Timer.periodic(const Duration(seconds: 30), (_) => _checkHealth());
|
|
||||||
|
|
||||||
// Check if VPN was already running (app killed and reopened)
|
|
||||||
try {
|
try {
|
||||||
final coreVersion = await _vless.getCoreVersion();
|
final coreVersion = await _vless.getCoreVersion();
|
||||||
debugPrint('[VPN] Xray core version: $coreVersion');
|
debugPrint('[VPN] Xray core version: $coreVersion');
|
||||||
@@ -92,8 +104,6 @@ class VpnConnection extends ChangeNotifier {
|
|||||||
_setStatus(VpnStatus.disconnecting, 'Tearing down…');
|
_setStatus(VpnStatus.disconnecting, 'Tearing down…');
|
||||||
break;
|
break;
|
||||||
case VlessConnectionState.unknown:
|
case VlessConnectionState.unknown:
|
||||||
// Native backend emitted an unrecognized state — treat as error
|
|
||||||
// only if we aren't already in a terminal state.
|
|
||||||
if (_status != VpnStatus.connected &&
|
if (_status != VpnStatus.connected &&
|
||||||
_status != VpnStatus.disconnected) {
|
_status != VpnStatus.disconnected) {
|
||||||
_setStatus(VpnStatus.error, 'Connection failed');
|
_setStatus(VpnStatus.error, 'Connection failed');
|
||||||
@@ -102,7 +112,18 @@ class VpnConnection extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<bool> connect({bool skipAdBypass = false, bool quickReconnect = false}) async {
|
// ── Connect ────────────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// 1. Direct HTTPS to the public API → get per-user VLESS URL
|
||||||
|
// 2. Start tunnel directly with that URL (no bootstrap, no switch)
|
||||||
|
//
|
||||||
|
// The only hardcoded data in the APK is the Reality public key and
|
||||||
|
// shortId (needed for every Reality handshake — unavoidable).
|
||||||
|
// The tunnel UUID is per-user, assigned by Hivemind via AdMob SSV.
|
||||||
|
|
||||||
|
Future<bool> connect({
|
||||||
|
bool skipAdBypass = false,
|
||||||
|
}) async {
|
||||||
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) {
|
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -114,7 +135,16 @@ class VpnConnection extends ChangeNotifier {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
_setStatus(VpnStatus.connecting, 'Fetching config…');
|
if (!kIsWeb) {
|
||||||
|
final ok = await _vless.requestPermission();
|
||||||
|
if (!ok) {
|
||||||
|
_errorMessage = 'VPN permission denied.';
|
||||||
|
_setStatus(VpnStatus.error, 'Permission required');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_setStatus(VpnStatus.connecting, 'Establishing secure channel…');
|
||||||
_errorMessage = null;
|
_errorMessage = null;
|
||||||
|
|
||||||
if (kIsWeb) {
|
if (kIsWeb) {
|
||||||
@@ -123,33 +153,28 @@ class VpnConnection extends ChangeNotifier {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
String vlessUrl;
|
_setStatus(VpnStatus.connecting, 'Fetching config…');
|
||||||
|
|
||||||
|
String realUrl;
|
||||||
try {
|
try {
|
||||||
vlessUrl = await HivemindService.fetchConfigWithPolling(
|
realUrl = await HivemindService.fetchConfigDirectly(
|
||||||
skipAdBypass: skipAdBypass,
|
skipAdBypass: skipAdBypass,
|
||||||
quickReconnect: quickReconnect,
|
|
||||||
onAttempt: (attempt, total) {
|
onAttempt: (attempt, total) {
|
||||||
if (!quickReconnect) {
|
_setStatus(
|
||||||
_setStatus(VpnStatus.connecting, 'Contacting server ($attempt/$total)…');
|
VpnStatus.connecting, 'Contacting server ($attempt/$total)…');
|
||||||
}
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('[VPN] Hivemind config error: $e');
|
debugPrint('[VPN] Config fetch error: $e');
|
||||||
final raw = e.toString().replaceAll('Exception: ', '');
|
final raw = e.toString().replaceAll('Exception: ', '');
|
||||||
if (raw.contains('Cancelled')) {
|
if (raw.contains('Cancelled')) return false;
|
||||||
// User tapped disconnect — silently abort
|
if (raw.contains('timed out') || raw.contains('Session not activated')) {
|
||||||
return false;
|
_errorMessage =
|
||||||
} else if (raw.contains('timed out') || raw.contains('Session not activated')) {
|
'The server did not respond in time.\nCheck your connection and try again.';
|
||||||
_errorMessage = 'The server did not respond in time.\nCheck your connection and try again.';
|
|
||||||
_setStatus(VpnStatus.error, 'Server unreachable');
|
_setStatus(VpnStatus.error, 'Server unreachable');
|
||||||
} else if (raw.contains('SocketException') || raw.contains('Failed host lookup')) {
|
|
||||||
_errorMessage = 'Cannot reach the server.\nMake sure you have internet access.';
|
|
||||||
_setStatus(VpnStatus.error, 'No internet');
|
|
||||||
} else {
|
} else {
|
||||||
_errorMessage = raw;
|
_errorMessage = e.toString().replaceAll('Exception: ', '');
|
||||||
final short = raw.length > 35 ? '${raw.substring(0, 35)}…' : raw;
|
_setStatus(VpnStatus.error, 'Config fetch error');
|
||||||
_setStatus(VpnStatus.error, short);
|
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -159,57 +184,31 @@ class VpnConnection extends ChangeNotifier {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_setStatus(VpnStatus.connecting, 'Securing connection…');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final parsed = FlutterVless.parse(vlessUrl);
|
final parsed = FlutterVless.parse(realUrl);
|
||||||
final config = parsed.getFullConfiguration();
|
|
||||||
|
|
||||||
await _vless.startVless(
|
await _vless.startVless(
|
||||||
remark: parsed.remark.isNotEmpty ? parsed.remark : 'ReVoltVPN',
|
remark: parsed.remark.isNotEmpty ? parsed.remark : 'Revolt VPN',
|
||||||
config: config,
|
config: parsed.getFullConfiguration(),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (quickReconnect) {
|
|
||||||
_setStatus(VpnStatus.connected, 'Secured');
|
|
||||||
} else {
|
|
||||||
// Give the tunnel a moment to stabilise
|
|
||||||
_setStatus(VpnStatus.connecting, 'Verifying session…');
|
|
||||||
await Future.delayed(const Duration(seconds: 1));
|
|
||||||
|
|
||||||
bool sessionOk = false;
|
|
||||||
for (int attempt = 0; attempt < 2; attempt++) {
|
|
||||||
sessionOk = await HivemindService.verifySession();
|
|
||||||
if (sessionOk) break;
|
|
||||||
if (attempt == 0) {
|
|
||||||
debugPrint('[VPN] verifySession attempt 1 failed, retrying…');
|
|
||||||
await Future.delayed(const Duration(seconds: 2));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!sessionOk) {
|
|
||||||
debugPrint('[VPN] Tunnel started but no server session — tearing down.');
|
|
||||||
try {
|
|
||||||
await _vless.stopVless();
|
|
||||||
} catch (_) {}
|
|
||||||
_errorMessage = 'Session not confirmed by server.\nPlease try again.';
|
|
||||||
_setStatus(VpnStatus.error, 'Session rejected');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
_setStatus(VpnStatus.connected, 'Secured');
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('[VPN] VLESS tunnel error: $e');
|
debugPrint('[VPN] Tunnel start error: $e');
|
||||||
_errorMessage = 'Tunnel failed to start.\nTry reconnecting.';
|
_errorMessage = 'Tunnel failed to start.\nTry reconnecting.';
|
||||||
_setStatus(VpnStatus.error, 'Connection failed');
|
_setStatus(VpnStatus.error, 'Connection failed');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_setStatus(VpnStatus.connected, 'Secured');
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> disconnect({bool skipCleanup = false}) async {
|
Future<void> disconnect() async {
|
||||||
_cancelled = true;
|
_cancelled = true;
|
||||||
HivemindService.cancel(); // abort any in-progress polling
|
HivemindService.cancel();
|
||||||
if (_status == VpnStatus.disconnected || _status == VpnStatus.disconnecting) {
|
if (_status == VpnStatus.disconnected ||
|
||||||
|
_status == VpnStatus.disconnecting) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,18 +220,28 @@ class VpnConnection extends ChangeNotifier {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool timedOut = false;
|
||||||
try {
|
try {
|
||||||
await _vless.stopVless().timeout(
|
await _vless.stopVless().timeout(
|
||||||
const Duration(seconds: 5),
|
const Duration(seconds: 5),
|
||||||
onTimeout: () => debugPrint('[VPN] stopVless() timed out.'),
|
onTimeout: () => timedOut = true,
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('[VPN] VLESS stop error: $e');
|
debugPrint('[VPN] VLESS stop error: $e');
|
||||||
|
_errorMessage = 'VPN shutdown error.\nPlease restart the app.';
|
||||||
|
_setStatus(VpnStatus.error, 'Shutdown failed');
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!skipCleanup) {
|
if (timedOut) {
|
||||||
HivemindService.disconnectAndCleanup();
|
debugPrint('[VPN] stopVless() timed out after 5 s — '
|
||||||
|
'tunnel may still be active.');
|
||||||
|
_errorMessage = 'VPN did not shut down cleanly.\n'
|
||||||
|
'Please restart the app.';
|
||||||
|
_setStatus(VpnStatus.error, 'Shutdown failed');
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_setStatus(VpnStatus.disconnected, 'Tap to connect');
|
_setStatus(VpnStatus.disconnected, 'Tap to connect');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -242,20 +251,42 @@ class VpnConnection extends ChangeNotifier {
|
|||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _startHealthPolling() {
|
||||||
|
_healthTimer?.cancel();
|
||||||
|
_checkHealthIfIdle();
|
||||||
|
_healthTimer = Timer.periodic(
|
||||||
|
const Duration(seconds: 30), (_) => _checkHealthIfIdle());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _checkHealthIfIdle() async {
|
||||||
|
// A live tunnel already proves reachability.
|
||||||
|
if (_status == VpnStatus.connected) return;
|
||||||
|
await _checkHealth();
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _checkHealth() async {
|
Future<void> _checkHealth() async {
|
||||||
_serverReachable = await HivemindService.checkHealth();
|
_serverReachable = await HivemindService.checkHealth();
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||||
|
if (state == AppLifecycleState.paused ||
|
||||||
|
state == AppLifecycleState.detached) {
|
||||||
|
_healthTimer?.cancel();
|
||||||
|
} else if (state == AppLifecycleState.resumed) {
|
||||||
|
_startHealthPolling();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
WidgetsBinding.instance.removeObserver(this);
|
||||||
_healthTimer?.cancel();
|
_healthTimer?.cancel();
|
||||||
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) {
|
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) {
|
||||||
try {
|
try {
|
||||||
_vless.stopVless();
|
_vless.stopVless();
|
||||||
} catch (_) {
|
} catch (_) {}
|
||||||
// Best-effort — widget is being destroyed anyway
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,16 +2,14 @@ import 'package:flutter/material.dart';
|
|||||||
import 'dart:ui';
|
import 'dart:ui';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
import 'package:google_mobile_ads/google_mobile_ads.dart';
|
|
||||||
|
|
||||||
import 'package:revoltvpn/logic/vpn_connection.dart';
|
import 'package:revoltvpn/logic/vpn_connection.dart';
|
||||||
import 'package:revoltvpn/logic/session_timer.dart';
|
import 'package:revoltvpn/logic/session_timer.dart';
|
||||||
import 'package:revoltvpn/logic/ad_manager.dart';
|
import 'package:revoltvpn/logic/ad_manager.dart';
|
||||||
import 'package:revoltvpn/logic/consent_manager.dart';
|
import 'package:revoltvpn/logic/server_list.dart';
|
||||||
import 'package:revoltvpn/logic/app_colors.dart';
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
import 'package:revoltvpn/screens/intro.dart';
|
import 'package:revoltvpn/screens/intro.dart';
|
||||||
|
void main() {
|
||||||
void main() async {
|
|
||||||
WidgetsFlutterBinding.ensureInitialized();
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
|
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
|
||||||
@@ -32,9 +30,6 @@ void main() async {
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
await ConsentManager.requestConsentIfNeeded();
|
|
||||||
await MobileAds.instance.initialize();
|
|
||||||
|
|
||||||
runApp(const ReVoltApp());
|
runApp(const ReVoltApp());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,12 +40,18 @@ class ReVoltApp extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return MultiProvider(
|
return MultiProvider(
|
||||||
providers: [
|
providers: [
|
||||||
ChangeNotifierProvider(create: (_) => VpnConnection()),
|
// lazy: false — the native VLESS engine takes real time to start, and
|
||||||
|
// providers are lazy by default, so it used to begin initialising only
|
||||||
|
// once MainScreen first read it, i.e. *after* the loading screen was
|
||||||
|
// gone. Constructing it eagerly moves that work under the intro, which
|
||||||
|
// now awaits VpnConnection.ready before navigating.
|
||||||
|
ChangeNotifierProvider(create: (_) => VpnConnection(), lazy: false),
|
||||||
ChangeNotifierProxyProvider<VpnConnection, SessionTimer>(
|
ChangeNotifierProxyProvider<VpnConnection, SessionTimer>(
|
||||||
create: (ctx) => SessionTimer(vpnConnection: ctx.read<VpnConnection>()),
|
create: (ctx) => SessionTimer(vpnConnection: ctx.read<VpnConnection>()),
|
||||||
update: (_, vpn, prev) => prev ?? SessionTimer(vpnConnection: vpn),
|
update: (_, vpn, prev) => prev ?? SessionTimer(vpnConnection: vpn),
|
||||||
),
|
),
|
||||||
ChangeNotifierProvider(create: (_) => AdManager()),
|
ChangeNotifierProvider(create: (_) => AdManager()),
|
||||||
|
ChangeNotifierProvider(create: (_) => ServerList()..init(), lazy: false),
|
||||||
],
|
],
|
||||||
child: MaterialApp(
|
child: MaterialApp(
|
||||||
title: 'ReVolt VPN',
|
title: 'ReVolt VPN',
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
import 'package:revoltvpn/logic/app_colors.dart';
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
|
import 'package:revoltvpn/logic/vpn_connection.dart';
|
||||||
import 'package:revoltvpn/screens/main_screen.dart';
|
import 'package:revoltvpn/screens/main_screen.dart';
|
||||||
|
import 'package:revoltvpn/screens/settings/in_settings/rain.dart';
|
||||||
|
import 'package:revoltvpn/screens/settings/in_settings/lightning.dart';
|
||||||
|
import 'package:revoltvpn/screens/settings/in_settings/haptic.dart';
|
||||||
|
|
||||||
class IntroScreen extends StatefulWidget {
|
class IntroScreen extends StatefulWidget {
|
||||||
const IntroScreen({super.key});
|
const IntroScreen({super.key});
|
||||||
@@ -11,11 +16,18 @@ class IntroScreen extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
|
class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
|
||||||
|
static const _minDisplay = Duration(milliseconds: 500);
|
||||||
|
static const _bootTimeout = Duration(seconds: 8);
|
||||||
|
|
||||||
|
String _status = 'Starting secure engine…';
|
||||||
|
bool _bootComplete = false;
|
||||||
|
bool _navigated = false;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
_scheduleNavigation();
|
_boot();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -26,28 +38,54 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||||
if (state == AppLifecycleState.resumed) {
|
if (state == AppLifecycleState.resumed) _navigateIfReady();
|
||||||
_navigateToMain();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _boot() async {
|
||||||
|
final elapsed = Stopwatch()..start();
|
||||||
|
final vpn = context.read<VpnConnection>();
|
||||||
|
|
||||||
|
// The overlays read these in initState, so they must land before
|
||||||
|
// MainScreen mounts.
|
||||||
|
final settingsPrefs = Future.wait(
|
||||||
|
[loadRainPref(), loadLightningPref(), loadHapticPref()]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await vpn.ready.timeout(_bootTimeout);
|
||||||
|
} on TimeoutException {
|
||||||
|
debugPrint('[Boot] Engine init exceeded ${_bootTimeout.inSeconds}s '
|
||||||
|
'— continuing to the main screen anyway.');
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[Boot] Engine init error: $e');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await settingsPrefs;
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[Boot] Settings prefs load failed, using defaults: $e');
|
||||||
}
|
}
|
||||||
|
|
||||||
void _scheduleNavigation() {
|
|
||||||
// Brief natural pause — just long enough to perceive the logo.
|
|
||||||
Timer(const Duration(milliseconds: 1200), () {
|
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
|
setState(() => _status = 'Ready');
|
||||||
|
|
||||||
|
final remaining = _minDisplay - elapsed.elapsed;
|
||||||
|
if (remaining > Duration.zero) await Future.delayed(remaining);
|
||||||
|
|
||||||
|
if (!mounted) return;
|
||||||
|
_bootComplete = true;
|
||||||
|
_navigateIfReady();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _navigateIfReady() {
|
||||||
|
if (!mounted || _navigated || !_bootComplete) return;
|
||||||
if (WidgetsBinding.instance.lifecycleState == AppLifecycleState.paused) {
|
if (WidgetsBinding.instance.lifecycleState == AppLifecycleState.paused) {
|
||||||
// App is backgrounded — defer navigation until resumed.
|
return; // resume will call back in
|
||||||
return;
|
|
||||||
}
|
|
||||||
_navigateToMain();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
_navigated = true;
|
||||||
|
|
||||||
void _navigateToMain() {
|
|
||||||
if (!mounted) return;
|
|
||||||
Navigator.of(context).pushReplacement(
|
Navigator.of(context).pushReplacement(
|
||||||
PageRouteBuilder(
|
PageRouteBuilder(
|
||||||
transitionDuration: const Duration(milliseconds: 600),
|
transitionDuration: const Duration(milliseconds: 400),
|
||||||
pageBuilder: (_, __, ___) => const MainScreen(),
|
pageBuilder: (_, __, ___) => const MainScreen(),
|
||||||
transitionsBuilder: (_, animation, __, child) {
|
transitionsBuilder: (_, animation, __, child) {
|
||||||
return FadeTransition(opacity: animation, child: child);
|
return FadeTransition(opacity: animation, child: child);
|
||||||
@@ -90,7 +128,7 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
const Text(
|
const Text(
|
||||||
'REVOLT VPN',
|
'Revolt VPN',
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: AppColors.textWhite,
|
color: AppColors.textWhite,
|
||||||
fontSize: 28,
|
fontSize: 28,
|
||||||
@@ -98,6 +136,20 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
|
|||||||
letterSpacing: 2.0,
|
letterSpacing: 2.0,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
// Says what the spinner is actually waiting on.
|
||||||
|
AnimatedSwitcher(
|
||||||
|
duration: const Duration(milliseconds: 250),
|
||||||
|
child: Text(
|
||||||
|
_status,
|
||||||
|
key: ValueKey(_status),
|
||||||
|
style: const TextStyle(
|
||||||
|
color: AppColors.textDim,
|
||||||
|
fontSize: 13,
|
||||||
|
letterSpacing: 0.5,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
const Spacer(flex: 5),
|
const Spacer(flex: 5),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,15 +1,32 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:revoltvpn/logic/app_colors.dart';
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
import 'package:revoltvpn/components/connect_button.dart';
|
import 'package:revoltvpn/components/connect_button.dart';
|
||||||
|
import 'package:revoltvpn/components/data_disclosure_dialog.dart';
|
||||||
import 'package:revoltvpn/components/sidebar_drawer.dart';
|
import 'package:revoltvpn/components/sidebar_drawer.dart';
|
||||||
import 'package:revoltvpn/components/timer_box.dart';
|
import 'package:revoltvpn/components/timer_box.dart';
|
||||||
import 'package:revoltvpn/components/speed_box.dart';
|
import 'package:revoltvpn/components/speed_box.dart';
|
||||||
import 'package:revoltvpn/components/status_bar.dart';
|
import 'package:revoltvpn/components/status_bar.dart';
|
||||||
import 'package:revoltvpn/components/support_button.dart';
|
import 'package:revoltvpn/components/support_button.dart';
|
||||||
|
import 'package:revoltvpn/components/rain.dart';
|
||||||
|
import 'package:revoltvpn/components/lightning.dart';
|
||||||
|
|
||||||
class MainScreen extends StatelessWidget {
|
class MainScreen extends StatefulWidget {
|
||||||
const MainScreen({super.key});
|
const MainScreen({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<MainScreen> createState() => _MainScreenState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _MainScreenState extends State<MainScreen> {
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
// Show data disclosure on first launch — Google Play Data safety requirement.
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
DataDisclosureDialog.showIfFirstLaunch(context);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
@@ -27,8 +44,21 @@ class MainScreen extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
child: SafeArea(
|
child: SafeArea(
|
||||||
child: Stack(
|
child: LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
// Proportional positioning — fractions of available height.
|
||||||
|
// On the reference device (~700 dp) this produces the exact
|
||||||
|
// original pixel positions (100, 175, 250, 520) and scales
|
||||||
|
// proportionally on taller/shorter screens.
|
||||||
|
final h = constraints.maxHeight;
|
||||||
|
return Stack(
|
||||||
children: [
|
children: [
|
||||||
|
// Lightning — behind rain
|
||||||
|
const Positioned.fill(child: LightningEffect()),
|
||||||
|
|
||||||
|
// Rain — behind all UI
|
||||||
|
const Positioned.fill(child: RainEffect()),
|
||||||
|
|
||||||
Positioned(
|
Positioned(
|
||||||
top: 0,
|
top: 0,
|
||||||
right: 4,
|
right: 4,
|
||||||
@@ -42,40 +72,42 @@ class MainScreen extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
|
|
||||||
Positioned(
|
Positioned(
|
||||||
top: 100, // <-- CHANGE ME: timer distance from top
|
top: h * 0.143,
|
||||||
left: 0,
|
left: 0,
|
||||||
right: 0,
|
right: 0,
|
||||||
child: const Center(child: TimerBox()),
|
child: const Center(child: TimerBox()),
|
||||||
),
|
),
|
||||||
|
|
||||||
Positioned(
|
Positioned(
|
||||||
top: 175, // <-- CHANGE ME: support button from top
|
top: h * 0.250,
|
||||||
left: 0,
|
left: 0,
|
||||||
right: 0,
|
right: 0,
|
||||||
child: const Center(child: SupportButton()),
|
child: const Center(child: SupportButton()),
|
||||||
),
|
),
|
||||||
|
|
||||||
Positioned(
|
Positioned(
|
||||||
top: 250, // <-- CHANGE ME: connect button from top
|
top: h * 0.357,
|
||||||
left: 0,
|
left: 0,
|
||||||
right: 0,
|
right: 0,
|
||||||
child: const Center(child: ConnectButton()),
|
child: const Center(child: ConnectButton()),
|
||||||
),
|
),
|
||||||
|
|
||||||
Positioned(
|
Positioned(
|
||||||
top: 520, // <-- CHANGE ME: speed box from top
|
top: h * 0.743,
|
||||||
left: 0,
|
left: 0,
|
||||||
right: 0,
|
right: 0,
|
||||||
child: const Center(child: SpeedBox()),
|
child: const Center(child: SpeedBox()),
|
||||||
),
|
),
|
||||||
|
|
||||||
Positioned(
|
const Positioned(
|
||||||
bottom: 16, // <-- CHANGE ME: status bar from bottom
|
bottom: 16,
|
||||||
left: 0,
|
left: 0,
|
||||||
right: 0,
|
right: 0,
|
||||||
child: const StatusBar(),
|
child: StatusBar(),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
|
import 'package:revoltvpn/logic/server_list.dart';
|
||||||
|
|
||||||
|
// ── lib/screens/server_selector/selection_screen.dart ──────────────────────
|
||||||
|
// Server picker — reads the server list from the ServerList provider.
|
||||||
|
// Each row shows a flag + city name. Tapping a row persists the choice
|
||||||
|
// and pops back. No latency measurement — the app runs inside a Reality
|
||||||
|
// tunnel and must not emit separate probe traffic.
|
||||||
|
|
||||||
|
class SelectionScreen extends StatelessWidget {
|
||||||
|
const SelectionScreen({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final serverList = context.watch<ServerList>();
|
||||||
|
|
||||||
|
return Scaffold(
|
||||||
|
backgroundColor: AppColors.bgDeep,
|
||||||
|
appBar: AppBar(
|
||||||
|
backgroundColor: AppColors.bgSurface,
|
||||||
|
elevation: 0,
|
||||||
|
leading: IconButton(
|
||||||
|
icon: const Icon(Icons.arrow_back, color: AppColors.textWhite),
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
),
|
||||||
|
title: const Text(
|
||||||
|
'Select Server',
|
||||||
|
style: TextStyle(
|
||||||
|
color: AppColors.textWhite,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
body: ListView.builder(
|
||||||
|
itemCount: serverList.all.length,
|
||||||
|
itemBuilder: (context, index) {
|
||||||
|
final server = serverList.all[index];
|
||||||
|
final isSelected = index == serverList.selectedIndex;
|
||||||
|
|
||||||
|
return ListTile(
|
||||||
|
leading: Image.asset(server.flagAsset, width: 28, height: 28),
|
||||||
|
title: Text(server.name,
|
||||||
|
style: TextStyle(
|
||||||
|
color: isSelected ? AppColors.accent : AppColors.textWhite,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
)),
|
||||||
|
trailing: isSelected
|
||||||
|
? const Icon(Icons.check, color: AppColors.accent)
|
||||||
|
: null,
|
||||||
|
onTap: () {
|
||||||
|
serverList.select(index);
|
||||||
|
Navigator.of(context).pop();
|
||||||
|
},
|
||||||
|
contentPadding:
|
||||||
|
const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
|
|
||||||
|
// A plain bool, not a ValueNotifier: this is only read at the moment of a tap,
|
||||||
|
// so nothing has to react to it changing. Default: false.
|
||||||
|
bool hapticEnabled = false;
|
||||||
|
|
||||||
|
/// Hydrates [hapticEnabled] from disk. Called at boot — the toggle tile below
|
||||||
|
/// only mounts once Settings is opened.
|
||||||
|
Future<void> loadHapticPref() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
hapticEnabled = prefs.getBool('haptic_feedback_enabled') ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Haptic calls are deliberately best-effort: a vibration failure must never
|
||||||
|
/// block or fail a VPN connect/disconnect. `mediumImpact` is used instead of
|
||||||
|
/// `lightImpact` — the latter is imperceptible on many Android devices.
|
||||||
|
class Haptics {
|
||||||
|
Haptics._();
|
||||||
|
|
||||||
|
static Future<void> connectionChanged() async {
|
||||||
|
if (!hapticEnabled) return;
|
||||||
|
try {
|
||||||
|
await HapticFeedback.mediumImpact();
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[Haptics] Feedback unavailable: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<void> previewEnabled() async {
|
||||||
|
try {
|
||||||
|
await HapticFeedback.selectionClick();
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[Haptics] Preview unavailable: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class HapticFeedbackTile extends StatefulWidget {
|
||||||
|
const HapticFeedbackTile({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<HapticFeedbackTile> createState() => _HapticFeedbackTileState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HapticFeedbackTileState extends State<HapticFeedbackTile> {
|
||||||
|
bool _on = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
await loadHapticPref();
|
||||||
|
if (mounted) setState(() => _on = hapticEnabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Writes to SharedPreferences AND updates the live bool so the connect
|
||||||
|
// button sees the change immediately — no restart needed.
|
||||||
|
Future<void> _toggle(bool value) async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setBool('haptic_feedback_enabled', value);
|
||||||
|
hapticEnabled = value;
|
||||||
|
if (value) unawaited(Haptics.previewEnabled());
|
||||||
|
setState(() => _on = value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return SwitchListTile(
|
||||||
|
title: const Text(
|
||||||
|
'Haptic feedback',
|
||||||
|
style: TextStyle(color: AppColors.textWhite, fontSize: 15),
|
||||||
|
),
|
||||||
|
value: _on,
|
||||||
|
onChanged: _toggle,
|
||||||
|
activeTrackColor: AppColors.accent.withAlpha(80),
|
||||||
|
activeThumbColor: AppColors.accent,
|
||||||
|
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
|
|
||||||
|
// ── lib/screens/settings/in_settings/lightning.dart ─────────────────────────
|
||||||
|
// Toggle for the lightning strike overlay on the main screen.
|
||||||
|
|
||||||
|
final ValueNotifier<bool> lightningEnabled = ValueNotifier(true);
|
||||||
|
|
||||||
|
Future<void> loadLightningPref() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
lightningEnabled.value = prefs.getBool('lightning_effect_enabled') ?? true;
|
||||||
|
}
|
||||||
|
|
||||||
|
class LightningToggleTile extends StatefulWidget {
|
||||||
|
const LightningToggleTile({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<LightningToggleTile> createState() => _LightningToggleTileState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _LightningToggleTileState extends State<LightningToggleTile> {
|
||||||
|
bool _on = true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
await loadLightningPref();
|
||||||
|
if (mounted) setState(() => _on = lightningEnabled.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _toggle(bool value) async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setBool('lightning_effect_enabled', value);
|
||||||
|
lightningEnabled.value = value;
|
||||||
|
setState(() => _on = value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return SwitchListTile(
|
||||||
|
title: const Text(
|
||||||
|
'Lightning effect',
|
||||||
|
style: TextStyle(color: AppColors.textWhite, fontSize: 15),
|
||||||
|
),
|
||||||
|
value: _on,
|
||||||
|
onChanged: _toggle,
|
||||||
|
activeTrackColor: AppColors.accent.withAlpha(80),
|
||||||
|
activeThumbColor: AppColors.accent,
|
||||||
|
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
|
|
||||||
|
// ── lib/screens/settings/in_settings/rain.dart ──────────────────────────────
|
||||||
|
// Toggle for the animated rain overlay on the main screen.
|
||||||
|
|
||||||
|
final ValueNotifier<bool> rainEnabled = ValueNotifier(true);
|
||||||
|
|
||||||
|
Future<void> loadRainPref() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
rainEnabled.value = prefs.getBool('rain_effect_enabled') ?? true;
|
||||||
|
}
|
||||||
|
|
||||||
|
class RainToggleTile extends StatefulWidget {
|
||||||
|
const RainToggleTile({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<RainToggleTile> createState() => _RainToggleTileState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RainToggleTileState extends State<RainToggleTile> {
|
||||||
|
bool _on = true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
await loadRainPref();
|
||||||
|
if (mounted) setState(() => _on = rainEnabled.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _toggle(bool value) async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setBool('rain_effect_enabled', value);
|
||||||
|
rainEnabled.value = value;
|
||||||
|
setState(() => _on = value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return SwitchListTile(
|
||||||
|
title: const Text(
|
||||||
|
'Rain effect',
|
||||||
|
style: TextStyle(color: AppColors.textWhite, fontSize: 15),
|
||||||
|
),
|
||||||
|
value: _on,
|
||||||
|
onChanged: _toggle,
|
||||||
|
activeTrackColor: AppColors.accent.withAlpha(80),
|
||||||
|
activeThumbColor: AppColors.accent,
|
||||||
|
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:revoltvpn/logic/app_colors.dart';
|
||||||
|
import 'package:revoltvpn/screens/settings/in_settings/haptic.dart';
|
||||||
|
import 'package:revoltvpn/screens/settings/in_settings/rain.dart';
|
||||||
|
import 'package:revoltvpn/screens/settings/in_settings/lightning.dart';
|
||||||
|
|
||||||
|
// ── lib/screens/settings/settings_screen.dart ────────────────────────────────
|
||||||
|
// Settings shell — full-screen page reached from the sidebar.
|
||||||
|
//
|
||||||
|
// Folder layout:
|
||||||
|
// lib/screens/settings/ ← this folder: settings family
|
||||||
|
// settings_screen.dart ← shell: Scaffold + AppBar + ListView (this file)
|
||||||
|
// *_tile.dart ← one file per setting feature (add below)
|
||||||
|
// lib/components/sidebar_contents/
|
||||||
|
// settings.dart ← thin sidebar row that navigates here
|
||||||
|
//
|
||||||
|
// To add a setting:
|
||||||
|
// 1. Create a new file in this folder, e.g. appearance_tile.dart
|
||||||
|
// 2. Import it below
|
||||||
|
// 3. Append it to the children list
|
||||||
|
|
||||||
|
class SettingsScreen extends StatelessWidget {
|
||||||
|
const SettingsScreen({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Scaffold(
|
||||||
|
backgroundColor: AppColors.bgDeep,
|
||||||
|
appBar: AppBar(
|
||||||
|
backgroundColor: AppColors.bgSurface,
|
||||||
|
elevation: 0,
|
||||||
|
leading: IconButton(
|
||||||
|
icon: const Icon(Icons.arrow_back, color: AppColors.textWhite),
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
),
|
||||||
|
title: const Text(
|
||||||
|
'Settings',
|
||||||
|
style: TextStyle(
|
||||||
|
color: AppColors.textWhite,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
body: ListView(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||||
|
children: const [
|
||||||
|
HapticFeedbackTile(),
|
||||||
|
RainToggleTile(),
|
||||||
|
LightningToggleTile(),
|
||||||
|
// ── Add setting tiles here ────────────────────────────────────────
|
||||||
|
// Each tile imports from its own file in this folder.
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -97,14 +97,6 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.2.0"
|
version: "2.2.0"
|
||||||
ffi_leak_tracker:
|
|
||||||
dependency: transitive
|
|
||||||
description:
|
|
||||||
name: ffi_leak_tracker
|
|
||||||
sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97"
|
|
||||||
url: "https://pub.dev"
|
|
||||||
source: hosted
|
|
||||||
version: "0.1.2"
|
|
||||||
file:
|
file:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -202,10 +194,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: flutter_secure_storage_windows
|
name: flutter_secure_storage_windows
|
||||||
sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1"
|
sha256: "3b7c8e068875dfd46719ff57c90d8c459c87f2302ed6b00ff006b3c9fcad1613"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "4.2.2"
|
version: "4.1.0"
|
||||||
flutter_test:
|
flutter_test:
|
||||||
dependency: "direct dev"
|
dependency: "direct dev"
|
||||||
description: flutter
|
description: flutter
|
||||||
@@ -215,26 +207,26 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: flutter_vless
|
name: flutter_vless
|
||||||
sha256: aa66ea904e7593cc9b2f8f12c291a3a1f404377125d5cd9faa6399d444f511ab
|
sha256: db242f7fe007d35b4d51c5bd5b895d816f141e4d4afc7038c3b6228c1c66dfb5
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.1.4"
|
version: "1.1.5"
|
||||||
flutter_vless_android:
|
flutter_vless_android:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: flutter_vless_android
|
name: flutter_vless_android
|
||||||
sha256: f2f2c81a410a7341ea05dfe3643b213530be44d6574bc91fa29c0bd417d97ac2
|
sha256: "5e6fe73d3606ed8c73e87fac15efa7631e12ce18d39a4bd4e13b6c097c6d52b9"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.1.4"
|
version: "1.1.5"
|
||||||
flutter_vless_macos:
|
flutter_vless_macos:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: flutter_vless_macos
|
name: flutter_vless_macos
|
||||||
sha256: "096c21bd9728ee2856325c85f60bc7075dda44f99205dd0baa82e5a1223a62a2"
|
sha256: "2651eda1ae75aff8d0acd74f3d38980c71e7629075eee7aa57e52897479f973f"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.1.4"
|
version: "1.1.5"
|
||||||
flutter_vless_platform_interface:
|
flutter_vless_platform_interface:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -400,6 +392,22 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.2.0"
|
version: "2.2.0"
|
||||||
|
package_info_plus:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: package_info_plus
|
||||||
|
sha256: cb44f49b6e690fa766f023d5b22cac6b9affe741dd792b6ac7ad4fabe0d7b097
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "6.0.0"
|
||||||
|
package_info_plus_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: package_info_plus_platform_interface
|
||||||
|
sha256: "9bc8ba46813a4cc42c66ab781470711781940780fd8beddd0c3da62506d3a6c6"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.0.1"
|
||||||
path:
|
path:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -721,10 +729,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: web
|
name: web
|
||||||
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
|
sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27"
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.1.1"
|
version: "0.5.1"
|
||||||
webview_flutter:
|
webview_flutter:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -761,10 +769,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: win32
|
name: win32
|
||||||
sha256: ba6f4bba816c8d7e3c1580e170f3786d216951cc6b94babc3b814c08d2cb2738
|
sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "6.3.0"
|
version: "5.15.0"
|
||||||
xdg_directories:
|
xdg_directories:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
|
|||||||
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
|
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
|
||||||
# Read more about iOS versioning at
|
# Read more about iOS versioning at
|
||||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
version: 1.0.6+10
|
version: 3.3.0+26
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ">=3.0.0 <4.0.0"
|
sdk: ">=3.0.0 <4.0.0"
|
||||||
@@ -30,7 +30,7 @@ dependencies:
|
|||||||
google_fonts: ^6.1.0
|
google_fonts: ^6.1.0
|
||||||
provider: ^6.1.1
|
provider: ^6.1.1
|
||||||
google_mobile_ads: ^4.0.0
|
google_mobile_ads: ^4.0.0
|
||||||
flutter_vless: 1.1.4
|
flutter_vless: 1.1.5
|
||||||
http: ^1.6.0
|
http: ^1.6.0
|
||||||
shared_preferences: ^2.5.5
|
shared_preferences: ^2.5.5
|
||||||
url_launcher: ^6.3.2
|
url_launcher: ^6.3.2
|
||||||
@@ -38,6 +38,7 @@ dependencies:
|
|||||||
uuid: ^4.5.3
|
uuid: ^4.5.3
|
||||||
flutter_local_notifications: ^17.0.0
|
flutter_local_notifications: ^17.0.0
|
||||||
path_provider: ^2.1.5
|
path_provider: ^2.1.5
|
||||||
|
package_info_plus: ^6.0.0
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
|||||||
@@ -1,737 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""
|
|
||||||
Hivemind VPN Session Manager
|
|
||||||
Manages VLESS Reality sessions via ad rewards — 60 min, throttle at 4 GB.
|
|
||||||
Designed for Android-only clients.
|
|
||||||
|
|
||||||
=== TABLE OF CONTENTS ===========================================================
|
|
||||||
Configuration — ad rewards, Reality constants, Xray paths
|
|
||||||
State & Cache — sessions dict, stats failure counter
|
|
||||||
Flask Routes — /admob/callback, /session/status, /session/stop
|
|
||||||
Session Logic — _start_or_extend_session, _extend_session
|
|
||||||
AdMob SSV Verification — Google ECDSA signature checks
|
|
||||||
Management Loop — expiry + throttle watchdog (60 s tick)
|
|
||||||
Low-Level Plumbing — add/remove users, Xray stats
|
|
||||||
Entry Point — daemon thread + gunicorn bootstrap
|
|
||||||
================================================================================
|
|
||||||
"""
|
|
||||||
|
|
||||||
import time
|
|
||||||
import subprocess
|
|
||||||
import threading
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import tempfile
|
|
||||||
import requests
|
|
||||||
import shlex
|
|
||||||
import urllib.parse
|
|
||||||
import uuid
|
|
||||||
import base64
|
|
||||||
from flask import Flask, request, jsonify
|
|
||||||
from cryptography.hazmat.primitives.asymmetric import ec
|
|
||||||
from cryptography.hazmat.primitives import hashes
|
|
||||||
from cryptography.hazmat.primitives.serialization import load_pem_public_key
|
|
||||||
|
|
||||||
app = Flask(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
# ── Log buffer for TUI / remote monitoring ────────────────────────────────
|
|
||||||
# Captures every print() into a ring buffer so the TUI dashboard can pull
|
|
||||||
# recent log lines without SSH. /api/log returns the last 200 lines.
|
|
||||||
import sys
|
|
||||||
from collections import deque
|
|
||||||
|
|
||||||
_log_buffer = deque(maxlen=200)
|
|
||||||
|
|
||||||
class _TeeStdout:
|
|
||||||
def __init__(self, original):
|
|
||||||
self.original = original
|
|
||||||
def write(self, s):
|
|
||||||
self.original.write(s)
|
|
||||||
self.original.flush()
|
|
||||||
for line in s.splitlines():
|
|
||||||
stripped = line.rstrip()
|
|
||||||
if stripped:
|
|
||||||
_log_buffer.append(stripped)
|
|
||||||
def flush(self):
|
|
||||||
self.original.flush()
|
|
||||||
|
|
||||||
sys.stdout = _TeeStdout(sys.stdout)
|
|
||||||
|
|
||||||
|
|
||||||
def _is_valid_device_id(device_id):
|
|
||||||
"""Validate that device_id is a well-formed UUID (Flutter uuid.v4() format).
|
|
||||||
|
|
||||||
Rejects empty strings, non-UUID garbage, and oversized payloads
|
|
||||||
before they reach the session dict or Xray config.
|
|
||||||
"""
|
|
||||||
if not isinstance(device_id, str):
|
|
||||||
return False
|
|
||||||
if len(device_id) > 64:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
uuid.UUID(device_id)
|
|
||||||
return True
|
|
||||||
except (ValueError, AttributeError):
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _atomic_write_json(path, data):
|
|
||||||
"""Write JSON to path atomically (temp file + rename).
|
|
||||||
|
|
||||||
Prevents Xray from reading a half-written config file during hot-reload.
|
|
||||||
"""
|
|
||||||
tmpfd, tmppath = tempfile.mkstemp(dir=os.path.dirname(path), suffix='.tmp')
|
|
||||||
try:
|
|
||||||
with os.fdopen(tmpfd, 'w') as f:
|
|
||||||
json.dump(data, f, indent=2)
|
|
||||||
os.replace(tmppath, path)
|
|
||||||
except Exception:
|
|
||||||
try:
|
|
||||||
os.unlink(tmppath)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
raise
|
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# CONFIGURATION
|
|
||||||
# ==============================================================================
|
|
||||||
CHECK_INTERVAL_SECONDS = 60 # Checking every 1 minute is extremely safe and uses 0% CPU.
|
|
||||||
|
|
||||||
# Main Ad Rewards
|
|
||||||
MAIN_AD_MINUTES = 60
|
|
||||||
|
|
||||||
# Support Ad Rewards (top-up)
|
|
||||||
SUPPORT_AD_MINUTES = 30
|
|
||||||
|
|
||||||
# ── Reality — returned to app in /session/status ────────────────────────
|
|
||||||
REALITY_SNI = "www.microsoft.com"
|
|
||||||
VLESS_SERVER_IP = "204.168.246.88"
|
|
||||||
VLESS_REALITY_PORT = 8443
|
|
||||||
REALITY_PUBLIC_KEY = "GENERATE_ME_WITH_xray_x25519"
|
|
||||||
REALITY_SHORT_ID = "abc123"
|
|
||||||
|
|
||||||
# ── Persistent swarm total (survives restarts) ──────────────────────────
|
|
||||||
SWARM_TOTAL_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
|
||||||
"swarm_total.json")
|
|
||||||
_persistent_total_gb = 0.0
|
|
||||||
REALITY_FINGERPRINT = "chrome"
|
|
||||||
|
|
||||||
# ── Xray paths ───────────────────────────────────────────────────────────
|
|
||||||
XRAY_CONFIG = "/usr/local/etc/xray/config.json"
|
|
||||||
XRAY_API = "http://127.0.0.1:10085"
|
|
||||||
VLESS_REALITY_TAG = "vless-reality"
|
|
||||||
VLESS_REALITY_THROTTLED_TAG = "vless-reality-throttled"
|
|
||||||
|
|
||||||
THROTTLE_BYTES = 4 * 1024 * 1024 * 1024 # 4 GB
|
|
||||||
|
|
||||||
# AdMob SSV verification toggle
|
|
||||||
# True = dev mode, accept any callback (no signature check)
|
|
||||||
# False = prod mode, enforce Google ECDSA signature verification
|
|
||||||
#
|
|
||||||
# ⚠️ Set to False AFTER Google Play verifies your AdMob implementation is
|
|
||||||
# working correctly with real rewarded ads. Until then, keep True so
|
|
||||||
# the debug fake-callback path in the Flutter app still functions.
|
|
||||||
ADMOB_BYPASS = True
|
|
||||||
|
|
||||||
def _load_persistent_total():
|
|
||||||
"""Read the running total GB from disk. Returns 0.0 if file missing/corrupt."""
|
|
||||||
try:
|
|
||||||
with open(SWARM_TOTAL_FILE, 'r') as f:
|
|
||||||
data = json.load(f)
|
|
||||||
return float(data.get("total_gb", 0.0))
|
|
||||||
except Exception:
|
|
||||||
return 0.0
|
|
||||||
|
|
||||||
|
|
||||||
def _save_persistent_total():
|
|
||||||
"""Write the running total GB to disk atomically."""
|
|
||||||
_atomic_write_json(SWARM_TOTAL_FILE, {"total_gb": _persistent_total_gb})
|
|
||||||
|
|
||||||
|
|
||||||
# Load at module init — survives Hivemind restarts.
|
|
||||||
_persistent_total_gb = _load_persistent_total()
|
|
||||||
|
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# STATE & CACHE
|
|
||||||
# ==============================================================================
|
|
||||||
sessions_lock = threading.Lock()
|
|
||||||
|
|
||||||
# Consecutive Xray stats API failures — reset to 0 on first success.
|
|
||||||
# Used to rate-limit log spam when the stats endpoint is unreachable.
|
|
||||||
_xray_stats_failures = 0
|
|
||||||
|
|
||||||
active_sessions = {}
|
|
||||||
|
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# FLASK ROUTES (API surface — what the outside world sees)
|
|
||||||
# ==============================================================================
|
|
||||||
|
|
||||||
@app.route('/api/admob/callback', methods=['GET'])
|
|
||||||
def admob_callback():
|
|
||||||
"""
|
|
||||||
Google AdMob SSV callback — called server-to-server when a rewarded ad completes.
|
|
||||||
The Android client never touches this endpoint; Google calls it directly.
|
|
||||||
|
|
||||||
custom_data (JSON, set by the app before showing the ad):
|
|
||||||
{ "device_id": "...", "nonce": "..." }
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
if ADMOB_BYPASS:
|
|
||||||
# ── DEV: accept any callback without signature verification ──
|
|
||||||
custom_data_str = request.args.get('custom_data')
|
|
||||||
if not custom_data_str:
|
|
||||||
return "OK", 200
|
|
||||||
else:
|
|
||||||
# ── PROD: enforce Google ECDSA signature verification ────────
|
|
||||||
signature = request.args.get('signature')
|
|
||||||
key_id = request.args.get('key_id')
|
|
||||||
custom_data_str = request.args.get('custom_data')
|
|
||||||
|
|
||||||
# Google sends a verification ping with signature+key_id but no custom_data
|
|
||||||
if not custom_data_str:
|
|
||||||
return "OK", 200
|
|
||||||
|
|
||||||
if not all([signature, key_id]):
|
|
||||||
return "Missing parameters", 400
|
|
||||||
|
|
||||||
raw_qs = request.query_string.decode("utf-8")
|
|
||||||
if not _verify_admob_signature(raw_qs, signature, key_id):
|
|
||||||
print("[ADMOB] Rejected callback — invalid signature.")
|
|
||||||
return "Forbidden", 403
|
|
||||||
|
|
||||||
try:
|
|
||||||
custom_data = json.loads(custom_data_str)
|
|
||||||
except (json.JSONDecodeError, TypeError) as e:
|
|
||||||
print(f"[ADMOB] Malformed custom_data JSON: {e}")
|
|
||||||
return "Invalid JSON in custom_data", 400
|
|
||||||
|
|
||||||
device_id = custom_data.get('device_id')
|
|
||||||
|
|
||||||
if not device_id:
|
|
||||||
return "Invalid custom_data payload", 400
|
|
||||||
if not _is_valid_device_id(device_id):
|
|
||||||
print(f"[ADMOB] Rejected — invalid device_id: {str(device_id)[:32]}...")
|
|
||||||
return "Invalid device_id", 400
|
|
||||||
|
|
||||||
nonce = custom_data.get('nonce', None)
|
|
||||||
ad_type = custom_data.get('ad_type', 'main')
|
|
||||||
|
|
||||||
if ad_type == 'support':
|
|
||||||
success, msg = _extend_session(device_id, nonce)
|
|
||||||
else:
|
|
||||||
success, msg = _start_or_extend_session(device_id, nonce)
|
|
||||||
return ("OK", 200) if success else (msg, 500)
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[ADMOB] SSV Error: {e}")
|
|
||||||
return "Internal Error", 500
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/api/health')
|
|
||||||
def health():
|
|
||||||
return jsonify({"ok": True})
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/api/swarm')
|
|
||||||
def swarm_status():
|
|
||||||
"""Returns sorted drone list — consumed by TUI dashboards and CLI tools."""
|
|
||||||
return jsonify(get_swarm_status())
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/api/log')
|
|
||||||
def log_tail():
|
|
||||||
"""Returns recent log lines — consumed by TUI dashboards."""
|
|
||||||
return jsonify(list(_log_buffer))
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/api/session/status', methods=['GET'])
|
|
||||||
def session_status():
|
|
||||||
"""
|
|
||||||
Query: ?device_id=esf-xxx
|
|
||||||
Returns current VLESS session state so the app can connect.
|
|
||||||
"""
|
|
||||||
device_id = request.args.get('device_id')
|
|
||||||
if not device_id:
|
|
||||||
return jsonify({"error": "Missing query parameter: device_id"}), 400
|
|
||||||
if not _is_valid_device_id(device_id):
|
|
||||||
return jsonify({"error": "Invalid device_id — expected UUID"}), 400
|
|
||||||
|
|
||||||
with sessions_lock:
|
|
||||||
session = active_sessions.get(device_id)
|
|
||||||
|
|
||||||
if not session:
|
|
||||||
return jsonify({"active": False, "message": "No session found."}), 200
|
|
||||||
|
|
||||||
stats = get_xray_stats()
|
|
||||||
used_bytes = stats.get(device_id, {}).get("total_bytes", 0)
|
|
||||||
remaining_secs = max(0, session["expires_at"] - time.time())
|
|
||||||
|
|
||||||
return jsonify({
|
|
||||||
"active": remaining_secs > 0,
|
|
||||||
"vless_uuid": session["vless_uuid"],
|
|
||||||
"vless_ip": VLESS_SERVER_IP,
|
|
||||||
# NOTE: assumes throttled port = normal port + 1. If you change the
|
|
||||||
# throttled port in xray_config_reality.json, update this logic too.
|
|
||||||
"vless_port": VLESS_REALITY_PORT + 1 if session.get("throttled") else VLESS_REALITY_PORT,
|
|
||||||
"reality_pbk": REALITY_PUBLIC_KEY,
|
|
||||||
"reality_sid": REALITY_SHORT_ID,
|
|
||||||
"reality_sni": REALITY_SNI,
|
|
||||||
"reality_fp": REALITY_FINGERPRINT,
|
|
||||||
"expires_in_seconds": int(remaining_secs),
|
|
||||||
"used_bytes": used_bytes,
|
|
||||||
"nonce": session.get("nonce", ""),
|
|
||||||
"is_throttled": session.get("throttled", False),
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/api/session/stop', methods=['POST'])
|
|
||||||
def session_stop():
|
|
||||||
"""Allows the app to explicitly tear down its session on disconnect."""
|
|
||||||
data = request.get_json(silent=True)
|
|
||||||
device_id = data.get('device_id') if data else None
|
|
||||||
|
|
||||||
if not device_id:
|
|
||||||
return jsonify({"error": "Missing device_id"}), 400
|
|
||||||
if not _is_valid_device_id(device_id):
|
|
||||||
return jsonify({"error": "Invalid device_id — expected UUID"}), 400
|
|
||||||
|
|
||||||
if device_id:
|
|
||||||
with sessions_lock:
|
|
||||||
session = active_sessions.pop(device_id, None)
|
|
||||||
# Lock released — file I/O and subprocess happen outside.
|
|
||||||
if session:
|
|
||||||
# Add final bytes to persistent odometer.
|
|
||||||
stats = get_xray_stats()
|
|
||||||
used = stats.get(device_id, {}).get("total_bytes", 0)
|
|
||||||
if used > 0:
|
|
||||||
global _persistent_total_gb
|
|
||||||
_persistent_total_gb += used / 1_000_000_000
|
|
||||||
_save_persistent_total()
|
|
||||||
remove_vless_client(device_id)
|
|
||||||
print(f"[API] Explicit stop for {device_id}.")
|
|
||||||
|
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# SESSION LOGIC
|
|
||||||
# ==============================================================================
|
|
||||||
|
|
||||||
def _start_or_extend_session(device_id, nonce=None):
|
|
||||||
"""Provision a new VLESS session (or replace an existing one).
|
|
||||||
|
|
||||||
nonce -- client-generated random token; stored in session and echoed
|
|
||||||
back in /session/status so the client can reject stale sessions.
|
|
||||||
"""
|
|
||||||
now = time.time()
|
|
||||||
|
|
||||||
# ── Phase 1: update in-memory state under lock ────────────────────
|
|
||||||
xray_action = None # ("add", uuid) | ("replace", uuid)
|
|
||||||
|
|
||||||
with sessions_lock:
|
|
||||||
existing = active_sessions.get(device_id)
|
|
||||||
vless_uuid = str(uuid.uuid4())
|
|
||||||
|
|
||||||
active_sessions[device_id] = {
|
|
||||||
"vless_uuid": vless_uuid,
|
|
||||||
"expires_at": now + (MAIN_AD_MINUTES * 60),
|
|
||||||
"nonce": nonce,
|
|
||||||
"throttled": False,
|
|
||||||
"_created_at": now,
|
|
||||||
"_prev_bytes": 0,
|
|
||||||
}
|
|
||||||
|
|
||||||
if existing:
|
|
||||||
xray_action = ("replace", vless_uuid)
|
|
||||||
else:
|
|
||||||
xray_action = ("add", vless_uuid)
|
|
||||||
|
|
||||||
print(f"[SESSION] Session started for {device_id} (UUID: {vless_uuid[:8]}...).")
|
|
||||||
|
|
||||||
# ── Phase 2: Xray file I/O + subprocess OUTSIDE the lock ──────────
|
|
||||||
op, arg = xray_action[0], xray_action[1]
|
|
||||||
if op == "replace":
|
|
||||||
remove_vless_client(device_id)
|
|
||||||
add_vless_client(arg, device_id, inbound_tag=VLESS_REALITY_TAG)
|
|
||||||
return True, "Session active."
|
|
||||||
elif op == "add":
|
|
||||||
add_vless_client(arg, device_id, inbound_tag=VLESS_REALITY_TAG)
|
|
||||||
return True, "Session active."
|
|
||||||
else:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"BUG: _start_or_extend_session got unexpected xray_action op={op!r}. "
|
|
||||||
f"Expected one of: replace, add. "
|
|
||||||
f"This is a code bug — add the new op to the if-chain."
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _extend_session(device_id, nonce=None):
|
|
||||||
"""Top-up an EXISTING session — adds time without replacing the UUID.
|
|
||||||
|
|
||||||
Used by the 'Support us' rewarded ad. Does NOT touch the throttle state
|
|
||||||
or move the user between inbounds.
|
|
||||||
"""
|
|
||||||
with sessions_lock:
|
|
||||||
session = active_sessions.get(device_id)
|
|
||||||
if not session:
|
|
||||||
print(f"[SESSION] Extend failed — no active session for {device_id}.")
|
|
||||||
return False, "No active session to extend"
|
|
||||||
|
|
||||||
session["expires_at"] += SUPPORT_AD_MINUTES * 60
|
|
||||||
session["nonce"] = nonce
|
|
||||||
|
|
||||||
print(f"[SESSION] Extended for {device_id}: +{SUPPORT_AD_MINUTES} min")
|
|
||||||
|
|
||||||
return True, "Session extended"
|
|
||||||
|
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# ADMOB SERVER-TO-SERVER (SSV) VERIFICATION
|
|
||||||
# ==============================================================================
|
|
||||||
ADMOB_KEYS_URL = "https://www.gstatic.com/admob/reward/verifier-keys.json"
|
|
||||||
|
|
||||||
# Cache: { key_id_str: EllipticCurvePublicKey }
|
|
||||||
# Refreshed at most once every 24 hours so we don't hammer Google's CDN.
|
|
||||||
_admob_key_cache = {}
|
|
||||||
_admob_keys_fetched_at = 0.0
|
|
||||||
_ADMOB_KEY_TTL = 86400 # seconds
|
|
||||||
|
|
||||||
|
|
||||||
def _get_admob_public_key(key_id: str):
|
|
||||||
"""
|
|
||||||
Returns the Google ECDSA public-key object for the given key_id.
|
|
||||||
Fetches and caches the key list from gstatic; refreshes every 24h.
|
|
||||||
Returns None if the key_id is unknown.
|
|
||||||
"""
|
|
||||||
global _admob_key_cache, _admob_keys_fetched_at
|
|
||||||
|
|
||||||
now = time.time()
|
|
||||||
if now - _admob_keys_fetched_at > _ADMOB_KEY_TTL or not _admob_key_cache:
|
|
||||||
try:
|
|
||||||
resp = requests.get(ADMOB_KEYS_URL, timeout=5)
|
|
||||||
resp.raise_for_status()
|
|
||||||
data = resp.json()
|
|
||||||
|
|
||||||
new_cache = {}
|
|
||||||
for entry in data.get("keys", []):
|
|
||||||
kid = str(entry["keyId"])
|
|
||||||
pem = entry["pem"].encode()
|
|
||||||
new_cache[kid] = load_pem_public_key(pem)
|
|
||||||
|
|
||||||
_admob_key_cache = new_cache
|
|
||||||
_admob_keys_fetched_at = now
|
|
||||||
print(f"[ADMOB] Refreshed {len(new_cache)} public key(s) from Google.")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[ADMOB] WARNING: Could not refresh public keys: {e}")
|
|
||||||
# Fall through with stale cache rather than rejecting all valid callbacks
|
|
||||||
|
|
||||||
return _admob_key_cache.get(key_id)
|
|
||||||
|
|
||||||
|
|
||||||
def _verify_admob_signature(raw_query_string: str, signature_b64url: str, key_id: str) -> bool:
|
|
||||||
"""
|
|
||||||
Verifies an AdMob SSV ECDSA-SHA256 signature.
|
|
||||||
Google signs all query params EXCEPT 'signature' and 'key_id', in original order.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
public_key = _get_admob_public_key(key_id)
|
|
||||||
if not public_key:
|
|
||||||
print("[ADMOB] Unknown key_id — rejecting callback.")
|
|
||||||
return False
|
|
||||||
|
|
||||||
# Reconstruct the signed payload by stripping signature + key_id from raw qs
|
|
||||||
parsed = urllib.parse.parse_qs(raw_query_string, keep_blank_values=True)
|
|
||||||
|
|
||||||
# Google signs query params in the exact order they appear in the URL.
|
|
||||||
# Use the raw string to preserve ordering — parse_qs loses it.
|
|
||||||
ordered_pairs = []
|
|
||||||
for pair in raw_query_string.split('&'):
|
|
||||||
if '=' not in pair:
|
|
||||||
continue
|
|
||||||
k, v = pair.split('=', 1)
|
|
||||||
if k in ('signature', 'key_id'):
|
|
||||||
continue
|
|
||||||
ordered_pairs.append(f"{k}={v}")
|
|
||||||
payload = '&'.join(ordered_pairs).encode('utf-8')
|
|
||||||
|
|
||||||
# Google uses URL-safe base64 (no padding) for the signature
|
|
||||||
sig_bytes = base64.urlsafe_b64decode(signature_b64url + '==')
|
|
||||||
|
|
||||||
public_key.verify(
|
|
||||||
sig_bytes,
|
|
||||||
payload,
|
|
||||||
ec.ECDSA(hashes.SHA256())
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[ADMOB] Signature verification failed: {e}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# MANAGEMENT LOOP (The Hivemind — expiry + throttle watchdog)
|
|
||||||
# ==============================================================================
|
|
||||||
def management_loop():
|
|
||||||
global _persistent_total_gb
|
|
||||||
print(f"[HIVEMIND] Started. Tick every {CHECK_INTERVAL_SECONDS}s.")
|
|
||||||
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
stats = get_xray_stats()
|
|
||||||
now = time.time()
|
|
||||||
|
|
||||||
with sessions_lock:
|
|
||||||
to_remove = []
|
|
||||||
to_throttle_add = []
|
|
||||||
to_throttle_cleanup = []
|
|
||||||
|
|
||||||
for device_id, session in list(active_sessions.items()):
|
|
||||||
|
|
||||||
if now > session["expires_at"]:
|
|
||||||
print(f"[HIVEMIND] Session expired for {device_id}.")
|
|
||||||
to_remove.append(device_id)
|
|
||||||
continue
|
|
||||||
|
|
||||||
used_bytes = stats.get(device_id, {}).get("total_bytes", 0)
|
|
||||||
session["_prev_bytes"] = used_bytes
|
|
||||||
|
|
||||||
just_throttled = False
|
|
||||||
if used_bytes > THROTTLE_BYTES and not session.get("throttled", False):
|
|
||||||
print(f"[HIVEMIND] Throttling {device_id} ({used_bytes/1e9:.2f} GB used).")
|
|
||||||
session["throttled"] = True
|
|
||||||
just_throttled = True
|
|
||||||
to_throttle_add.append((device_id, session["vless_uuid"]))
|
|
||||||
|
|
||||||
if (session.get("throttled") and not just_throttled
|
|
||||||
and not session.get("_cleaned_normal")):
|
|
||||||
to_throttle_cleanup.append(device_id)
|
|
||||||
session["_cleaned_normal"] = True
|
|
||||||
|
|
||||||
for device_id in to_remove:
|
|
||||||
# Add final used bytes to the persistent odometer before culling.
|
|
||||||
used = stats.get(device_id, {}).get("total_bytes", 0)
|
|
||||||
if used > 0:
|
|
||||||
_persistent_total_gb += used / 1_000_000_000
|
|
||||||
_save_persistent_total()
|
|
||||||
del active_sessions[device_id]
|
|
||||||
|
|
||||||
for device_id in to_remove:
|
|
||||||
remove_vless_client(device_id)
|
|
||||||
|
|
||||||
for device_id, uuid in to_throttle_add:
|
|
||||||
add_vless_client(uuid, device_id, level=1, inbound_tag=VLESS_REALITY_THROTTLED_TAG)
|
|
||||||
|
|
||||||
for device_id in to_throttle_cleanup:
|
|
||||||
remove_vless_client_from(device_id, VLESS_REALITY_TAG)
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[HIVEMIND] Unhandled error: {e}")
|
|
||||||
|
|
||||||
time.sleep(CHECK_INTERVAL_SECONDS)
|
|
||||||
|
|
||||||
|
|
||||||
# ##############################################################################
|
|
||||||
# SWARM INTELLIGENCE (drone status — sorted data for TUI / API consumers)
|
|
||||||
# ##############################################################################
|
|
||||||
# get_swarm_status() returns a list of dicts sorted by GB used (highest first).
|
|
||||||
# Callers (CLI tools, TUI dashboards, /api/swarm endpoint) consume this.
|
|
||||||
# It snapshots active_sessions under lock and reads Xray stats — no side effects.
|
|
||||||
# ##############################################################################
|
|
||||||
|
|
||||||
def get_swarm_status():
|
|
||||||
"""Return sorted drone list + aggregate totals for external monitoring.
|
|
||||||
|
|
||||||
Returns a dict:
|
|
||||||
{
|
|
||||||
"drones": [ {...}, {...}, ... ], # sorted by gb descending
|
|
||||||
"swarm_gb": 7.3, # total GB across all drones
|
|
||||||
"active_count": 3, # sessions still alive
|
|
||||||
}
|
|
||||||
|
|
||||||
Each drone dict:
|
|
||||||
{
|
|
||||||
"id": "a1b2c3d4", # first 8 chars of device_id
|
|
||||||
"uptime_min": 23, # minutes since session created
|
|
||||||
"gb": 2.14, # data used (GB, 2 decimal places)
|
|
||||||
"throttled": false, # over quota?
|
|
||||||
"active": true, # had traffic in the last tick?
|
|
||||||
"remaining_min": 37, # minutes until expiry
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
now = time.time()
|
|
||||||
stats = get_xray_stats()
|
|
||||||
|
|
||||||
with sessions_lock:
|
|
||||||
drones = []
|
|
||||||
for device_id, session in active_sessions.items():
|
|
||||||
used_bytes = stats.get(device_id, {}).get("total_bytes", 0)
|
|
||||||
gb = round(used_bytes / 1_000_000_000, 2)
|
|
||||||
uptime_min = int((now - session.get("_created_at", session.get("expires_at", now) - MAIN_AD_MINUTES * 60)) / 60)
|
|
||||||
remaining_min = max(0, int((session["expires_at"] - now) / 60))
|
|
||||||
prev_bytes = session.get("_prev_bytes", 0)
|
|
||||||
active = used_bytes > prev_bytes
|
|
||||||
|
|
||||||
drones.append({
|
|
||||||
"id": device_id[:8],
|
|
||||||
"uptime_min": max(0, uptime_min),
|
|
||||||
"gb": gb,
|
|
||||||
"throttled": session.get("throttled", False),
|
|
||||||
"active": active,
|
|
||||||
"remaining_min": remaining_min,
|
|
||||||
})
|
|
||||||
|
|
||||||
# Sort: highest data usage first — abusers float to the top.
|
|
||||||
drones.sort(key=lambda d: d["gb"], reverse=True)
|
|
||||||
|
|
||||||
swarm_gb = round(sum(d["gb"] for d in drones), 2)
|
|
||||||
|
|
||||||
return {
|
|
||||||
"drones": drones,
|
|
||||||
"swarm_gb": swarm_gb,
|
|
||||||
"total_gb": round(_persistent_total_gb + swarm_gb, 2),
|
|
||||||
"active_count": len(drones),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# LOW-LEVEL PLUMBING (Xray client management + stats)
|
|
||||||
# ==============================================================================
|
|
||||||
|
|
||||||
def run_cmd(cmd, ignore_errors=False):
|
|
||||||
"""Executes a shell command directly on the host."""
|
|
||||||
args = shlex.split(cmd)
|
|
||||||
try:
|
|
||||||
result = subprocess.run(
|
|
||||||
args, shell=False, check=not ignore_errors,
|
|
||||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
|
|
||||||
)
|
|
||||||
return result.stdout.strip()
|
|
||||||
except FileNotFoundError:
|
|
||||||
print(f"[CMD FAIL] executable not found: {args[0]}")
|
|
||||||
return None
|
|
||||||
except subprocess.CalledProcessError as e:
|
|
||||||
if not ignore_errors:
|
|
||||||
print(f"[CMD FAIL] {cmd}\n stderr: {e.stderr.strip()}")
|
|
||||||
return None
|
|
||||||
except OSError as e:
|
|
||||||
print(f"[CMD FAIL] {cmd}\n os error: {e}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def add_vless_client(uuid, email, level=0, inbound_tag=VLESS_REALITY_TAG):
|
|
||||||
"""Add a client UUID to the Xray inbound config and hot-reload.
|
|
||||||
|
|
||||||
level -- Xray policy level for bandwidth limits: 0 = default.
|
|
||||||
inbound_tag -- which inbound to add the client to (default: VLESS_REALITY_TAG).
|
|
||||||
"""
|
|
||||||
with open(XRAY_CONFIG, 'r') as f:
|
|
||||||
config = json.load(f)
|
|
||||||
|
|
||||||
for inbound in config["inbounds"]:
|
|
||||||
if inbound.get("tag") == inbound_tag:
|
|
||||||
inbound["settings"]["clients"].append({
|
|
||||||
"id": uuid,
|
|
||||||
"email": email,
|
|
||||||
"level": level
|
|
||||||
})
|
|
||||||
break
|
|
||||||
|
|
||||||
_atomic_write_json(XRAY_CONFIG, config)
|
|
||||||
run_cmd("xray api adi --server=127.0.0.1:10085")
|
|
||||||
print(f"[VLESS] User added to {inbound_tag}: {email[:16]}...")
|
|
||||||
|
|
||||||
|
|
||||||
def remove_vless_client(email):
|
|
||||||
"""Remove a client from ALL VLESS inbounds and hot-reload."""
|
|
||||||
with open(XRAY_CONFIG, 'r') as f:
|
|
||||||
config = json.load(f)
|
|
||||||
|
|
||||||
for inbound in config["inbounds"]:
|
|
||||||
if inbound.get("tag") in (VLESS_REALITY_TAG, VLESS_REALITY_THROTTLED_TAG):
|
|
||||||
clients = inbound["settings"]["clients"]
|
|
||||||
inbound["settings"]["clients"] = [
|
|
||||||
c for c in clients if c.get("email") != email
|
|
||||||
]
|
|
||||||
|
|
||||||
_atomic_write_json(XRAY_CONFIG, config)
|
|
||||||
run_cmd("xray api adi --server=127.0.0.1:10085")
|
|
||||||
print(f"[VLESS] User removed: {email[:16]}...")
|
|
||||||
|
|
||||||
|
|
||||||
def remove_vless_client_from(email, inbound_tag):
|
|
||||||
"""Remove a client from one specific inbound and hot-reload."""
|
|
||||||
with open(XRAY_CONFIG, 'r') as f:
|
|
||||||
config = json.load(f)
|
|
||||||
|
|
||||||
for inbound in config["inbounds"]:
|
|
||||||
if inbound.get("tag") == inbound_tag:
|
|
||||||
clients = inbound["settings"]["clients"]
|
|
||||||
inbound["settings"]["clients"] = [
|
|
||||||
c for c in clients if c.get("email") != email
|
|
||||||
]
|
|
||||||
break
|
|
||||||
|
|
||||||
_atomic_write_json(XRAY_CONFIG, config)
|
|
||||||
run_cmd("xray api adi --server=127.0.0.1:10085")
|
|
||||||
print(f"[VLESS] User removed from {inbound_tag}: {email[:16]}...")
|
|
||||||
|
|
||||||
|
|
||||||
def get_xray_stats():
|
|
||||||
"""Query Xray stats API for per-user upload+download bytes.
|
|
||||||
|
|
||||||
Returns: { "device_id": {"total_bytes": 12345}, ... }
|
|
||||||
"""
|
|
||||||
global _xray_stats_failures
|
|
||||||
|
|
||||||
try:
|
|
||||||
resp = requests.get(
|
|
||||||
f"{XRAY_API}/stats/query",
|
|
||||||
json={"pattern": "", "reset": False},
|
|
||||||
timeout=5
|
|
||||||
)
|
|
||||||
data = resp.json()
|
|
||||||
except Exception as e:
|
|
||||||
# Rate-limit log spam: warn on first failure, then every 10th.
|
|
||||||
_xray_stats_failures += 1
|
|
||||||
if _xray_stats_failures == 1:
|
|
||||||
print(f"[XRAY_STATS] WARNING: Cannot reach Xray stats API: {e}")
|
|
||||||
elif _xray_stats_failures % 10 == 0:
|
|
||||||
print(f"[XRAY_STATS] ERROR: {_xray_stats_failures} consecutive failures. "
|
|
||||||
f"Quota enforcement is NOT running. Last error: {e}")
|
|
||||||
return {}
|
|
||||||
|
|
||||||
# Success — reset the failure counter.
|
|
||||||
if _xray_stats_failures > 0:
|
|
||||||
print(f"[XRAY_STATS] Recovered after {_xray_stats_failures} failure(s).")
|
|
||||||
_xray_stats_failures = 0
|
|
||||||
|
|
||||||
stats = {}
|
|
||||||
for entry in data.get("stat", []):
|
|
||||||
name = entry.get("name", "")
|
|
||||||
value = int(entry.get("value", 0))
|
|
||||||
|
|
||||||
# Xray stats names look like: "user>>>email>>>traffic>>>uplink"
|
|
||||||
if ">>>traffic>>>" in name:
|
|
||||||
parts = name.split(">>>")
|
|
||||||
email = parts[1] if len(parts) > 1 else None
|
|
||||||
if email and email != "api":
|
|
||||||
if email not in stats:
|
|
||||||
stats[email] = {"total_bytes": 0}
|
|
||||||
stats[email]["total_bytes"] += value
|
|
||||||
|
|
||||||
return stats
|
|
||||||
|
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# ENTRY POINT
|
|
||||||
# ==============================================================================
|
|
||||||
# Start management daemon at module load (gunicorn-safe, runs once per process)
|
|
||||||
_daemon_thread = threading.Thread(target=management_loop, daemon=True)
|
|
||||||
_daemon_thread.start()
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
# When running directly with Flask, the before_request hook handles it
|
|
||||||
app.run(host='0.0.0.0', port=5000)
|
|
||||||