V0.2.0 (#37)
* refactor go files, add headless telemost support * js crap -> ts crap * docker-build (#32) Co-authored-by: Mimocro <suzumagefag@gmail.com> * add headless telemost for creator app * UX improvements (#39) * Add search in split tunneling app list * Add captcha detection * Add autoclick settings * headless vk joiner * add headless telemost joiner * refactor go modules * redesign settings dialog * headless option in settings * headless joiner support in MainActivity * display headless vk status in statusBar * update ux for headless in creator app * fix double log render for headless mode in creator * unicode for cyrillic * add socks auth * put socksPort inf prefs, verify that port is free on start * proxy only mode * mask addresses in go network errors * update docker build, add file write logic for headless * increment release version, add make-release script --------- Co-authored-by: kulikov <user@Mac.lan> Co-authored-by: Mimocro <67226986+Mimocro@users.noreply.github.com> Co-authored-by: Mimocro <suzumagefag@gmail.com> Co-authored-by: senya <76913432+senya-sh@users.noreply.github.com>
This commit is contained in:
122 files changed
+9921
-3267
No files matched your search
+2
-3
@@ -2,7 +2,6 @@
|
|||||||
relay/mobile.aar
|
relay/mobile.aar
|
||||||
relay/relay-*
|
relay/relay-*
|
||||||
prebuilts/
|
prebuilts/
|
||||||
cookies.json
|
cookies*.json
|
||||||
pion-light/
|
|
||||||
headless/headless-creator
|
|
||||||
relay/relay
|
relay/relay
|
||||||
|
whitelist-experiments/
|
||||||
@@ -10,7 +10,7 @@ Two tunnel modes are available: **DC** (DataChannel) and **Pion Video** (VP8 dat
|
|||||||
|
|
||||||
Browser-based. JavaScript hooks intercept RTCPeerConnection on the call page, create a DataChannel alongside the call's built-in channels, and use it as a bidirectional data pipe.
|
Browser-based. JavaScript hooks intercept RTCPeerConnection on the call page, create a DataChannel alongside the call's built-in channels, and use it as a bidirectional data pipe.
|
||||||
|
|
||||||
- **VK Call** - Negotiated DataChannel id:2 (alongside VK's animoji channel id:1). P2P via TURN relay
|
- **VK Call** - Negotiated DataChannel id:2 (alongside VK's animoji channel id:1). Data flows through VK's SFU
|
||||||
- **Telemost** - Non-negotiated DataChannel labeled "sharing" (matching real screen sharing traffic), with SDP renegotiation via signaling WebSocket. SFU architecture
|
- **Telemost** - Non-negotiated DataChannel labeled "sharing" (matching real screen sharing traffic), with SDP renegotiation via signaling WebSocket. SFU architecture
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -28,7 +28,7 @@ WebSocket (:9000)
|
|||||||
|
|
|
|
||||||
WebView (call page) Electron (call page)
|
WebView (call page) Electron (call page)
|
||||||
| |
|
| |
|
||||||
DataChannel <--- TURN/SFU ---> DataChannel
|
DataChannel <----- SFU -----> DataChannel
|
||||||
|
|
|
|
||||||
WebSocket (:9000)
|
WebSocket (:9000)
|
||||||
|
|
|
|
||||||
@@ -41,7 +41,7 @@ DataChannel <--- TURN/SFU ---> DataChannel
|
|||||||
|
|
||||||
Go-based. Pion (Go WebRTC library) connects directly to the platform's TURN/SFU servers, bypassing the browser's WebRTC stack entirely. Data is encoded inside VP8 video frames.
|
Go-based. Pion (Go WebRTC library) connects directly to the platform's TURN/SFU servers, bypassing the browser's WebRTC stack entirely. Data is encoded inside VP8 video frames.
|
||||||
|
|
||||||
- **VK Call** - Single PeerConnection, P2P via TURN relay
|
- **VK Call** - Single PeerConnection, data flows through VK's SFU
|
||||||
- **Telemost** - Dual PeerConnection (pub/sub), SFU architecture
|
- **Telemost** - Dual PeerConnection (pub/sub), SFU architecture
|
||||||
|
|
||||||
The JS hook replaces `RTCPeerConnection` with a `MockPeerConnection` that forwards all SDP/ICE operations to the local Pion server via WebSocket. Pion creates the real PeerConnection with the platform's TURN servers.
|
The JS hook replaces `RTCPeerConnection` with a `MockPeerConnection` that forwards all SDP/ICE operations to the local Pion server via WebSocket. Pion creates the real PeerConnection with the platform's TURN servers.
|
||||||
@@ -71,46 +71,23 @@ VP8 data tunnel (Pion) VP8 data tunnel (Pion)
|
|||||||
| |
|
| |
|
||||||
MockPC (WebView) MockPC (Electron)
|
MockPC (WebView) MockPC (Electron)
|
||||||
| |
|
| |
|
||||||
Pion WebRTC <--- TURN/SFU ---> Pion WebRTC
|
Pion WebRTC <------ SFU ------> Pion WebRTC
|
||||||
|
|
|
|
||||||
Relay bridge
|
Relay bridge
|
||||||
|
|
|
|
||||||
Internet
|
Internet
|
||||||
```
|
```
|
||||||
|
|
||||||
Traffic goes through the platform's TURN servers which are whitelisted. To the network firewall it looks like a normal video call.
|
Traffic goes through the platform's SFU servers which are whitelisted. To the network firewall it looks like a normal video call.
|
||||||
|
|
||||||
## Components
|
## Components
|
||||||
|
|
||||||
- `hooks/` - JavaScript hooks injected into call pages
|
- `hooks/` - JavaScript hooks for DC, Video, and Headless modes (VK and Telemost)
|
||||||
- `joiner-vk.js`, `creator-vk.js` - VK Call DC hooks
|
- `relay/` - Go relay: SOCKS5 proxy, WebSocket server, VP8 video tunnel, headless joiner, connection multiplexing
|
||||||
- `joiner-telemost.js`, `creator-telemost.js` - Telemost DC hooks
|
- `headless/vk/` - Headless VK creator: creates calls via API, Pion DataChannel tunnel, no browser
|
||||||
- `pion-vk.js`, `pion-telemost.js` - Pion Video hooks (MockPeerConnection mode)
|
- `headless/telemost/` - Headless Telemost creator: same approach for Yandex Telemost
|
||||||
- DC hooks intercept RTCPeerConnection, create tunnel DataChannel, bridge to local WebSocket
|
- `android-app/` - Android joiner app (WebView/headless + VpnService + Go relay)
|
||||||
- Pion hooks replace RTCPeerConnection with MockPC, forward SDP/ICE to Pion via WebSocket
|
|
||||||
- Telemost hooks include fake media (camera/mic), message chunking (994B payload, 1000B total), and SDP renegotiation
|
|
||||||
- `relay/` - Go relay binary and gomobile library
|
|
||||||
- `relay/mobile/` - DC mode: SOCKS5 proxy, WebSocket server, binary framing protocol
|
|
||||||
- `relay/pion/` - Pion Video mode: VP8 data tunnel, relay bridge, SOCKS5 proxy
|
|
||||||
- `common.go` - Shared types, WebSocket helper, ICE server parsing, AndroidNet
|
|
||||||
- `vk.go` - VK Pion client (single PeerConnection, P2P)
|
|
||||||
- `telemost.go` - Telemost Pion client (dual PeerConnection, pub/sub)
|
|
||||||
- `vp8tunnel.go` - VP8 frame encoding/decoding, keepalive generation
|
|
||||||
- `relay.go` - Relay bridge with connection multiplexing, SOCKS5 proxy, UDP ASSOCIATE
|
|
||||||
- `relay/mobile/tun_android.go` - Android-only: tun2socks + fdsan fix (CGo)
|
|
||||||
- `relay/mobile/tun_stub.go` - Desktop stub (no tun2socks needed)
|
|
||||||
- `android-app/` - Android joiner app
|
|
||||||
- WebView loading call page with hook injection
|
|
||||||
- VpnService capturing all device traffic
|
|
||||||
- Tunnel mode selector (DC / Pion Video)
|
|
||||||
- Go relay as .aar library (gomobile) + Pion relay as native binary
|
|
||||||
- `creator-app/` - Electron desktop creator app
|
- `creator-app/` - Electron desktop creator app
|
||||||
- Webview with persistent session for login retention
|
|
||||||
- CSP header stripping for localhost WebSocket access
|
|
||||||
- Auto-permission granting (camera/mic)
|
|
||||||
- Tunnel mode selector (DC / Pion Video)
|
|
||||||
- Go relay spawned as child process
|
|
||||||
- Log panels for relay and hook output
|
|
||||||
|
|
||||||
## Download
|
## Download
|
||||||
|
|
||||||
@@ -144,7 +121,7 @@ Download and run the Electron app from [GitHub Releases](../../releases). It bun
|
|||||||
|
|
||||||
### Requirements
|
### Requirements
|
||||||
|
|
||||||
- Go 1.21+
|
- Go 1.26+
|
||||||
- gomobile (`go install golang.org/x/mobile/cmd/gomobile@latest`)
|
- gomobile (`go install golang.org/x/mobile/cmd/gomobile@latest`)
|
||||||
- gobind (`go install golang.org/x/mobile/cmd/gobind@latest`)
|
- gobind (`go install golang.org/x/mobile/cmd/gobind@latest`)
|
||||||
- Android SDK + NDK 29
|
- Android SDK + NDK 29
|
||||||
@@ -174,6 +151,16 @@ Output in `prebuilts/`:
|
|||||||
| `WhitelistBypass Creator-*.AppImage` | Linux x64 |
|
| `WhitelistBypass Creator-*.AppImage` | Linux x64 |
|
||||||
| `whitelist-bypass.apk` | Android |
|
| `whitelist-bypass.apk` | Android |
|
||||||
|
|
||||||
|
### Docker build
|
||||||
|
|
||||||
|
To build the project using Docker, execute:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose -f docker-build/docker-compose.yml up
|
||||||
|
```
|
||||||
|
|
||||||
|
This will build all components (creator-app, headless, android app) into the `prebuild` folder (except the macOS creator)
|
||||||
|
|
||||||
### Relay
|
### Relay
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -191,21 +178,24 @@ The Go relay is split into platform-specific files:
|
|||||||
|
|
||||||
This allows cross-compiling the relay for macOS/Windows/Linux without CGo or Android NDK.
|
This allows cross-compiling the relay for macOS/Windows/Linux without CGo or Android NDK.
|
||||||
|
|
||||||
### Headless creator
|
### Headless creators
|
||||||
|
|
||||||
Pure Go creator that creates VK calls via API without a browser. No Electron, no JS hooks - Go Pion PeerConnection handles the DataChannel tunnel directly.
|
Pure Go creators that create calls via API without a browser. No Electron, no JS hooks - Go Pion PeerConnection handles the DataChannel tunnel directly.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# Build
|
# VK
|
||||||
cd headless && go build -o headless-creator .
|
cd headless/vk && go build -o headless-vk-creator .
|
||||||
|
./headless-vk-creator --cookies cookies.json [--peer-id <vk_peer_id>] [--resources <mode>] [--write-file call-vk]
|
||||||
|
|
||||||
# Run
|
# Telemost
|
||||||
./headless-creator --cookies cookies.json [--peer-id <vk_peer_id>] [--resources <mode>]
|
cd headless/telemost && go build -o headless-telemost .
|
||||||
|
./headless-telemost --cookies cookies-yandex.json [--resources <mode>] [--write-file call-telemost]
|
||||||
```
|
```
|
||||||
|
|
||||||
- `--cookies` - path to VK cookies exported as JSON (`[{"name":"..","value":".."},...]`). Use the "Export Cookies" button in the Creator app to get this file
|
- `--cookies` - path to cookies exported as JSON (`[{"name":"..","value":".."},...]`)
|
||||||
- `--peer-id` - VK peer_id for the call (optional)
|
- `--peer-id` - VK peer_id for the call (VK only, optional)
|
||||||
- `--resources` - resource mode (see below)
|
- `--resources` - resource mode (see below)
|
||||||
|
- `--write-file` - path to file where the active call link is appended (one link per line, created if missing)
|
||||||
|
|
||||||
**Resource modes:**
|
**Resource modes:**
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
val versionMajor = 0
|
val versionMajor = 0
|
||||||
val versionMinor = 1
|
val versionMinor = 2
|
||||||
val versionPatch = 9
|
val versionPatch = 0
|
||||||
val versionBuild = System.getenv("BUILD_NUMBER")?.toIntOrNull() ?: 0
|
val versionBuild = System.getenv("BUILD_NUMBER")?.toIntOrNull() ?: 0
|
||||||
|
|
||||||
android {
|
android {
|
||||||
|
|||||||
Binary file not shown.
@@ -38,6 +38,10 @@
|
|||||||
<action android:name="android.net.VpnService" />
|
<action android:name="android.net.VpnService" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</service>
|
</service>
|
||||||
|
<service
|
||||||
|
android:name=".tunnel.ProxyService"
|
||||||
|
android:foregroundServiceType="specialUse"
|
||||||
|
android:exported="false" />
|
||||||
<provider
|
<provider
|
||||||
android:name="androidx.core.content.FileProvider"
|
android:name="androidx.core.content.FileProvider"
|
||||||
android:authorities="${applicationId}.fileprovider"
|
android:authorities="${applicationId}.fileprovider"
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
(function() {
|
(function() {
|
||||||
if (window.__autoclickInstalled) return;
|
if (window.__autoclickInstalled) return;
|
||||||
window.__autoclickInstalled = true;
|
window.__autoclickInstalled = true;
|
||||||
|
var wasCaptchaDetected = false;
|
||||||
|
|
||||||
var log = function() {
|
var log = function() {
|
||||||
var args = ['[HOOK] [autoclick]'];
|
var args = ['[HOOK] [autoclick]'];
|
||||||
@@ -24,7 +25,7 @@
|
|||||||
if (inp && !inp.value) {
|
if (inp && !inp.value) {
|
||||||
log('Filling name');
|
log('Filling name');
|
||||||
var set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
|
var set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
|
||||||
set.call(inp, 'Hello');
|
set.call(inp, window.autofillName);
|
||||||
inp.dispatchEvent(new Event('input', { bubbles: true }));
|
inp.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
inp.dispatchEvent(new Event('change', { bubbles: true }));
|
inp.dispatchEvent(new Event('change', { bubbles: true }));
|
||||||
return;
|
return;
|
||||||
@@ -40,5 +41,27 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function scanForCaptcha() {
|
||||||
|
var iframes = document.querySelectorAll("iframe");
|
||||||
|
for (var i = 0; i < iframes.length; i++) {
|
||||||
|
if (iframes[i].src.startsWith("https://id.vk.com/not_robot_captcha")) {
|
||||||
|
if(!wasCaptchaDetected) {
|
||||||
|
log('Captcha detected, user action required');
|
||||||
|
AndroidBridge.onCaptchaDetected(false);
|
||||||
|
wasCaptchaDetected = true;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(wasCaptchaDetected) { // assuming captcha iframe wasn't found
|
||||||
|
log('Captcha closed or solved');
|
||||||
|
AndroidBridge.onCaptchaDetected(true);
|
||||||
|
wasCaptchaDetected = false;
|
||||||
|
clearInterval(captcha_iv);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var iv = setInterval(scan, 1500);
|
var iv = setInterval(scan, 1500);
|
||||||
|
var captcha_iv = setInterval(scanForCaptcha, 1500);
|
||||||
})();
|
})();
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
(() => {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
var JOIN_LINK = window.JOIN_LINK || '';
|
||||||
|
var ANON_NAME = window.ANON_NAME || 'Guest';
|
||||||
|
|
||||||
|
function log(msg) { console.log('[AUTH] ' + msg); }
|
||||||
|
function setStatus(msg) {
|
||||||
|
if (typeof AndroidCaptchaBridge !== 'undefined' && AndroidCaptchaBridge.setStatus) {
|
||||||
|
AndroidCaptchaBridge.setStatus(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getText(url) {
|
||||||
|
try {
|
||||||
|
var response = await fetch(url, {
|
||||||
|
headers: { 'User-Agent': navigator.userAgent }
|
||||||
|
});
|
||||||
|
if (response.status !== 200) log('GET ' + url.substring(0, 60) + ' status=' + response.status);
|
||||||
|
return response.text();
|
||||||
|
} catch(error) {
|
||||||
|
log('GET ' + url.substring(0, 60) + ' failed: ' + error);
|
||||||
|
setStatus('Network error: ' + error.message);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postAPI(url, body, headers) {
|
||||||
|
try {
|
||||||
|
var response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: Object.assign({'Content-Type': 'application/x-www-form-urlencoded'}, headers || {}),
|
||||||
|
body: new URLSearchParams(body).toString()
|
||||||
|
});
|
||||||
|
return response.json();
|
||||||
|
} catch(error) {
|
||||||
|
log('fetch error for ' + url.substring(0, 80) + ': ' + error);
|
||||||
|
return { error: { error_code: -1, error_msg: error.toString() } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var config = {};
|
||||||
|
var savedAuth = null;
|
||||||
|
var savedCaptchaSid = null;
|
||||||
|
|
||||||
|
async function fetchConfig() {
|
||||||
|
setStatus('Fetching config...');
|
||||||
|
var page = await getText('https://vk.com');
|
||||||
|
var bundleMatch = page.match(/https:\/\/[a-z0-9.-]+\/dist\/core_spa\/core_spa_vk\.[a-f0-9]+\.js/);
|
||||||
|
if (!bundleMatch) { log('Bundle URL not found'); return false; }
|
||||||
|
var bundleURL = bundleMatch[0];
|
||||||
|
var chunksBase = bundleURL.substring(0, bundleURL.lastIndexOf('core_spa_vk.')) + 'chunks/';
|
||||||
|
log('Bundle: ' + bundleURL.split('/').pop());
|
||||||
|
|
||||||
|
var bundle = await getText(bundleURL);
|
||||||
|
|
||||||
|
var appIdMatch = bundle.match(/[,;]u=(\d{7,8}),_=\d{7,8},p=\d{8,9}/);
|
||||||
|
var apiMatch = bundle.match(/\d+:\(e,t,n\)=>\{"use strict";n\.d\(t,\{m:\(\)=>r\}\);const r="(5\.\d+)"\}/);
|
||||||
|
if (!appIdMatch || !apiMatch) { log('appId or API version not found'); return false; }
|
||||||
|
config.appId = appIdMatch[1];
|
||||||
|
config.apiVersion = apiMatch[1];
|
||||||
|
log('appId=' + config.appId + ' api=' + config.apiVersion);
|
||||||
|
|
||||||
|
var bridgeMatch = bundle.match(/core_spa\/chunks\/webCallsBridge\.([a-f0-9]+)\.js/);
|
||||||
|
if (!bridgeMatch) { log('webCallsBridge not found'); return false; }
|
||||||
|
var bridgeURL = chunksBase + 'webCallsBridge.' + bridgeMatch[1] + '.js';
|
||||||
|
var bridgeText = await getText(bridgeURL);
|
||||||
|
|
||||||
|
var moduleIds = [];
|
||||||
|
var seen = {};
|
||||||
|
var modMatches = bridgeText.match(/i\((\d{4,6})\)/g) || [];
|
||||||
|
modMatches.forEach(function(match) {
|
||||||
|
var id = match.match(/\d+/)[0];
|
||||||
|
if (!seen[id]) { seen[id] = true; moduleIds.push(id); }
|
||||||
|
});
|
||||||
|
|
||||||
|
var chunkMap = {};
|
||||||
|
var chunkRegex = /(\d+)===e\)return"core_spa\/chunks\/"\+e\+"\.([a-f0-9]+)\.js"/g;
|
||||||
|
var chunkMatch;
|
||||||
|
while ((chunkMatch = chunkRegex.exec(bundle)) !== null) {
|
||||||
|
chunkMap[chunkMatch[1]] = chunkMatch[2];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var idx = 0; idx < moduleIds.length; idx++) {
|
||||||
|
var modId = moduleIds[idx];
|
||||||
|
var hash = chunkMap[modId] || chunkMap[modId.substring(1)];
|
||||||
|
if (!hash) continue;
|
||||||
|
var chunkId = chunkMap[modId] ? modId : modId.substring(1);
|
||||||
|
var chunkURL = chunksBase + chunkId + '.' + hash + '.js';
|
||||||
|
var chunkText = await getText(chunkURL);
|
||||||
|
|
||||||
|
var appVersionMatch = chunkText.match(/appVersion.{0,40}return\s+([0-9.]+)/);
|
||||||
|
if (appVersionMatch) {
|
||||||
|
config.appVersion = appVersionMatch[1];
|
||||||
|
var protoMatch = chunkText.match(/protocolVersion.{0,40}return.*?(\d+)/);
|
||||||
|
if (protoMatch) config.protocolVersion = protoMatch[1];
|
||||||
|
log('appVersion=' + config.appVersion + ' protocolVersion=' + config.protocolVersion);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.retryCaptcha = async function(successToken) {
|
||||||
|
setStatus('Captcha solved, retrying...');
|
||||||
|
document.getElementById('captcha').style.display = 'none';
|
||||||
|
var params = {
|
||||||
|
v: config.apiVersion,
|
||||||
|
vk_join_link: JOIN_LINK,
|
||||||
|
name: ANON_NAME,
|
||||||
|
};
|
||||||
|
if (savedCaptchaSid) {
|
||||||
|
params.captcha_sid = savedCaptchaSid;
|
||||||
|
params.captcha_key = '';
|
||||||
|
params.success_token = successToken;
|
||||||
|
}
|
||||||
|
var result = await postAPI('https://api.vk.com/method/calls.getAnonymousToken', params, savedAuth);
|
||||||
|
log('Retry response: ' + JSON.stringify(result));
|
||||||
|
if (result.error && result.error.error_code === 14) {
|
||||||
|
showCaptcha(result.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (result.response) {
|
||||||
|
onAuthComplete(result.response);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function showCaptcha(error) {
|
||||||
|
savedCaptchaSid = error.captcha_sid || '';
|
||||||
|
var captchaURL = error.redirect_uri;
|
||||||
|
log('Captcha required, showing iframe');
|
||||||
|
setStatus('Solve the captcha:');
|
||||||
|
var iframe = document.getElementById('captcha');
|
||||||
|
iframe.style.display = 'block';
|
||||||
|
iframe.src = captchaURL;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onAuthComplete(response) {
|
||||||
|
var callToken = response.token;
|
||||||
|
var apiBaseURL = response.api_base_url;
|
||||||
|
var okJoinLink = response.ok_join_link;
|
||||||
|
setStatus('Authenticating with OK.ru...');
|
||||||
|
|
||||||
|
var baseURL = apiBaseURL.replace(/\/$/, '');
|
||||||
|
if (baseURL.indexOf('/fb.do') === -1) baseURL += '/fb.do';
|
||||||
|
var deviceId = String(Math.floor(Math.random() * 9e18));
|
||||||
|
|
||||||
|
var sessionData = {
|
||||||
|
version: 2,
|
||||||
|
device_id: deviceId,
|
||||||
|
client_version: config.appVersion,
|
||||||
|
client_type: 'SDK_JS',
|
||||||
|
};
|
||||||
|
|
||||||
|
var okLogin = await postAPI(baseURL, {
|
||||||
|
method: 'auth.anonymLogin',
|
||||||
|
session_data: JSON.stringify(sessionData),
|
||||||
|
application_key: config.publicKey,
|
||||||
|
format: 'json',
|
||||||
|
});
|
||||||
|
log('anonymLogin: ' + JSON.stringify(okLogin));
|
||||||
|
if (!okLogin.session_key) {
|
||||||
|
setStatus('anonymLogin failed: ' + JSON.stringify(okLogin));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setStatus('Auth complete, handing off to relay...');
|
||||||
|
var authResult = {
|
||||||
|
sessionKey: okLogin.session_key,
|
||||||
|
applicationKey: config.publicKey,
|
||||||
|
apiBaseURL: baseURL,
|
||||||
|
joinLink: okJoinLink || config.okJoinLink || JOIN_LINK,
|
||||||
|
anonymToken: callToken,
|
||||||
|
appVersion: config.appVersion,
|
||||||
|
protocolVersion: config.protocolVersion,
|
||||||
|
};
|
||||||
|
log('Passing auth to relay');
|
||||||
|
if (typeof AndroidCaptchaBridge !== 'undefined') {
|
||||||
|
AndroidCaptchaBridge.onJoined(JSON.stringify(authResult));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startAuth() {
|
||||||
|
if (!(await fetchConfig())) {
|
||||||
|
setStatus('Config extraction failed');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setStatus('Getting anonymous token...');
|
||||||
|
var anonResult = await postAPI('https://login.vk.com/?act=get_anonym_token', {
|
||||||
|
client_id: config.appId,
|
||||||
|
});
|
||||||
|
var anonToken = anonResult.data && anonResult.data.access_token;
|
||||||
|
if (!anonToken) {
|
||||||
|
setStatus('Failed to get anon token');
|
||||||
|
log('get_anonym_token failed: ' + JSON.stringify(anonResult));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log('anon token OK');
|
||||||
|
savedAuth = { Authorization: 'Bearer ' + anonToken };
|
||||||
|
|
||||||
|
setStatus('Getting call settings...');
|
||||||
|
var settings = await postAPI('https://api.vk.com/method/calls.getSettings', {
|
||||||
|
v: config.apiVersion,
|
||||||
|
}, savedAuth);
|
||||||
|
config.publicKey = settings.response && settings.response.settings && settings.response.settings.public_key;
|
||||||
|
log('publicKey: ' + config.publicKey);
|
||||||
|
|
||||||
|
setStatus('Getting call preview...');
|
||||||
|
var preview = await postAPI('https://api.vk.com/method/calls.getCallPreview', {
|
||||||
|
v: config.apiVersion,
|
||||||
|
vk_join_link: JOIN_LINK,
|
||||||
|
}, savedAuth);
|
||||||
|
var okJoinLink = preview.response && preview.response.ok_join_link;
|
||||||
|
if (okJoinLink) {
|
||||||
|
config.okJoinLink = okJoinLink;
|
||||||
|
log('okJoinLink: ' + okJoinLink);
|
||||||
|
}
|
||||||
|
|
||||||
|
setStatus('Getting call token...');
|
||||||
|
var callResult = await postAPI('https://api.vk.com/method/calls.getAnonymousToken', {
|
||||||
|
v: config.apiVersion,
|
||||||
|
vk_join_link: JOIN_LINK,
|
||||||
|
name: ANON_NAME,
|
||||||
|
}, savedAuth);
|
||||||
|
log('getAnonymousToken: ' + JSON.stringify(callResult));
|
||||||
|
|
||||||
|
if (callResult.error && callResult.error.error_code === 14) {
|
||||||
|
showCaptcha(callResult.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (callResult.response) {
|
||||||
|
onAuthComplete(callResult.response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
startAuth().catch(function(error) {
|
||||||
|
log('startAuth error: ' + error);
|
||||||
|
setStatus('Error: ' + error.message);
|
||||||
|
});
|
||||||
|
})();
|
||||||
@@ -0,0 +1,500 @@
|
|||||||
|
Мальцев Фёдор
|
||||||
|
Кудрявцев Алексей
|
||||||
|
Тихомиров Михаил
|
||||||
|
Козлова Варвара
|
||||||
|
Григорьев Артемий
|
||||||
|
Дегтярева София
|
||||||
|
Климов Олег
|
||||||
|
Гришина София
|
||||||
|
Михайлов Алексей
|
||||||
|
Полякова Анна
|
||||||
|
Губанов Степан
|
||||||
|
Петрова Анастасия
|
||||||
|
Наумов Сергей
|
||||||
|
Кузнецова Ариана
|
||||||
|
Федотов Лука
|
||||||
|
Софронова Евгения
|
||||||
|
Лебедева Дарья
|
||||||
|
Кузьмина Евгения
|
||||||
|
Зайцева Елизавета
|
||||||
|
Митрофанова Малика
|
||||||
|
Шапошников Максим
|
||||||
|
Ермаков Алексей
|
||||||
|
Муравьев Григорий
|
||||||
|
Сидорова Полина
|
||||||
|
Дорофеев Ярослав
|
||||||
|
Сорокин Даниил
|
||||||
|
Гуляев Платон
|
||||||
|
Ларина Мария
|
||||||
|
Гончарова Милана
|
||||||
|
Львова Анастасия
|
||||||
|
Долгов Руслан
|
||||||
|
Соловьев Алексей
|
||||||
|
Морозов Андрей
|
||||||
|
Макарова Софья
|
||||||
|
Грачев Андрей
|
||||||
|
Комарова Милана
|
||||||
|
Соколов Матвей
|
||||||
|
Костина Мария
|
||||||
|
Калугин Никита
|
||||||
|
Воробьев Николай
|
||||||
|
Нечаев Лев
|
||||||
|
Ермакова Василиса
|
||||||
|
Соколов Григорий
|
||||||
|
Соколов Артём
|
||||||
|
Новиков Дмитрий
|
||||||
|
Матвеев Данила
|
||||||
|
Иванова Мария
|
||||||
|
Старикова Арина
|
||||||
|
Ефимова Виктория
|
||||||
|
Козин Иван
|
||||||
|
Смирнов Артём
|
||||||
|
Виноградов Марк
|
||||||
|
Серова Евгения
|
||||||
|
Касаткина Дарья
|
||||||
|
Смирнова Екатерина
|
||||||
|
Попова Ясмина
|
||||||
|
Баранова Вера
|
||||||
|
Шубин Даниил
|
||||||
|
Туманова Виктория
|
||||||
|
Иванов Данил
|
||||||
|
Павлов Дмитрий
|
||||||
|
Смирнов Святослав
|
||||||
|
Михеева Алёна
|
||||||
|
Иванова Виктория
|
||||||
|
Ильина Алиса
|
||||||
|
Морозов Иван
|
||||||
|
Гаврилова Ариана
|
||||||
|
Борисов Игорь
|
||||||
|
Николаева Ксения
|
||||||
|
Фомин Артемий
|
||||||
|
Абрамова Анастасия
|
||||||
|
Осипов Артур
|
||||||
|
Кузнецова Аделина
|
||||||
|
Спиридонов Кирилл
|
||||||
|
Нечаева Екатерина
|
||||||
|
Белова Анастасия
|
||||||
|
Романова Василиса
|
||||||
|
Русаков Максим
|
||||||
|
Ежова Светлана
|
||||||
|
Макарова Ярослава
|
||||||
|
Алешин Владислав
|
||||||
|
Власов Михаил
|
||||||
|
Карпов Ибрагим
|
||||||
|
Маслов Артём
|
||||||
|
Бондарев Семён
|
||||||
|
Наумова Каролина
|
||||||
|
Майоров Евгений
|
||||||
|
Новиков Михаил
|
||||||
|
Петрова Ирина
|
||||||
|
Кондратьев Александр
|
||||||
|
Антонова Дарья
|
||||||
|
Чернышева Евгения
|
||||||
|
Пименов Матвей
|
||||||
|
Блинова Виктория
|
||||||
|
Орехов Алексей
|
||||||
|
Моисеев Иван
|
||||||
|
Крючков Макар
|
||||||
|
Щербакова Кристина
|
||||||
|
Черняев Николай
|
||||||
|
Иванова Мирослава
|
||||||
|
Колесова Софья
|
||||||
|
Королев Глеб
|
||||||
|
Киселев Олег
|
||||||
|
Авдеева Мария
|
||||||
|
Кузнецов Мирон
|
||||||
|
Кузнецова Эмилия
|
||||||
|
Колесникова Вера
|
||||||
|
Федорова Александра
|
||||||
|
Коновалов Лев
|
||||||
|
Казаков Платон
|
||||||
|
Зорина Эмилия
|
||||||
|
Сафонова Виктория
|
||||||
|
Зайцев Даниил
|
||||||
|
Ульянова Татьяна
|
||||||
|
Еремина Аделина
|
||||||
|
Пономарева Дарья
|
||||||
|
Серова Виктория
|
||||||
|
Афанасьева Полина
|
||||||
|
Орлова Анна
|
||||||
|
Антонов Владимир
|
||||||
|
Федоров Владислав
|
||||||
|
Петухов Виктор
|
||||||
|
Волкова Полина
|
||||||
|
Токарева Мила
|
||||||
|
Королева Вера
|
||||||
|
Хомякова Виктория
|
||||||
|
Селиванов Лука
|
||||||
|
Сотников Семён
|
||||||
|
Васильева Аврора
|
||||||
|
Фомина Анна
|
||||||
|
Дементьева София
|
||||||
|
Васильева Валерия
|
||||||
|
Гордеев Демид
|
||||||
|
Владимирова Дарья
|
||||||
|
Колосова Арина
|
||||||
|
Алексеев Егор
|
||||||
|
Воробьев Семён
|
||||||
|
Гусева Анастасия
|
||||||
|
Дементьев Мирон
|
||||||
|
Никитина Елизавета
|
||||||
|
Орлова Софья
|
||||||
|
Кириллов Максим
|
||||||
|
Крюкова Екатерина
|
||||||
|
Синицына Алёна
|
||||||
|
Егорова Дарья
|
||||||
|
Васильева Виктория
|
||||||
|
Сорокин Михаил
|
||||||
|
Пономарев Никита
|
||||||
|
Калашникова Алиса
|
||||||
|
Артамонова Мария
|
||||||
|
Орлова София
|
||||||
|
Трошина Елизавета
|
||||||
|
Корнева Надежда
|
||||||
|
Алексеев Матвей
|
||||||
|
Пономарев Фёдор
|
||||||
|
Воробьева Алиса
|
||||||
|
Круглов Егор
|
||||||
|
Дроздова Дарья
|
||||||
|
Алексеева Элина
|
||||||
|
Лебедева Екатерина
|
||||||
|
Измайлова Александра
|
||||||
|
Гусева Анна
|
||||||
|
Березина Марьям
|
||||||
|
Блинов Фёдор
|
||||||
|
Лукина Кристина
|
||||||
|
Соловьева Мирослава
|
||||||
|
Назарова Мария
|
||||||
|
Королева Алиса
|
||||||
|
Смирнов Александр
|
||||||
|
Зверева Анастасия
|
||||||
|
Егорова Мия
|
||||||
|
Самойлов Сергей
|
||||||
|
Кузнецова Вероника
|
||||||
|
Спиридонов Мирослав
|
||||||
|
Казакова Фатима
|
||||||
|
Ефимова Анастасия
|
||||||
|
Гончаров Максим
|
||||||
|
Соболева Екатерина
|
||||||
|
Казаков Лука
|
||||||
|
Шапошникова Дарья
|
||||||
|
Лыков Макар
|
||||||
|
Широков Константин
|
||||||
|
Горячев Филипп
|
||||||
|
Мартынова София
|
||||||
|
Филатов Никита
|
||||||
|
Денисов Александр
|
||||||
|
Полякова Дарья
|
||||||
|
Некрасов Евгений
|
||||||
|
Чернов Артём
|
||||||
|
Дорофеева Вера
|
||||||
|
Пирогова Мария
|
||||||
|
Смирнова Кристина
|
||||||
|
Гришина Ксения
|
||||||
|
Федорова Вероника
|
||||||
|
Козлов Максим
|
||||||
|
Васильев Давид
|
||||||
|
Андрианова Евгения
|
||||||
|
Платонова Анна
|
||||||
|
Савельев Владислав
|
||||||
|
Серова Майя
|
||||||
|
Старикова Полина
|
||||||
|
Пантелеева Милана
|
||||||
|
Царев Михаил
|
||||||
|
Постников Никита
|
||||||
|
Александров Александр
|
||||||
|
Соколова Амина
|
||||||
|
Борисов Артём
|
||||||
|
Тимофеев Михаил
|
||||||
|
Титова Василиса
|
||||||
|
Олейникова Ксения
|
||||||
|
Борисов Антон
|
||||||
|
Власова Василиса
|
||||||
|
Новиков Тимофей
|
||||||
|
Лосева Мадина
|
||||||
|
Семенова Арина
|
||||||
|
Евдокимов Артём
|
||||||
|
Смирнов Роман
|
||||||
|
Фомина Софья
|
||||||
|
Давыдов Максим
|
||||||
|
Максимов Эмир
|
||||||
|
Васильев Арсений
|
||||||
|
Васильева Марьям
|
||||||
|
Баженова Надежда
|
||||||
|
Захарова Ольга
|
||||||
|
Кравцова Полина
|
||||||
|
Носова Вера
|
||||||
|
Павлов Ростислав
|
||||||
|
Лазарева Софья
|
||||||
|
Воронина Елизавета
|
||||||
|
Лебедева Арина
|
||||||
|
Панкратова Полина
|
||||||
|
Иванова Елизавета
|
||||||
|
Назарова Ева
|
||||||
|
Трошин Вячеслав
|
||||||
|
Еремин Фёдор
|
||||||
|
Кравцова Ульяна
|
||||||
|
Киселева София
|
||||||
|
Филатов Алексей
|
||||||
|
Жуков Сергей
|
||||||
|
Руднева Вероника
|
||||||
|
Киселева Зоя
|
||||||
|
Крылов Тигран
|
||||||
|
Тарасов Алексей
|
||||||
|
Бородин Тимур
|
||||||
|
Филиппова Дарья
|
||||||
|
Жукова Маргарита
|
||||||
|
Касаткин Артём
|
||||||
|
Бондарев Александр
|
||||||
|
Краснов Игорь
|
||||||
|
Иванов Владислав
|
||||||
|
Виноградов Юрий
|
||||||
|
Белов Данил
|
||||||
|
Медведева Ангелина
|
||||||
|
Карпов Семён
|
||||||
|
Трофимова София
|
||||||
|
Кузин Андрей
|
||||||
|
Давыдова Эмма
|
||||||
|
Николаева Анастасия
|
||||||
|
Жданова Валерия
|
||||||
|
Кондрашов Александр
|
||||||
|
Ильина Анастасия
|
||||||
|
Семенова Серафима
|
||||||
|
Кузьмин Лев
|
||||||
|
Потапова Софья
|
||||||
|
Назарова Татьяна
|
||||||
|
Смирнова Полина
|
||||||
|
Козлова Алиса
|
||||||
|
Боброва Дарья
|
||||||
|
Герасимова Татьяна
|
||||||
|
Ковалев Евгений
|
||||||
|
Иванов Даниил
|
||||||
|
Потапов Максим
|
||||||
|
Кузнецова Анастасия
|
||||||
|
Егоров Лев
|
||||||
|
Маслов Матвей
|
||||||
|
Кочергин Артём
|
||||||
|
Щукина Дарья
|
||||||
|
Крюков Гордей
|
||||||
|
Федорова Елена
|
||||||
|
Соколов Яромир
|
||||||
|
Власов Лев
|
||||||
|
Голикова Маргарита
|
||||||
|
Медведева Елизавета
|
||||||
|
Соловьева Ясмина
|
||||||
|
Степанов Артём
|
||||||
|
Сухова Екатерина
|
||||||
|
Логинов Сергей
|
||||||
|
Дорохов Никита
|
||||||
|
Матвеев Степан
|
||||||
|
Смирнова Стефания
|
||||||
|
Федотова Карина
|
||||||
|
Морозов Сергей
|
||||||
|
Максимов Дмитрий
|
||||||
|
Фомина Василиса
|
||||||
|
Громов Кирилл
|
||||||
|
Чижова Полина
|
||||||
|
Гришин Дмитрий
|
||||||
|
Беляев Максим
|
||||||
|
Емельянова Надежда
|
||||||
|
Мальцева Таисия
|
||||||
|
Ефимова София
|
||||||
|
Зайцева Василиса
|
||||||
|
Ковалева Алиса
|
||||||
|
Маркин Мирон
|
||||||
|
Алексеева Полина
|
||||||
|
Кошелева Александра
|
||||||
|
Булгакова Мария
|
||||||
|
Волошина Амалия
|
||||||
|
Григорьева Анна
|
||||||
|
Тихомирова Оливия
|
||||||
|
Борисов Михаил
|
||||||
|
Зорина Евгения
|
||||||
|
Калашникова Екатерина
|
||||||
|
Воронцова Анастасия
|
||||||
|
Фадеев Данила
|
||||||
|
Смирнов Егор
|
||||||
|
Артамонова Оливия
|
||||||
|
Семенова Мария
|
||||||
|
Афанасьев Егор
|
||||||
|
Кузнецов Артём
|
||||||
|
Титов Дмитрий
|
||||||
|
Чернышева Диана
|
||||||
|
Казаков Артём
|
||||||
|
Николаева Мария
|
||||||
|
Наумов Алексей
|
||||||
|
Мартынова Полина
|
||||||
|
Тихонова Алиса
|
||||||
|
Козлов Александр
|
||||||
|
Попова Мадина
|
||||||
|
Ларионова Злата
|
||||||
|
Кононов Егор
|
||||||
|
Волкова Татьяна
|
||||||
|
Малышева Вера
|
||||||
|
Николаев Артём
|
||||||
|
Мельникова Варвара
|
||||||
|
Сафонов Захар
|
||||||
|
Гришин Захар
|
||||||
|
Ермилов Роман
|
||||||
|
Иванова Яна
|
||||||
|
Николаев Артур
|
||||||
|
Седов Артём
|
||||||
|
Морозов Данила
|
||||||
|
Дорофеева Елена
|
||||||
|
Демина Надежда
|
||||||
|
Анохина Анастасия
|
||||||
|
Соколова Диана
|
||||||
|
Скворцова София
|
||||||
|
Воронцова Злата
|
||||||
|
Марков Степан
|
||||||
|
Белова Маргарита
|
||||||
|
Нефедова Алия
|
||||||
|
Рудаков Сергей
|
||||||
|
Маслов Дмитрий
|
||||||
|
Маркова Анастасия
|
||||||
|
Хохлов Дамир
|
||||||
|
Воронина Екатерина
|
||||||
|
Николаев Степан
|
||||||
|
Кондрашов Артур
|
||||||
|
Нечаева София
|
||||||
|
Ильин Павел
|
||||||
|
Филиппов Михаил
|
||||||
|
Ефимов Фёдор
|
||||||
|
Захарова Малика
|
||||||
|
Фомин Артём
|
||||||
|
Мешков Владимир
|
||||||
|
Тарасова Арина
|
||||||
|
Демин Егор
|
||||||
|
Федорова Маргарита
|
||||||
|
Широков Георгий
|
||||||
|
Гусева Мария
|
||||||
|
Скворцов Михаил
|
||||||
|
Макаров Фёдор
|
||||||
|
Волков Владислав
|
||||||
|
Воронина Ульяна
|
||||||
|
Кириллова Ева
|
||||||
|
Орлов Мирослав
|
||||||
|
Волкова Варвара
|
||||||
|
Анисимова Майя
|
||||||
|
Лапшина Елизавета
|
||||||
|
Попов Тимофей
|
||||||
|
Федотов Глеб
|
||||||
|
Кудрявцев Владимир
|
||||||
|
Егоров Роман
|
||||||
|
Юдин Александр
|
||||||
|
Леонтьева Анна
|
||||||
|
Соловьев Марк
|
||||||
|
Павлов Даниил
|
||||||
|
Климова Виктория
|
||||||
|
Кочетов Марк
|
||||||
|
Волков Захар
|
||||||
|
Давыдова Любовь
|
||||||
|
Зайцева Таисия
|
||||||
|
Морозова Мария
|
||||||
|
Алексеев Ярослав
|
||||||
|
Новиков Юрий
|
||||||
|
Голубев Владислав
|
||||||
|
Карпов Артём
|
||||||
|
Румянцева Арина
|
||||||
|
Прохоров Григорий
|
||||||
|
Ульянова Мария
|
||||||
|
Суркова Мира
|
||||||
|
Евсеева Екатерина
|
||||||
|
Астафьева Ульяна
|
||||||
|
Николаева Мария
|
||||||
|
Иванов Кирилл
|
||||||
|
Балашова Ева
|
||||||
|
Степанов Дмитрий
|
||||||
|
Игнатьева Елизавета
|
||||||
|
Иванов Даниил
|
||||||
|
Наумова Александра
|
||||||
|
Смирнова Александра
|
||||||
|
Иванов Макар
|
||||||
|
Новиков Владимир
|
||||||
|
Андреев Олег
|
||||||
|
Романов Александр
|
||||||
|
Гордеева Кира
|
||||||
|
Киреева Юлия
|
||||||
|
Никифоров Максим
|
||||||
|
Сахарова Алина
|
||||||
|
Филатов Андрей
|
||||||
|
Андреев Глеб
|
||||||
|
Буров Лев
|
||||||
|
Спиридонова Мария
|
||||||
|
Кузьмин Герман
|
||||||
|
Федоров Артём
|
||||||
|
Рыжов Владимир
|
||||||
|
Сизова Виктория
|
||||||
|
Новикова Варвара
|
||||||
|
Голубев Евгений
|
||||||
|
Васильев Всеволод
|
||||||
|
Самойлова Вероника
|
||||||
|
Лукина Ксения
|
||||||
|
Пономарев Андрей
|
||||||
|
Кудряшова Полина
|
||||||
|
Фирсова Елизавета
|
||||||
|
Субботина Софья
|
||||||
|
Шевцова Виктория
|
||||||
|
Рябов Дмитрий
|
||||||
|
Воронин Владимир
|
||||||
|
Соловьева Полина
|
||||||
|
Чистякова Валерия
|
||||||
|
Николаев Тимофей
|
||||||
|
Фролова Майя
|
||||||
|
Серов Павел
|
||||||
|
Леонов Михаил
|
||||||
|
Логинова Вероника
|
||||||
|
Михайлова Александра
|
||||||
|
Шарова Амалия
|
||||||
|
Горелов Павел
|
||||||
|
Косарев Кирилл
|
||||||
|
Климов Мирон
|
||||||
|
Минин Алексей
|
||||||
|
Тихонова Ариана
|
||||||
|
Исаев Иван
|
||||||
|
Седов Михаил
|
||||||
|
Воробьева Валерия
|
||||||
|
Волкова Николь
|
||||||
|
Литвинова Таисия
|
||||||
|
Смирнов Сергей
|
||||||
|
Павлова Ева
|
||||||
|
Королева Ксения
|
||||||
|
Зуева Мия
|
||||||
|
Алехин Артемий
|
||||||
|
Большакова Владислава
|
||||||
|
Серебряков Артём
|
||||||
|
Козин Евгений
|
||||||
|
Коровина Юлия
|
||||||
|
Панов Лев
|
||||||
|
Королев Василий
|
||||||
|
Акимова Алиса
|
||||||
|
Маркин Ярослав
|
||||||
|
Зайцева Полина
|
||||||
|
Верещагин Иван
|
||||||
|
Максимова София
|
||||||
|
Иванов Илья
|
||||||
|
Степанова Екатерина
|
||||||
|
Щербакова Анна
|
||||||
|
Никитин Герман
|
||||||
|
Лебедев Антон
|
||||||
|
Жуков Кирилл
|
||||||
|
Дементьева Ксения
|
||||||
|
Тихонов Григорий
|
||||||
|
Савицкая Арина
|
||||||
|
Фадеева Ульяна
|
||||||
|
Воробьева Вера
|
||||||
|
Сорокин Кирилл
|
||||||
|
Сахарова Екатерина
|
||||||
|
Савельева Амина
|
||||||
|
Золотарев Семён
|
||||||
|
Черная Анастасия
|
||||||
|
Лазарева Юлия
|
||||||
|
Муравьева Ксения
|
||||||
|
Сорокин Матвей
|
||||||
|
Максимов Александр
|
||||||
|
Иванов Евгений
|
||||||
|
Зайцев Фёдор
|
||||||
|
Алексеева Анастасия
|
||||||
|
Козлов Александр
|
||||||
|
Никитина Василиса
|
||||||
|
Миронова Ангелина
|
||||||
@@ -412,13 +412,13 @@
|
|||||||
log('Incoming subscriberSdpOffer, pcSeq=' + result.subscriberSdpOffer.pcSeq);
|
log('Incoming subscriberSdpOffer, pcSeq=' + result.subscriberSdpOffer.pcSeq);
|
||||||
}
|
}
|
||||||
if (result && result.slotsChanged) {
|
if (result && result.slotsChanged) {
|
||||||
log('Incoming slotsChanged:', JSON.stringify(result.slotsChanged).substring(0, 200));
|
log('Incoming slotsChanged:', JSON.stringify(result.slotsChanged));
|
||||||
}
|
}
|
||||||
if (result && result.participantsChanged) {
|
if (result && result.participantsChanged) {
|
||||||
log('Incoming participantsChanged');
|
log('Incoming participantsChanged');
|
||||||
}
|
}
|
||||||
if (result && result.connectionStatusChanged) {
|
if (result && result.connectionStatusChanged) {
|
||||||
log('Incoming connectionStatusChanged:', JSON.stringify(result.connectionStatusChanged).substring(0, 200));
|
log('Incoming connectionStatusChanged:', JSON.stringify(result.connectionStatusChanged));
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -386,7 +386,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (msg.notification === 'remote-media-settings' || msg.notification === 'media-settings' || msg.notification === 'media-settings-changed') {
|
if (msg.notification === 'remote-media-settings' || msg.notification === 'media-settings' || msg.notification === 'media-settings-changed') {
|
||||||
log('VK media-settings notification:', maskAddr(JSON.stringify(msg).substring(0, 300)));
|
log('VK media-settings notification:', maskAddr(JSON.stringify(msg)));
|
||||||
}
|
}
|
||||||
if (msg.notification === 'participant-added' || msg.notification === 'participant-removed') {
|
if (msg.notification === 'participant-added' || msg.notification === 'participant-removed') {
|
||||||
log('VK participant event: ' + msg.notification);
|
log('VK participant event: ' + msg.notification);
|
||||||
|
|||||||
@@ -2,13 +2,10 @@ package bypass.whitelist
|
|||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.net.ConnectivityManager
|
|
||||||
import android.net.VpnService
|
import android.net.VpnService
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.util.Log
|
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.webkit.JavascriptInterface
|
|
||||||
import android.widget.Button
|
import android.widget.Button
|
||||||
import android.widget.EditText
|
import android.widget.EditText
|
||||||
import android.widget.ImageButton
|
import android.widget.ImageButton
|
||||||
@@ -18,36 +15,29 @@ import androidx.appcompat.app.AppCompatActivity
|
|||||||
import androidx.core.view.ViewCompat
|
import androidx.core.view.ViewCompat
|
||||||
import androidx.core.view.WindowInsetsCompat
|
import androidx.core.view.WindowInsetsCompat
|
||||||
import bypass.whitelist.tunnel.CallPlatform
|
import bypass.whitelist.tunnel.CallPlatform
|
||||||
import bypass.whitelist.tunnel.RelayController
|
import bypass.whitelist.tunnel.TunnelMode
|
||||||
|
import bypass.whitelist.tunnel.ProxyService
|
||||||
import bypass.whitelist.tunnel.TunnelVpnService
|
import bypass.whitelist.tunnel.TunnelVpnService
|
||||||
import bypass.whitelist.tunnel.VpnStatus
|
import bypass.whitelist.tunnel.VpnStatus
|
||||||
|
import bypass.whitelist.ui.HeadlessTelemostFragment
|
||||||
|
import bypass.whitelist.ui.HeadlessVkFragment
|
||||||
|
import bypass.whitelist.ui.JoinFragmentHost
|
||||||
|
import bypass.whitelist.ui.JsHookJoinFragment
|
||||||
import bypass.whitelist.ui.LogViewController
|
import bypass.whitelist.ui.LogViewController
|
||||||
import bypass.whitelist.ui.SettingsMenuController
|
import bypass.whitelist.ui.SettingsDialogFragment
|
||||||
import bypass.whitelist.ui.StatusBarController
|
import bypass.whitelist.ui.StatusBarController
|
||||||
import bypass.whitelist.ui.WebViewManager
|
|
||||||
import bypass.whitelist.util.LogWriter
|
import bypass.whitelist.util.LogWriter
|
||||||
import bypass.whitelist.util.Prefs
|
import bypass.whitelist.util.Prefs
|
||||||
import bypass.whitelist.util.hideKeyboard
|
import bypass.whitelist.util.hideKeyboard
|
||||||
import bypass.whitelist.util.maskUrl
|
import bypass.whitelist.util.maskUrl
|
||||||
import java.net.Inet4Address
|
|
||||||
import java.net.InetAddress
|
|
||||||
|
|
||||||
class MainActivity : AppCompatActivity() {
|
class MainActivity : AppCompatActivity(), SettingsDialogFragment.Listener, JoinFragmentHost {
|
||||||
|
|
||||||
private val logWriter by lazy { LogWriter(cacheDir) }
|
private val logWriter by lazy { LogWriter(cacheDir) }
|
||||||
private val relay by lazy {
|
|
||||||
RelayController(
|
|
||||||
nativeLibDir = applicationInfo.nativeLibraryDir,
|
|
||||||
onLog = { logCtrl.append(it) },
|
|
||||||
onStatus = ::onVpnStatus,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private lateinit var urlInput: EditText
|
private lateinit var urlInput: EditText
|
||||||
private lateinit var logCtrl: LogViewController
|
private lateinit var logCtrl: LogViewController
|
||||||
private lateinit var statusCtrl: StatusBarController
|
private lateinit var statusCtrl: StatusBarController
|
||||||
private lateinit var settingsCtrl: SettingsMenuController
|
|
||||||
private lateinit var webViewMgr: WebViewManager
|
|
||||||
private lateinit var logContainer: View
|
private lateinit var logContainer: View
|
||||||
|
|
||||||
private var previousUrl = ""
|
private var previousUrl = ""
|
||||||
@@ -87,44 +77,21 @@ class MainActivity : AppCompatActivity() {
|
|||||||
onDisconnect = ::fullReset,
|
onDisconnect = ::fullReset,
|
||||||
)
|
)
|
||||||
|
|
||||||
settingsCtrl = SettingsMenuController(
|
|
||||||
activity = this,
|
|
||||||
onModeChanged = { mode ->
|
|
||||||
statusCtrl.tunnelMode = mode
|
|
||||||
webViewMgr.tunnelMode = mode
|
|
||||||
fullReset()
|
|
||||||
},
|
|
||||||
onShareLogs = { logCtrl.shareLogs() },
|
|
||||||
onReset = ::fullReset,
|
|
||||||
)
|
|
||||||
settingsCtrl.onShowLogsChanged = { visible ->
|
|
||||||
logContainer.visibility = if (visible) View.VISIBLE else View.GONE
|
|
||||||
}
|
|
||||||
|
|
||||||
webViewMgr = WebViewManager(
|
|
||||||
activity = this,
|
|
||||||
webView = findViewById(R.id.webView),
|
|
||||||
toggleButton = findViewById(R.id.toggleWebViewButton),
|
|
||||||
toggleArrow = findViewById(R.id.toggleWebViewArrow),
|
|
||||||
toggleLabel = findViewById(R.id.toggleWebViewLabel),
|
|
||||||
onLog = { logCtrl.append(it) },
|
|
||||||
onStatus = ::onVpnStatus,
|
|
||||||
)
|
|
||||||
webViewMgr.setup(JsBridge())
|
|
||||||
|
|
||||||
previousUrl = Prefs.lastUrl
|
previousUrl = Prefs.lastUrl
|
||||||
urlInput.setText(previousUrl)
|
urlInput.setText(previousUrl)
|
||||||
statusCtrl.tunnelMode = Prefs.tunnelMode
|
statusCtrl.tunnelMode = Prefs.tunnelMode
|
||||||
webViewMgr.tunnelMode = Prefs.tunnelMode
|
|
||||||
statusCtrl.setIdle()
|
statusCtrl.setIdle()
|
||||||
logContainer.visibility = if (Prefs.showLogs) View.VISIBLE else View.GONE
|
logContainer.visibility = if (Prefs.showLogs) View.VISIBLE else View.GONE
|
||||||
|
|
||||||
findViewById<Button>(R.id.goButton).setOnClickListener { onGoPressed() }
|
findViewById<Button>(R.id.goButton).setOnClickListener { onGoPressed() }
|
||||||
findViewById<ImageButton>(R.id.shareLogsButton).setOnClickListener { logCtrl.shareLogs() }
|
findViewById<ImageButton>(R.id.shareLogsButton).setOnClickListener { logCtrl.shareLogs() }
|
||||||
findViewById<ImageButton>(R.id.gearButton).setOnClickListener { settingsCtrl.show(it) }
|
findViewById<ImageButton>(R.id.gearButton).setOnClickListener {
|
||||||
|
SettingsDialogFragment().show(supportFragmentManager, SettingsDialogFragment.TAG)
|
||||||
|
}
|
||||||
findViewById<View>(R.id.clearButton).setOnClickListener { urlInput.setText("") }
|
findViewById<View>(R.id.clearButton).setOnClickListener { urlInput.setText("") }
|
||||||
|
|
||||||
TunnelVpnService.onDisconnect = { runOnUiThread { resetState() } }
|
TunnelVpnService.onDisconnect = { runOnUiThread { resetState() } }
|
||||||
|
ProxyService.onDisconnect = { runOnUiThread { resetState() } }
|
||||||
|
|
||||||
VpnService.prepare(this)?.let { vpnPrepLauncher.launch(it) }
|
VpnService.prepare(this)?.let { vpnPrepLauncher.launch(it) }
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||||
@@ -143,54 +110,96 @@ class MainActivity : AppCompatActivity() {
|
|||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
TunnelVpnService.onDisconnect = null
|
TunnelVpnService.onDisconnect = null
|
||||||
relay.stop()
|
|
||||||
TunnelVpnService.instance?.stop()
|
TunnelVpnService.instance?.stop()
|
||||||
|
ProxyService.onDisconnect = null
|
||||||
|
ProxyService.instance?.stop()
|
||||||
logCtrl.close()
|
logCtrl.close()
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun onGoPressed() {
|
override fun onTunnelModeChanged(mode: TunnelMode) {
|
||||||
val url = urlInput.text.toString().trim()
|
statusCtrl.tunnelMode = mode
|
||||||
if (url.isEmpty()) return
|
fullReset()
|
||||||
logCtrl.reset()
|
|
||||||
relay.stop()
|
|
||||||
relay.start(settingsCtrl.tunnelMode, CallPlatform.fromUrl(url))
|
|
||||||
hideKeyboard()
|
|
||||||
urlInput.clearFocus()
|
|
||||||
statusCtrl.setConnected(false)
|
|
||||||
statusCtrl.setStatus(VpnStatus.CONNECTING)
|
|
||||||
logCtrl.append("Loading: ${maskUrl(url)}")
|
|
||||||
if (previousUrl != url) {
|
|
||||||
previousUrl = url
|
|
||||||
Prefs.lastUrl = url
|
|
||||||
}
|
|
||||||
webViewMgr.loadUrl(url)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun onVpnStatus(status: VpnStatus) {
|
override fun onShowLogsChanged(visible: Boolean) {
|
||||||
if (!relay.isRunning) return
|
logContainer.visibility = if (visible) View.VISIBLE else View.GONE
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onShareLogs() {
|
||||||
|
logCtrl.shareLogs()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onReset() {
|
||||||
|
fullReset()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun appendLog(message: String) {
|
||||||
|
logCtrl.append(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onJoinStatusText(text: String) {
|
||||||
|
runOnUiThread { statusCtrl.setStatusText(text) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onJoinStatus(status: VpnStatus) {
|
||||||
TunnelVpnService.instance?.updateStatus(status)
|
TunnelVpnService.instance?.updateStatus(status)
|
||||||
|
ProxyService.instance?.updateStatus(status)
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
statusCtrl.setStatus(status)
|
statusCtrl.setStatus(status)
|
||||||
if (status == VpnStatus.TUNNEL_ACTIVE) statusCtrl.setConnected(true)
|
if (status == VpnStatus.TUNNEL_ACTIVE) statusCtrl.setConnected(true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun requestVpn() {
|
override fun requestVpn() {
|
||||||
|
if (Prefs.proxyOnly) {
|
||||||
|
logCtrl.append("Proxy only mode, skipping VPN")
|
||||||
|
startService(Intent(this, ProxyService::class.java))
|
||||||
|
onJoinStatus(VpnStatus.TUNNEL_ACTIVE)
|
||||||
|
return
|
||||||
|
}
|
||||||
val intent = VpnService.prepare(this)
|
val intent = VpnService.prepare(this)
|
||||||
if (intent != null) vpnLauncher.launch(intent) else startVpnService()
|
if (intent != null) vpnLauncher.launch(intent) else startVpnService()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun onGoPressed() {
|
||||||
|
val url = urlInput.text.toString().trim()
|
||||||
|
if (url.isEmpty()) return
|
||||||
|
|
||||||
|
logCtrl.reset()
|
||||||
|
hideKeyboard()
|
||||||
|
urlInput.clearFocus()
|
||||||
|
statusCtrl.setConnected(false)
|
||||||
|
statusCtrl.setStatus(VpnStatus.CONNECTING)
|
||||||
|
logCtrl.append("Loading: ${maskUrl(url)}")
|
||||||
|
|
||||||
|
if (previousUrl != url) {
|
||||||
|
previousUrl = url
|
||||||
|
Prefs.lastUrl = url
|
||||||
|
}
|
||||||
|
|
||||||
|
val fragment = if (Prefs.headless) {
|
||||||
|
when (CallPlatform.fromUrl(url)) {
|
||||||
|
CallPlatform.VK -> HeadlessVkFragment.newInstance(url)
|
||||||
|
CallPlatform.TELEMOST -> HeadlessTelemostFragment.newInstance(url)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
JsHookJoinFragment.newInstance(url)
|
||||||
|
}
|
||||||
|
|
||||||
|
supportFragmentManager.beginTransaction()
|
||||||
|
.replace(R.id.joinFragmentContainer, fragment)
|
||||||
|
.commit()
|
||||||
|
}
|
||||||
|
|
||||||
private fun startVpnService() {
|
private fun startVpnService() {
|
||||||
startService(Intent(this, TunnelVpnService::class.java))
|
startService(Intent(this, TunnelVpnService::class.java))
|
||||||
logCtrl.append("VPN started")
|
logCtrl.append("VPN started")
|
||||||
onVpnStatus(VpnStatus.TUNNEL_ACTIVE)
|
onJoinStatus(VpnStatus.TUNNEL_ACTIVE)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun resetState() {
|
private fun resetState() {
|
||||||
relay.stop()
|
removeJoinFragment()
|
||||||
webViewMgr.loadBlank()
|
|
||||||
webViewMgr.collapse()
|
|
||||||
logCtrl.reset()
|
logCtrl.reset()
|
||||||
statusCtrl.setConnected(false)
|
statusCtrl.setConnected(false)
|
||||||
statusCtrl.setIdle()
|
statusCtrl.setIdle()
|
||||||
@@ -199,51 +208,15 @@ class MainActivity : AppCompatActivity() {
|
|||||||
private fun fullReset() {
|
private fun fullReset() {
|
||||||
resetState()
|
resetState()
|
||||||
TunnelVpnService.instance?.stop()
|
TunnelVpnService.instance?.stop()
|
||||||
|
ProxyService.instance?.stop()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun getLocalIPAddress(): String {
|
private fun removeJoinFragment() {
|
||||||
try {
|
val fragment = supportFragmentManager.findFragmentById(R.id.joinFragmentContainer)
|
||||||
val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
|
if (fragment != null) {
|
||||||
val network = cm.activeNetwork ?: return ""
|
supportFragmentManager.beginTransaction()
|
||||||
val props = cm.getLinkProperties(network) ?: return ""
|
.remove(fragment)
|
||||||
for (addr in props.linkAddresses) {
|
.commitNowAllowingStateLoss()
|
||||||
val ip = addr.address
|
|
||||||
if (!ip.isLoopbackAddress && ip is Inet4Address) {
|
|
||||||
return ip.hostAddress ?: ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e("RELAY", "getLocalIPAddress error", e)
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
@Suppress("unused")
|
|
||||||
inner class JsBridge {
|
|
||||||
@JavascriptInterface
|
|
||||||
fun log(msg: String) = logCtrl.append(msg)
|
|
||||||
|
|
||||||
@JavascriptInterface
|
|
||||||
fun getLocalIP(): String = getLocalIPAddress()
|
|
||||||
|
|
||||||
@JavascriptInterface
|
|
||||||
fun resolveHost(hostname: String): String = try {
|
|
||||||
val all = InetAddress.getAllByName(hostname)
|
|
||||||
val v4 = all.firstOrNull { it is Inet4Address }
|
|
||||||
val addr = v4 ?: all.first()
|
|
||||||
val ip = addr.hostAddress ?: ""
|
|
||||||
Log.d("RELAY", "resolveHost: $hostname -> $ip (${addr.javaClass.simpleName}, ${all.size} addrs)")
|
|
||||||
ip
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.d("RELAY", "resolveHost: $hostname -> FAILED: ${e.message}")
|
|
||||||
""
|
|
||||||
}
|
|
||||||
|
|
||||||
@JavascriptInterface
|
|
||||||
fun onTunnelReady() {
|
|
||||||
logCtrl.append("Tunnel ready, starting VPN...")
|
|
||||||
onVpnStatus(VpnStatus.TUNNEL_ACTIVE)
|
|
||||||
runOnUiThread { requestVpn() }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package bypass.whitelist.tunnel
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import bypass.whitelist.util.ParamCallback
|
||||||
|
import bypass.whitelist.util.Ports
|
||||||
|
import bypass.whitelist.util.Prefs
|
||||||
|
import bypass.whitelist.util.SocksAuth
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.File
|
||||||
|
import java.io.OutputStreamWriter
|
||||||
|
import java.net.Inet4Address
|
||||||
|
import java.net.InetAddress
|
||||||
|
|
||||||
|
class HeadlessRelayController(
|
||||||
|
private val nativeLibDir: String,
|
||||||
|
private val relayMode: String = "vk-headless-joiner",
|
||||||
|
private val onLog: ParamCallback<String>,
|
||||||
|
private val onStatus: ParamCallback<VpnStatus>,
|
||||||
|
) {
|
||||||
|
private var process: Process? = null
|
||||||
|
private var thread: Thread? = null
|
||||||
|
private var stdinWriter: BufferedWriter? = null
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var isRunning = false
|
||||||
|
private set
|
||||||
|
|
||||||
|
fun start() {
|
||||||
|
stop()
|
||||||
|
isRunning = true
|
||||||
|
|
||||||
|
val relayBin = File(nativeLibDir, "librelay.so")
|
||||||
|
if (!relayBin.exists()) {
|
||||||
|
onLog("Relay binary not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
thread = Thread {
|
||||||
|
val socksPort = Prefs.socksPort
|
||||||
|
if (!PortGuard.ensurePortFree(socksPort)) {
|
||||||
|
onLog("SOCKS5 port $socksPort is busy and could not be freed")
|
||||||
|
onStatus(VpnStatus.PORT_BUSY)
|
||||||
|
isRunning = false
|
||||||
|
return@Thread
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
val processBuilder = ProcessBuilder(
|
||||||
|
relayBin.absolutePath,
|
||||||
|
"--mode", relayMode,
|
||||||
|
"--ws-port", "${Ports.PION_SIGNALING}",
|
||||||
|
"--socks-port", "${Prefs.socksPort}",
|
||||||
|
"--socks-user", SocksAuth.user,
|
||||||
|
"--socks-pass", SocksAuth.pass
|
||||||
|
)
|
||||||
|
processBuilder.redirectErrorStream(true)
|
||||||
|
val proc = processBuilder.start()
|
||||||
|
synchronized(this) {
|
||||||
|
process = proc
|
||||||
|
stdinWriter = BufferedWriter(OutputStreamWriter(proc.outputStream))
|
||||||
|
}
|
||||||
|
onLog("Headless relay started (signaling :${Ports.PION_SIGNALING}, SOCKS5 ${SocksAuth.user}:${SocksAuth.pass}@127.0.0.1:${Prefs.socksPort})")
|
||||||
|
|
||||||
|
proc.inputStream.bufferedReader().forEachLine { line ->
|
||||||
|
if (line.startsWith("RESOLVE:")) {
|
||||||
|
val hostname = line.removePrefix("RESOLVE:")
|
||||||
|
try {
|
||||||
|
val all = InetAddress.getAllByName(hostname)
|
||||||
|
val address = all.firstOrNull { it is Inet4Address } ?: all.first()
|
||||||
|
val resolvedIP = address.hostAddress ?: ""
|
||||||
|
Log.d("RELAY", "Resolved $hostname -> $resolvedIP")
|
||||||
|
writeStdin(resolvedIP)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e("RELAY", "DNS resolve failed for $hostname", e)
|
||||||
|
writeStdin("")
|
||||||
|
}
|
||||||
|
} else if (line.startsWith("STATUS:")) {
|
||||||
|
val status = line.removePrefix("STATUS:")
|
||||||
|
Log.d("RELAY", "status: $status")
|
||||||
|
when {
|
||||||
|
status == "READY" -> onStatus(VpnStatus.STARTING)
|
||||||
|
status == "CONNECTING" -> onStatus(VpnStatus.CONNECTING)
|
||||||
|
status == "TUNNEL_CONNECTED" -> onStatus(VpnStatus.TUNNEL_ACTIVE)
|
||||||
|
status == "TUNNEL_LOST" -> onStatus(VpnStatus.TUNNEL_LOST)
|
||||||
|
status.startsWith("ERROR:") -> onStatus(VpnStatus.CALL_FAILED)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Log.d("RELAY", line)
|
||||||
|
onLog(line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
proc.waitFor()
|
||||||
|
Log.d("RELAY", "Headless relay exited: ${proc.exitValue()}")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (isRunning) {
|
||||||
|
Log.e("RELAY", "Headless relay error", e)
|
||||||
|
onLog("Relay error: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.also { it.start() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendJoinParams(joinJson: String) {
|
||||||
|
writeStdin("JOIN:$joinJson")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun stop() {
|
||||||
|
isRunning = false
|
||||||
|
process?.let {
|
||||||
|
it.destroy()
|
||||||
|
it.waitFor()
|
||||||
|
}
|
||||||
|
process = null
|
||||||
|
stdinWriter = null
|
||||||
|
thread?.interrupt()
|
||||||
|
thread = null
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun writeStdin(line: String) {
|
||||||
|
try {
|
||||||
|
stdinWriter?.write(line)
|
||||||
|
stdinWriter?.newLine()
|
||||||
|
stdinWriter?.flush()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e("RELAY", "writeStdin error: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package bypass.whitelist.tunnel
|
||||||
|
|
||||||
|
import android.os.Process
|
||||||
|
import android.util.Log
|
||||||
|
import java.io.File
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.net.ServerSocket
|
||||||
|
|
||||||
|
object PortGuard {
|
||||||
|
|
||||||
|
private const val TAG = "PortGuard"
|
||||||
|
|
||||||
|
fun ensurePortFree(port: Long): Boolean {
|
||||||
|
if (tryBind(port)) return true
|
||||||
|
Log.w(TAG, "Port $port is busy, killing occupying process")
|
||||||
|
killByPort(port)
|
||||||
|
for (attempt in 1..20) {
|
||||||
|
Thread.sleep(100)
|
||||||
|
if (tryBind(port)) {
|
||||||
|
Log.i(TAG, "Port $port freed after kill (attempt $attempt)")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Log.e(TAG, "Port $port still busy after kill attempt")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun tryBind(port: Long): Boolean {
|
||||||
|
return try {
|
||||||
|
ServerSocket(port.toInt(), 1, InetAddress.getByName("127.0.0.1")).use { true }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun killByPort(port: Long) {
|
||||||
|
try {
|
||||||
|
val hexPort = String.format("%04X", port)
|
||||||
|
val tcp = File("/proc/net/tcp")
|
||||||
|
if (!tcp.canRead()) {
|
||||||
|
Log.w(TAG, "Cannot read /proc/net/tcp")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val inodes = mutableSetOf<String>()
|
||||||
|
tcp.forEachLine { line ->
|
||||||
|
val fields = line.trim().split("\\s+".toRegex())
|
||||||
|
if (fields.size >= 10) {
|
||||||
|
val localPort = fields[1].substringAfter(":")
|
||||||
|
if (localPort.equals(hexPort, ignoreCase = true)) {
|
||||||
|
inodes.add(fields[9])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (inodes.isEmpty()) {
|
||||||
|
Log.w(TAG, "No inode found for port $port")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val myPid = Process.myPid()
|
||||||
|
val procDir = File("/proc")
|
||||||
|
for (entry in procDir.listFiles() ?: emptyArray()) {
|
||||||
|
val pid = entry.name.toIntOrNull() ?: continue
|
||||||
|
if (pid == myPid) continue
|
||||||
|
val fdDir = File(entry, "fd")
|
||||||
|
if (!fdDir.canRead()) continue
|
||||||
|
for (fd in fdDir.listFiles() ?: emptyArray()) {
|
||||||
|
try {
|
||||||
|
val target = fd.canonicalPath
|
||||||
|
for (inode in inodes) {
|
||||||
|
if (target.contains("socket:[$inode]")) {
|
||||||
|
Log.w(TAG, "Killing PID $pid holding port $port (inode $inode)")
|
||||||
|
Process.killProcess(pid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (ignored: Exception) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Log.w(TAG, "Could not find PID for port $port via /proc, trying fuser")
|
||||||
|
try {
|
||||||
|
val fuser = Runtime.getRuntime().exec(arrayOf("fuser", "$port/tcp"))
|
||||||
|
val output = fuser.inputStream.bufferedReader().readText().trim()
|
||||||
|
fuser.waitFor()
|
||||||
|
for (token in output.split("\\s+".toRegex())) {
|
||||||
|
val pid = token.toIntOrNull() ?: continue
|
||||||
|
if (pid != myPid) {
|
||||||
|
Log.w(TAG, "fuser: killing PID $pid for port $port")
|
||||||
|
Process.killProcess(pid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "fuser fallback failed: ${e.message}")
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "killByPort error: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package bypass.whitelist.tunnel
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.app.Service
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.IBinder
|
||||||
|
import bypass.whitelist.MainActivity
|
||||||
|
import bypass.whitelist.util.Callback
|
||||||
|
import bypass.whitelist.R
|
||||||
|
|
||||||
|
class ProxyService : Service() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val CHANNEL_ID = "proxy_channel"
|
||||||
|
const val NOTIFICATION_ID = 2
|
||||||
|
const val ACTION_STOP = "bypass.whitelist.STOP_PROXY"
|
||||||
|
@Volatile var instance: ProxyService? = null
|
||||||
|
@Volatile var onDisconnect: Callback? = null
|
||||||
|
}
|
||||||
|
|
||||||
|
@Volatile var isRunning = false
|
||||||
|
private set
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
instance = this
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
if (intent?.action == ACTION_STOP) {
|
||||||
|
stop()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
start()
|
||||||
|
return START_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
stop()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateStatus(status: VpnStatus) {
|
||||||
|
val nm = getSystemService(NotificationManager::class.java)
|
||||||
|
nm.notify(NOTIFICATION_ID, buildNotification(getString(status.labelRes)))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun stop() {
|
||||||
|
if (!isRunning) return
|
||||||
|
isRunning = false
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
stopForeground(true)
|
||||||
|
stopSelf()
|
||||||
|
onDisconnect?.invoke()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun start() {
|
||||||
|
if (isRunning) return
|
||||||
|
isRunning = true
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
val channel = NotificationChannel(
|
||||||
|
CHANNEL_ID, "Proxy Tunnel", NotificationManager.IMPORTANCE_LOW
|
||||||
|
)
|
||||||
|
val nm = getSystemService(NotificationManager::class.java)
|
||||||
|
nm.createNotificationChannel(channel)
|
||||||
|
}
|
||||||
|
|
||||||
|
startForeground(NOTIFICATION_ID, buildNotification(getString(R.string.notification_proxy_title)))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildNotification(text: String): Notification {
|
||||||
|
val openIntent = Intent(this, MainActivity::class.java).apply {
|
||||||
|
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||||
|
}
|
||||||
|
val openPending = PendingIntent.getActivity(
|
||||||
|
this, 1, openIntent, PendingIntent.FLAG_IMMUTABLE
|
||||||
|
)
|
||||||
|
val stopIntent = Intent(this, ProxyService::class.java).apply {
|
||||||
|
action = ACTION_STOP
|
||||||
|
}
|
||||||
|
val stopPending = PendingIntent.getService(
|
||||||
|
this, 0, stopIntent, PendingIntent.FLAG_IMMUTABLE
|
||||||
|
)
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
Notification.Builder(this, CHANNEL_ID)
|
||||||
|
} else {
|
||||||
|
Notification.Builder(this)
|
||||||
|
}
|
||||||
|
return builder
|
||||||
|
.setContentTitle(getString(R.string.notification_proxy_title))
|
||||||
|
.setContentText(text)
|
||||||
|
.setSmallIcon(android.R.drawable.ic_lock_lock)
|
||||||
|
.setOngoing(true)
|
||||||
|
.setContentIntent(openPending)
|
||||||
|
.addAction(Notification.Action.Builder(null, getString(R.string.notification_disconnect), stopPending).build())
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,15 +1,22 @@
|
|||||||
package bypass.whitelist.tunnel
|
package bypass.whitelist.tunnel
|
||||||
|
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import bypass.whitelist.util.ParamCallback
|
||||||
import bypass.whitelist.util.Ports
|
import bypass.whitelist.util.Ports
|
||||||
|
import bypass.whitelist.util.Prefs
|
||||||
|
import bypass.whitelist.util.SocksAuth
|
||||||
import mobile.LogCallback
|
import mobile.LogCallback
|
||||||
import mobile.Mobile
|
import mobile.Mobile
|
||||||
|
import java.io.BufferedWriter
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
import java.io.OutputStreamWriter
|
||||||
|
import java.net.Inet4Address
|
||||||
|
import java.net.InetAddress
|
||||||
|
|
||||||
class RelayController(
|
class RelayController(
|
||||||
private val nativeLibDir: String,
|
private val nativeLibDir: String,
|
||||||
private val onLog: (String) -> Unit,
|
private val onLog: ParamCallback<String>,
|
||||||
private val onStatus: (VpnStatus) -> Unit,
|
private val onStatus: ParamCallback<VpnStatus>,
|
||||||
) {
|
) {
|
||||||
private var dcThread: Thread? = null
|
private var dcThread: Thread? = null
|
||||||
private var pionThread: Thread? = null
|
private var pionThread: Thread? = null
|
||||||
@@ -50,13 +57,14 @@ class RelayController(
|
|||||||
else if (msg.contains("ws read error")) onStatus(VpnStatus.TUNNEL_LOST)
|
else if (msg.contains("ws read error")) onStatus(VpnStatus.TUNNEL_LOST)
|
||||||
}
|
}
|
||||||
dcThread = Thread {
|
dcThread = Thread {
|
||||||
|
if (!checkPortOrAbort()) return@Thread
|
||||||
try {
|
try {
|
||||||
Mobile.startJoiner(Ports.DC_WS, Ports.SOCKS, cb)
|
Mobile.startJoiner(Ports.DC_WS, Prefs.socksPort, SocksAuth.user, SocksAuth.pass, cb)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
if (isRunning) onLog("Relay error: ${e.message}")
|
if (isRunning) onLog("Relay error: ${e.message}")
|
||||||
}
|
}
|
||||||
}.also { it.start() }
|
}.also { it.start() }
|
||||||
onLog("Relay started DC mode (SOCKS5 :${Ports.SOCKS}, WS :${Ports.DC_WS})")
|
onLog("Relay started DC mode (SOCKS5 ${SocksAuth.user}:${SocksAuth.pass}@127.0.0.1:${Prefs.socksPort}, WS :${Ports.DC_WS})")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun startPion(mode: TunnelMode, platform: CallPlatform) {
|
private fun startPion(mode: TunnelMode, platform: CallPlatform) {
|
||||||
@@ -67,23 +75,45 @@ class RelayController(
|
|||||||
}
|
}
|
||||||
val relayMode = mode.relayMode(platform)
|
val relayMode = mode.relayMode(platform)
|
||||||
pionThread = Thread {
|
pionThread = Thread {
|
||||||
|
if (!checkPortOrAbort()) return@Thread
|
||||||
try {
|
try {
|
||||||
val pb = ProcessBuilder(
|
val pb = ProcessBuilder(
|
||||||
relayBin.absolutePath,
|
relayBin.absolutePath,
|
||||||
"--mode", relayMode,
|
"--mode", relayMode,
|
||||||
"--ws-port", "${Ports.PION_SIGNALING}",
|
"--ws-port", "${Ports.PION_SIGNALING}",
|
||||||
"--socks-port", "${Ports.SOCKS}"
|
"--socks-port", "${Prefs.socksPort}",
|
||||||
|
"--socks-user", SocksAuth.user,
|
||||||
|
"--socks-pass", SocksAuth.pass
|
||||||
)
|
)
|
||||||
pb.redirectErrorStream(true)
|
pb.redirectErrorStream(true)
|
||||||
val proc = pb.start()
|
val proc = pb.start()
|
||||||
synchronized(this) { pionProcess = proc }
|
synchronized(this) { pionProcess = proc }
|
||||||
onLog("Pion relay started mode=$relayMode (signaling :${Ports.PION_SIGNALING}, SOCKS5 :${Ports.SOCKS})")
|
onLog("Pion relay started mode=$relayMode (signaling :${Ports.PION_SIGNALING}, SOCKS5 ${SocksAuth.user}:${SocksAuth.pass}@127.0.0.1:${Prefs.socksPort})")
|
||||||
|
val stdinWriter = BufferedWriter(OutputStreamWriter(proc.outputStream))
|
||||||
proc.inputStream.bufferedReader().forEachLine { line ->
|
proc.inputStream.bufferedReader().forEachLine { line ->
|
||||||
|
if (line.startsWith("RESOLVE:")) {
|
||||||
|
val hostname = line.removePrefix("RESOLVE:")
|
||||||
|
try {
|
||||||
|
val all = InetAddress.getAllByName(hostname)
|
||||||
|
val address = all.firstOrNull { it is Inet4Address } ?: all.first()
|
||||||
|
val resolvedIP = address.hostAddress ?: ""
|
||||||
|
Log.d("RELAY", "Resolved $hostname -> $resolvedIP")
|
||||||
|
stdinWriter.write(resolvedIP)
|
||||||
|
stdinWriter.newLine()
|
||||||
|
stdinWriter.flush()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e("RELAY", "DNS resolve failed for $hostname", e)
|
||||||
|
stdinWriter.write("")
|
||||||
|
stdinWriter.newLine()
|
||||||
|
stdinWriter.flush()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
Log.d("RELAY", line)
|
Log.d("RELAY", line)
|
||||||
onLog(line)
|
onLog(line)
|
||||||
if (line.contains("CONNECTED")) onStatus(VpnStatus.TUNNEL_ACTIVE)
|
if (line.contains("CONNECTED")) onStatus(VpnStatus.TUNNEL_ACTIVE)
|
||||||
else if (line.contains("session cleaned up")) onStatus(VpnStatus.TUNNEL_LOST)
|
else if (line.contains("session cleaned up")) onStatus(VpnStatus.TUNNEL_LOST)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
onLog("Pion relay exited: ${proc.exitValue()}")
|
onLog("Pion relay exited: ${proc.exitValue()}")
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
if (isRunning) {
|
if (isRunning) {
|
||||||
@@ -93,4 +123,13 @@ class RelayController(
|
|||||||
}
|
}
|
||||||
}.also { it.start() }
|
}.also { it.start() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun checkPortOrAbort(): Boolean {
|
||||||
|
val socksPort = Prefs.socksPort
|
||||||
|
if (PortGuard.ensurePortFree(socksPort)) return true
|
||||||
|
onLog("SOCKS5 port $socksPort is busy and could not be freed")
|
||||||
|
onStatus(VpnStatus.PORT_BUSY)
|
||||||
|
isRunning = false
|
||||||
|
return false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -5,13 +5,16 @@ import android.app.NotificationChannel
|
|||||||
import android.app.NotificationManager
|
import android.app.NotificationManager
|
||||||
import android.app.PendingIntent
|
import android.app.PendingIntent
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import android.net.ConnectivityManager
|
||||||
import android.net.VpnService
|
import android.net.VpnService
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.ParcelFileDescriptor
|
import android.os.ParcelFileDescriptor
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import bypass.whitelist.MainActivity
|
import bypass.whitelist.MainActivity
|
||||||
import bypass.whitelist.util.Ports
|
import bypass.whitelist.R
|
||||||
|
import bypass.whitelist.util.Callback
|
||||||
import bypass.whitelist.util.Prefs
|
import bypass.whitelist.util.Prefs
|
||||||
|
import bypass.whitelist.util.SocksAuth
|
||||||
import bypass.whitelist.util.Vpn
|
import bypass.whitelist.util.Vpn
|
||||||
import mobile.Mobile
|
import mobile.Mobile
|
||||||
|
|
||||||
@@ -22,11 +25,11 @@ class TunnelVpnService : VpnService() {
|
|||||||
const val CHANNEL_ID = "vpn_channel"
|
const val CHANNEL_ID = "vpn_channel"
|
||||||
const val NOTIFICATION_ID = 1
|
const val NOTIFICATION_ID = 1
|
||||||
const val ACTION_STOP = "bypass.whitelist.STOP_VPN"
|
const val ACTION_STOP = "bypass.whitelist.STOP_VPN"
|
||||||
var instance: TunnelVpnService? = null
|
@Volatile var instance: TunnelVpnService? = null
|
||||||
var onDisconnect: (() -> Unit)? = null
|
@Volatile var onDisconnect: Callback? = null
|
||||||
}
|
}
|
||||||
|
|
||||||
var isRunning: Boolean = false
|
@Volatile var isRunning: Boolean = false
|
||||||
private var vpnFd: ParcelFileDescriptor? = null
|
private var vpnFd: ParcelFileDescriptor? = null
|
||||||
private var tun2socksThread: Thread? = null
|
private var tun2socksThread: Thread? = null
|
||||||
|
|
||||||
@@ -54,6 +57,7 @@ class TunnelVpnService : VpnService() {
|
|||||||
nm.notify(NOTIFICATION_ID, buildNotification(getString(status.labelRes)))
|
nm.notify(NOTIFICATION_ID, buildNotification(getString(status.labelRes)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
fun stop() {
|
fun stop() {
|
||||||
if (!isRunning) return
|
if (!isRunning) return
|
||||||
isRunning = false
|
isRunning = false
|
||||||
@@ -80,10 +84,16 @@ class TunnelVpnService : VpnService() {
|
|||||||
.setSession(Vpn.SESSION_NAME)
|
.setSession(Vpn.SESSION_NAME)
|
||||||
.addAddress(Vpn.ADDRESS, Vpn.PREFIX_LENGTH)
|
.addAddress(Vpn.ADDRESS, Vpn.PREFIX_LENGTH)
|
||||||
.addRoute(Vpn.ROUTE, 0)
|
.addRoute(Vpn.ROUTE, 0)
|
||||||
.addDnsServer(Vpn.DNS_PRIMARY)
|
|
||||||
.addDnsServer(Vpn.DNS_SECONDARY)
|
|
||||||
.setMtu(Vpn.MTU)
|
.setMtu(Vpn.MTU)
|
||||||
|
|
||||||
|
val systemDns = getSystemDnsServers()
|
||||||
|
if (systemDns.isNotEmpty()) {
|
||||||
|
for (dns in systemDns) builder.addDnsServer(dns)
|
||||||
|
} else {
|
||||||
|
builder.addDnsServer(Vpn.DNS_PRIMARY)
|
||||||
|
builder.addDnsServer(Vpn.DNS_SECONDARY)
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
when (Prefs.splitTunnelingMode) {
|
when (Prefs.splitTunnelingMode) {
|
||||||
SplitTunnelingMode.NONE -> {
|
SplitTunnelingMode.NONE -> {
|
||||||
@@ -120,12 +130,12 @@ class TunnelVpnService : VpnService() {
|
|||||||
isRunning = true
|
isRunning = true
|
||||||
val fd = vpnFd!!.detachFd()
|
val fd = vpnFd!!.detachFd()
|
||||||
vpnFd = null
|
vpnFd = null
|
||||||
Log.i(TAG, "VPN established, fd=$fd")
|
Log.i(TAG, "VPN established, fd=$fd, SOCKS5 ${SocksAuth.user}:${SocksAuth.pass}@127.0.0.1:${Prefs.socksPort}")
|
||||||
updateStatus(VpnStatus.TUNNEL_ACTIVE)
|
updateStatus(VpnStatus.TUNNEL_ACTIVE)
|
||||||
|
|
||||||
tun2socksThread = Thread {
|
tun2socksThread = Thread {
|
||||||
try {
|
try {
|
||||||
Mobile.startTun2Socks(fd.toLong(), Vpn.MTU.toLong(), Ports.SOCKS)
|
Mobile.startTun2Socks(fd.toLong(), Vpn.MTU.toLong(), Prefs.socksPort, SocksAuth.user, SocksAuth.pass)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "tun2socks error: ${e.message}")
|
Log.e(TAG, "tun2socks error: ${e.message}")
|
||||||
isRunning = false
|
isRunning = false
|
||||||
@@ -133,6 +143,13 @@ class TunnelVpnService : VpnService() {
|
|||||||
}.also { it.start() }
|
}.also { it.start() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun getSystemDnsServers(): List<String> {
|
||||||
|
val connectivityManager = getSystemService(ConnectivityManager::class.java) ?: return emptyList()
|
||||||
|
val network = connectivityManager.activeNetwork ?: return emptyList()
|
||||||
|
val linkProperties = connectivityManager.getLinkProperties(network) ?: return emptyList()
|
||||||
|
return linkProperties.dnsServers.mapNotNull { it.hostAddress }
|
||||||
|
}
|
||||||
|
|
||||||
private fun startForegroundNotification() {
|
private fun startForegroundNotification() {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
val channel = NotificationChannel(
|
val channel = NotificationChannel(
|
||||||
@@ -165,12 +182,12 @@ class TunnelVpnService : VpnService() {
|
|||||||
Notification.Builder(this)
|
Notification.Builder(this)
|
||||||
}
|
}
|
||||||
return builder
|
return builder
|
||||||
.setContentTitle("VPN active")
|
.setContentTitle(getString(R.string.notification_vpn_title))
|
||||||
.setContentText(text)
|
.setContentText(text)
|
||||||
.setSmallIcon(android.R.drawable.ic_lock_lock)
|
.setSmallIcon(android.R.drawable.ic_lock_lock)
|
||||||
.setOngoing(true)
|
.setOngoing(true)
|
||||||
.setContentIntent(openPending)
|
.setContentIntent(openPending)
|
||||||
.addAction(Notification.Action.Builder(null, "Disconnect", stopPending).build())
|
.addAction(Notification.Action.Builder(null, getString(R.string.notification_disconnect), stopPending).build())
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,5 +12,7 @@ enum class VpnStatus(@StringRes val labelRes: Int) {
|
|||||||
TUNNEL_ACTIVE(R.string.vpn_tunnel_active),
|
TUNNEL_ACTIVE(R.string.vpn_tunnel_active),
|
||||||
TUNNEL_LOST(R.string.vpn_tunnel_lost),
|
TUNNEL_LOST(R.string.vpn_tunnel_lost),
|
||||||
CALL_DISCONNECTED(R.string.vpn_call_disconnected),
|
CALL_DISCONNECTED(R.string.vpn_call_disconnected),
|
||||||
CALL_FAILED(R.string.vpn_call_failed)
|
CALL_FAILED(R.string.vpn_call_failed),
|
||||||
|
PORT_BUSY(R.string.vpn_port_busy),
|
||||||
|
ACTION_REQUIRED_CAPTCHA(R.string.action_required_captcha)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package bypass.whitelist.ui
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.fragment.app.Fragment
|
||||||
|
import bypass.whitelist.R
|
||||||
|
import bypass.whitelist.tunnel.HeadlessRelayController
|
||||||
|
import bypass.whitelist.tunnel.VpnStatus
|
||||||
|
import bypass.whitelist.util.Prefs
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
class HeadlessTelemostFragment : Fragment() {
|
||||||
|
|
||||||
|
private lateinit var relay: HeadlessRelayController
|
||||||
|
|
||||||
|
private val host: JoinFragmentHost?
|
||||||
|
get() = activity as? JoinFragmentHost
|
||||||
|
|
||||||
|
override fun onCreateView(
|
||||||
|
inflater: LayoutInflater,
|
||||||
|
container: ViewGroup?,
|
||||||
|
savedInstanceState: Bundle?,
|
||||||
|
): View = inflater.inflate(R.layout.fragment_headless_telemost, container, false)
|
||||||
|
|
||||||
|
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||||
|
val joinLink = requireArguments().getString(ARG_URL, "")
|
||||||
|
val displayName = Prefs.autoclickName
|
||||||
|
val tunnelMode = Prefs.tunnelMode.relayArg
|
||||||
|
|
||||||
|
relay = HeadlessRelayController(
|
||||||
|
requireContext().applicationInfo.nativeLibraryDir,
|
||||||
|
relayMode = "telemost-headless-joiner",
|
||||||
|
onLog = { host?.appendLog(it) },
|
||||||
|
onStatus = { status ->
|
||||||
|
Log.d("TM-HEADLESS", "status: $status")
|
||||||
|
host?.onJoinStatus(status)
|
||||||
|
when (status) {
|
||||||
|
VpnStatus.STARTING -> {
|
||||||
|
val params = JSONObject().apply {
|
||||||
|
put("joinLink", joinLink)
|
||||||
|
put("displayName", displayName)
|
||||||
|
put("tunnelMode", tunnelMode)
|
||||||
|
}
|
||||||
|
relay.sendJoinParams(params.toString())
|
||||||
|
}
|
||||||
|
VpnStatus.TUNNEL_ACTIVE -> activity?.runOnUiThread { host?.requestVpn() }
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
relay.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroyView() {
|
||||||
|
if (::relay.isInitialized) relay.stop()
|
||||||
|
super.onDestroyView()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val ARG_URL = "url"
|
||||||
|
|
||||||
|
fun newInstance(url: String): HeadlessTelemostFragment {
|
||||||
|
return HeadlessTelemostFragment().apply {
|
||||||
|
arguments = Bundle().apply {
|
||||||
|
putString(ARG_URL, url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package bypass.whitelist.ui
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.webkit.WebView
|
||||||
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import androidx.fragment.app.Fragment
|
||||||
|
import bypass.whitelist.R
|
||||||
|
import bypass.whitelist.util.BLANK_URL
|
||||||
|
import bypass.whitelist.tunnel.HeadlessRelayController
|
||||||
|
import bypass.whitelist.tunnel.VpnStatus
|
||||||
|
import bypass.whitelist.util.Prefs
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
class HeadlessVkFragment : Fragment() {
|
||||||
|
|
||||||
|
private lateinit var relay: HeadlessRelayController
|
||||||
|
private lateinit var captchaView: VkCaptchaWebView
|
||||||
|
private lateinit var webView: WebView
|
||||||
|
|
||||||
|
private val host: JoinFragmentHost?
|
||||||
|
get() = activity as? JoinFragmentHost
|
||||||
|
|
||||||
|
override fun onCreateView(
|
||||||
|
inflater: LayoutInflater,
|
||||||
|
container: ViewGroup?,
|
||||||
|
savedInstanceState: Bundle?,
|
||||||
|
): View = inflater.inflate(R.layout.fragment_headless_vk, container, false)
|
||||||
|
|
||||||
|
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||||
|
webView = view.findViewById(R.id.captchaWebView)
|
||||||
|
val url = requireArguments().getString(ARG_URL, "")
|
||||||
|
val displayName = Prefs.autoclickName
|
||||||
|
|
||||||
|
relay = HeadlessRelayController(
|
||||||
|
requireContext().applicationInfo.nativeLibraryDir,
|
||||||
|
onLog = { message ->
|
||||||
|
if (message.contains("ERROR:")) {
|
||||||
|
host?.onJoinStatusText(message)
|
||||||
|
}
|
||||||
|
host?.appendLog(message)
|
||||||
|
},
|
||||||
|
onStatus = { status ->
|
||||||
|
Log.d("HEADLESS-VK", "status: $status")
|
||||||
|
host?.onJoinStatus(status)
|
||||||
|
if (status == VpnStatus.TUNNEL_ACTIVE) {
|
||||||
|
activity?.runOnUiThread { host?.requestVpn() }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
relay.start()
|
||||||
|
|
||||||
|
captchaView = VkCaptchaWebView(
|
||||||
|
requireActivity() as AppCompatActivity,
|
||||||
|
webView,
|
||||||
|
onStatus = { message -> host?.onJoinStatusText(message) },
|
||||||
|
) { joinJson ->
|
||||||
|
Log.d("HEADLESS-VK", "Auth complete, sending join params to relay")
|
||||||
|
val params = JSONObject(joinJson)
|
||||||
|
params.put("tunnelMode", Prefs.tunnelMode.relayArg)
|
||||||
|
relay.sendJoinParams(params.toString())
|
||||||
|
}
|
||||||
|
captchaView.setup()
|
||||||
|
captchaView.start(url, displayName)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroyView() {
|
||||||
|
webView.stopLoading()
|
||||||
|
webView.loadUrl(BLANK_URL)
|
||||||
|
webView.destroy()
|
||||||
|
relay.stop()
|
||||||
|
super.onDestroyView()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val ARG_URL = "url"
|
||||||
|
|
||||||
|
fun newInstance(url: String): HeadlessVkFragment {
|
||||||
|
return HeadlessVkFragment().apply {
|
||||||
|
arguments = Bundle().apply {
|
||||||
|
putString(ARG_URL, url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package bypass.whitelist.ui
|
||||||
|
|
||||||
|
import bypass.whitelist.tunnel.VpnStatus
|
||||||
|
|
||||||
|
interface JoinFragmentHost {
|
||||||
|
fun appendLog(message: String)
|
||||||
|
fun onJoinStatus(status: VpnStatus)
|
||||||
|
fun onJoinStatusText(text: String)
|
||||||
|
fun requestVpn()
|
||||||
|
}
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
package bypass.whitelist.ui
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.webkit.ConsoleMessage
|
||||||
|
import android.webkit.JavascriptInterface
|
||||||
|
import android.webkit.PermissionRequest
|
||||||
|
import android.webkit.WebChromeClient
|
||||||
|
import android.webkit.WebResourceRequest
|
||||||
|
import android.webkit.WebResourceResponse
|
||||||
|
import android.webkit.WebView
|
||||||
|
import android.webkit.WebViewClient
|
||||||
|
import android.widget.ImageView
|
||||||
|
import android.widget.TextView
|
||||||
|
import androidx.fragment.app.Fragment
|
||||||
|
import bypass.whitelist.R
|
||||||
|
import bypass.whitelist.tunnel.CallPlatform
|
||||||
|
import bypass.whitelist.tunnel.RelayController
|
||||||
|
import bypass.whitelist.tunnel.TunnelMode
|
||||||
|
import bypass.whitelist.tunnel.VpnStatus
|
||||||
|
import bypass.whitelist.util.BLANK_URL
|
||||||
|
import bypass.whitelist.util.Ports
|
||||||
|
import bypass.whitelist.util.DESKTOP_USER_AGENT
|
||||||
|
import bypass.whitelist.util.Prefs
|
||||||
|
import bypass.whitelist.util.maskUrl
|
||||||
|
import java.net.HttpURLConnection
|
||||||
|
import java.net.Inet4Address
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.net.URL
|
||||||
|
|
||||||
|
private data class HookKey(val isPion: Boolean, val platform: CallPlatform)
|
||||||
|
|
||||||
|
class JsHookJoinFragment : Fragment() {
|
||||||
|
|
||||||
|
private lateinit var webView: WebView
|
||||||
|
private lateinit var toggleButton: View
|
||||||
|
private lateinit var toggleArrow: ImageView
|
||||||
|
private lateinit var toggleLabel: TextView
|
||||||
|
private lateinit var relay: RelayController
|
||||||
|
|
||||||
|
private var expanded = false
|
||||||
|
private var callUrl = ""
|
||||||
|
|
||||||
|
private val host: JoinFragmentHost?
|
||||||
|
get() = activity as? JoinFragmentHost
|
||||||
|
|
||||||
|
private val tunnelMode: TunnelMode
|
||||||
|
get() = Prefs.tunnelMode
|
||||||
|
|
||||||
|
private val hooks = mapOf(
|
||||||
|
HookKey(false, CallPlatform.VK) to lazy { loadAsset("dc-joiner-vk.js") },
|
||||||
|
HookKey(false, CallPlatform.TELEMOST) to lazy { loadAsset("dc-joiner-telemost.js") },
|
||||||
|
HookKey(true, CallPlatform.VK) to lazy { loadAsset("video-vk.js") },
|
||||||
|
HookKey(true, CallPlatform.TELEMOST) to lazy { loadAsset("video-telemost.js") },
|
||||||
|
)
|
||||||
|
|
||||||
|
private val autoclickers = mapOf(
|
||||||
|
CallPlatform.VK to lazy { loadAsset("autoclick-vk.js") },
|
||||||
|
CallPlatform.TELEMOST to lazy { loadAsset("autoclick-telemost.js") },
|
||||||
|
)
|
||||||
|
|
||||||
|
private val muteAudioContext by lazy { loadAsset("mute-audio-context.js") }
|
||||||
|
|
||||||
|
private fun loadAsset(name: String): String =
|
||||||
|
requireContext().assets.open(name).bufferedReader().readText()
|
||||||
|
|
||||||
|
override fun onCreateView(
|
||||||
|
inflater: LayoutInflater,
|
||||||
|
container: ViewGroup?,
|
||||||
|
savedInstanceState: Bundle?,
|
||||||
|
): View = inflater.inflate(R.layout.fragment_jshook_join, container, false)
|
||||||
|
|
||||||
|
@SuppressLint("SetJavaScriptEnabled")
|
||||||
|
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||||
|
webView = view.findViewById(R.id.webView)
|
||||||
|
toggleButton = view.findViewById(R.id.toggleWebViewButton)
|
||||||
|
toggleArrow = view.findViewById(R.id.toggleWebViewArrow)
|
||||||
|
toggleLabel = view.findViewById(R.id.toggleWebViewLabel)
|
||||||
|
|
||||||
|
relay = RelayController(
|
||||||
|
nativeLibDir = requireContext().applicationInfo.nativeLibraryDir,
|
||||||
|
onLog = { host?.appendLog(it) },
|
||||||
|
onStatus = { status ->
|
||||||
|
if (!relay.isRunning) return@RelayController
|
||||||
|
host?.onJoinStatus(status)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
val platform = CallPlatform.fromUrl(requireArguments().getString(ARG_URL, ""))
|
||||||
|
relay.start(tunnelMode, platform)
|
||||||
|
|
||||||
|
toggleButton.setOnClickListener { setExpanded(!expanded) }
|
||||||
|
|
||||||
|
webView.settings.apply {
|
||||||
|
javaScriptEnabled = true
|
||||||
|
domStorageEnabled = true
|
||||||
|
mediaPlaybackRequiresUserGesture = false
|
||||||
|
allowContentAccess = true
|
||||||
|
allowFileAccess = true
|
||||||
|
databaseEnabled = true
|
||||||
|
setSupportMultipleWindows(false)
|
||||||
|
useWideViewPort = true
|
||||||
|
loadWithOverviewMode = true
|
||||||
|
builtInZoomControls = true
|
||||||
|
displayZoomControls = false
|
||||||
|
userAgentString = DESKTOP_USER_AGENT
|
||||||
|
}
|
||||||
|
|
||||||
|
webView.addJavascriptInterface(JsBridge(), "AndroidBridge")
|
||||||
|
|
||||||
|
webView.webChromeClient = object : WebChromeClient() {
|
||||||
|
override fun onPermissionRequest(request: PermissionRequest) {
|
||||||
|
activity?.runOnUiThread { request.grant(request.resources) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onConsoleMessage(msg: ConsoleMessage): Boolean {
|
||||||
|
val text = msg.message()
|
||||||
|
Log.d("HOOK", text)
|
||||||
|
if (text.contains("[HOOK]")) {
|
||||||
|
host?.appendLog(text)
|
||||||
|
when {
|
||||||
|
text.contains("CALL CONNECTED") -> host?.onJoinStatus(VpnStatus.CALL_CONNECTED)
|
||||||
|
text.contains("DataChannel open") -> host?.onJoinStatus(VpnStatus.DATACHANNEL_OPEN)
|
||||||
|
text.contains("DataChannel closed") -> host?.onJoinStatus(VpnStatus.DATACHANNEL_LOST)
|
||||||
|
text.contains("WebSocket connected") -> host?.onJoinStatus(VpnStatus.TUNNEL_ACTIVE)
|
||||||
|
text.contains("WebSocket disconnected") -> host?.onJoinStatus(VpnStatus.TUNNEL_LOST)
|
||||||
|
text.contains("Connection state: connecting") -> host?.onJoinStatus(VpnStatus.CONNECTING)
|
||||||
|
text.contains("Connection state: disconnected") -> host?.onJoinStatus(VpnStatus.CALL_DISCONNECTED)
|
||||||
|
text.contains("Connection state: failed") -> host?.onJoinStatus(VpnStatus.CALL_FAILED)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
webView.webViewClient = object : WebViewClient() {
|
||||||
|
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
|
||||||
|
val url = request.url.toString()
|
||||||
|
val platform = CallPlatform.fromUrl(url)
|
||||||
|
if (platform != CallPlatform.TELEMOST || !url.contains("/j/") || request.method != "GET") return null
|
||||||
|
return stripCsp(url, request)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
|
||||||
|
if (url.contains(BLANK_URL)) return
|
||||||
|
view.evaluateJavascript(muteAudioContext, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPageFinished(view: WebView, url: String) {
|
||||||
|
if (url.contains(BLANK_URL)) return
|
||||||
|
if (!expanded && url != callUrl) activity?.runOnUiThread { setExpanded(true) }
|
||||||
|
view.evaluateJavascript("!!window.__hookInstalled") { result ->
|
||||||
|
if (result == "true") {
|
||||||
|
Log.d("HOOK", "Hook already injected, skipping")
|
||||||
|
return@evaluateJavascript
|
||||||
|
}
|
||||||
|
val platform = CallPlatform.fromUrl(url)
|
||||||
|
host?.appendLog("Page loaded, injecting hook for ${maskUrl(url)}")
|
||||||
|
view.evaluateJavascript("window.WS_PORT=${mobile.Mobile.activeWsPort()}", null)
|
||||||
|
view.evaluateJavascript("window.PION_PORT=${Ports.PION_SIGNALING}", null)
|
||||||
|
view.evaluateJavascript(hookForPlatform(platform), null)
|
||||||
|
if (Prefs.autoclickEnabled) {
|
||||||
|
host?.appendLog("Injecting autoclick for ${maskUrl(url)}")
|
||||||
|
view.evaluateJavascript("window.autofillName='${Prefs.autoclickName}'", null)
|
||||||
|
view.evaluateJavascript(autoclickers[platform]!!.value, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val url = requireArguments().getString(ARG_URL, "")
|
||||||
|
if (url.isNotEmpty()) {
|
||||||
|
callUrl = url
|
||||||
|
webView.loadUrl(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroyView() {
|
||||||
|
webView.stopLoading()
|
||||||
|
webView.loadUrl(BLANK_URL)
|
||||||
|
webView.destroy()
|
||||||
|
relay.stop()
|
||||||
|
super.onDestroyView()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun expand() {
|
||||||
|
setExpanded(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun setExpanded(value: Boolean) {
|
||||||
|
expanded = value
|
||||||
|
webView.visibility = if (value) View.VISIBLE else View.GONE
|
||||||
|
toggleArrow.rotation = if (value) 180f else 0f
|
||||||
|
toggleLabel.setText(if (value) R.string.collapse_webview else R.string.expand_webview)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hookForPlatform(platform: CallPlatform): String =
|
||||||
|
hooks[HookKey(tunnelMode.isPion, platform)]!!.value
|
||||||
|
|
||||||
|
private fun stripCsp(url: String, request: WebResourceRequest): WebResourceResponse? {
|
||||||
|
return try {
|
||||||
|
val conn = URL(url).openConnection() as HttpURLConnection
|
||||||
|
conn.requestMethod = "GET"
|
||||||
|
request.requestHeaders?.forEach { (key, value) -> conn.setRequestProperty(key, value) }
|
||||||
|
val headers = mutableMapOf<String, String>()
|
||||||
|
conn.headerFields?.forEach { (key, values) ->
|
||||||
|
if (key != null
|
||||||
|
&& !key.equals("content-security-policy", ignoreCase = true)
|
||||||
|
&& !key.equals("content-security-policy-report-only", ignoreCase = true)
|
||||||
|
) {
|
||||||
|
headers[key] = values.joinToString(", ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WebResourceResponse(
|
||||||
|
conn.contentType?.split(";")?.firstOrNull() ?: "text/html",
|
||||||
|
"utf-8", conn.responseCode, conn.responseMessage ?: "OK",
|
||||||
|
headers, conn.inputStream
|
||||||
|
)
|
||||||
|
} catch (_: Exception) { null }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getLocalIPAddress(): String {
|
||||||
|
try {
|
||||||
|
val context = context ?: return ""
|
||||||
|
val connectivityManager = context.getSystemService(android.content.Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||||
|
val network = connectivityManager.activeNetwork ?: return ""
|
||||||
|
val linkProperties = connectivityManager.getLinkProperties(network) ?: return ""
|
||||||
|
for (addr in linkProperties.linkAddresses) {
|
||||||
|
val ip = addr.address
|
||||||
|
if (!ip.isLoopbackAddress && ip is Inet4Address) {
|
||||||
|
return ip.hostAddress ?: ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e("RELAY", "getLocalIPAddress error", e)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
inner class JsBridge {
|
||||||
|
@JavascriptInterface
|
||||||
|
fun log(msg: String) = host?.appendLog(msg)
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun getLocalIP(): String = getLocalIPAddress()
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun resolveHost(hostname: String): String = try {
|
||||||
|
val all = InetAddress.getAllByName(hostname)
|
||||||
|
val v4 = all.firstOrNull { it is Inet4Address }
|
||||||
|
val addr = v4 ?: all.first()
|
||||||
|
val ip = addr.hostAddress ?: ""
|
||||||
|
Log.d("RELAY", "resolveHost: $hostname -> $ip (${addr.javaClass.simpleName}, ${all.size} addrs)")
|
||||||
|
ip
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.d("RELAY", "resolveHost: $hostname -> FAILED: ${e.message}")
|
||||||
|
""
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun onTunnelReady() {
|
||||||
|
host?.appendLog("Tunnel ready, starting VPN...")
|
||||||
|
host?.onJoinStatus(VpnStatus.TUNNEL_ACTIVE)
|
||||||
|
activity?.runOnUiThread { host?.requestVpn() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun onCaptchaDetected(isDone: Boolean) {
|
||||||
|
if (!isDone) {
|
||||||
|
host?.onJoinStatus(VpnStatus.ACTION_REQUIRED_CAPTCHA)
|
||||||
|
activity?.runOnUiThread { expand() }
|
||||||
|
} else {
|
||||||
|
host?.onJoinStatus(VpnStatus.CONNECTING)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val ARG_URL = "url"
|
||||||
|
|
||||||
|
fun newInstance(url: String): JsHookJoinFragment {
|
||||||
|
return JsHookJoinFragment().apply {
|
||||||
|
arguments = Bundle().apply {
|
||||||
|
putString(ARG_URL, url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package bypass.whitelist.ui
|
||||||
|
|
||||||
|
import android.app.Dialog
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.view.View
|
||||||
|
import android.widget.Button
|
||||||
|
import android.widget.CheckBox
|
||||||
|
import android.widget.EditText
|
||||||
|
import android.widget.RadioButton
|
||||||
|
import android.widget.RadioGroup
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.appcompat.app.AlertDialog
|
||||||
|
import androidx.fragment.app.DialogFragment
|
||||||
|
import bypass.whitelist.R
|
||||||
|
import bypass.whitelist.util.Callback
|
||||||
|
import bypass.whitelist.util.Prefs
|
||||||
|
import bypass.whitelist.util.SocksAuthMode
|
||||||
|
|
||||||
|
class ProxySettingsDialogFragment(
|
||||||
|
private val onChanged: Callback? = null,
|
||||||
|
) : DialogFragment() {
|
||||||
|
|
||||||
|
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
|
||||||
|
val view = layoutInflater.inflate(R.layout.dialog_proxy_settings, null)
|
||||||
|
|
||||||
|
val portInput = view.findViewById<EditText>(R.id.proxyPortInput)
|
||||||
|
val authModeGroup = view.findViewById<RadioGroup>(R.id.authModeGroup)
|
||||||
|
val authModeAuto = view.findViewById<RadioButton>(R.id.authModeAuto)
|
||||||
|
val authModeManual = view.findViewById<RadioButton>(R.id.authModeManual)
|
||||||
|
val manualAuthContainer = view.findViewById<View>(R.id.manualAuthContainer)
|
||||||
|
val userInput = view.findViewById<EditText>(R.id.proxyUserInput)
|
||||||
|
val passInput = view.findViewById<EditText>(R.id.proxyPassInput)
|
||||||
|
val copyButton = view.findViewById<Button>(R.id.copyProxyButton)
|
||||||
|
val proxyOnlyCheckbox = view.findViewById<CheckBox>(R.id.proxyOnlyCheckbox)
|
||||||
|
|
||||||
|
portInput.setText(Prefs.socksPort.toString())
|
||||||
|
proxyOnlyCheckbox.isChecked = Prefs.proxyOnly
|
||||||
|
|
||||||
|
when (Prefs.socksAuthMode) {
|
||||||
|
SocksAuthMode.AUTO -> authModeAuto.isChecked = true
|
||||||
|
SocksAuthMode.MANUAL -> authModeManual.isChecked = true
|
||||||
|
}
|
||||||
|
manualAuthContainer.visibility = if (Prefs.socksAuthMode == SocksAuthMode.MANUAL) View.VISIBLE else View.GONE
|
||||||
|
userInput.setText(Prefs.socksUser)
|
||||||
|
passInput.setText(Prefs.socksPass)
|
||||||
|
|
||||||
|
authModeGroup.setOnCheckedChangeListener { _, checkedId ->
|
||||||
|
manualAuthContainer.visibility = if (checkedId == R.id.authModeManual) View.VISIBLE else View.GONE
|
||||||
|
}
|
||||||
|
|
||||||
|
copyButton.setOnClickListener {
|
||||||
|
val port = portInput.text.toString()
|
||||||
|
val user = userInput.text.toString()
|
||||||
|
val pass = passInput.text.toString()
|
||||||
|
val proxyUrl = "socks5://$user:$pass@127.0.0.1:$port"
|
||||||
|
val clipboard = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
clipboard.setPrimaryClip(ClipData.newPlainText("proxy", proxyUrl))
|
||||||
|
Toast.makeText(requireContext(), R.string.proxy_copied, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
|
||||||
|
return AlertDialog.Builder(requireContext())
|
||||||
|
.setTitle(R.string.proxy_settings_title)
|
||||||
|
.setView(view)
|
||||||
|
.setPositiveButton(android.R.string.ok) { _, _ ->
|
||||||
|
val port = portInput.text.toString().toLongOrNull()
|
||||||
|
if (port != null && port in 1..65535) {
|
||||||
|
Prefs.socksPort = port
|
||||||
|
}
|
||||||
|
Prefs.socksAuthMode = if (authModeManual.isChecked) SocksAuthMode.MANUAL else SocksAuthMode.AUTO
|
||||||
|
if (authModeManual.isChecked) {
|
||||||
|
Prefs.socksUser = userInput.text.toString()
|
||||||
|
Prefs.socksPass = passInput.text.toString()
|
||||||
|
}
|
||||||
|
Prefs.proxyOnly = proxyOnlyCheckbox.isChecked
|
||||||
|
onChanged?.invoke()
|
||||||
|
}
|
||||||
|
.setNegativeButton(android.R.string.cancel, null)
|
||||||
|
.create()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val TAG = "ProxySettingsDialog"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,303 @@
|
|||||||
|
package bypass.whitelist.ui
|
||||||
|
|
||||||
|
import android.app.Dialog
|
||||||
|
import android.content.pm.ApplicationInfo
|
||||||
|
import android.text.Editable
|
||||||
|
import android.text.TextWatcher
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.Button
|
||||||
|
import android.widget.CheckBox
|
||||||
|
import android.widget.EditText
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.ListView
|
||||||
|
import android.widget.ProgressBar
|
||||||
|
import android.widget.TextView
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.appcompat.app.AlertDialog
|
||||||
|
import androidx.fragment.app.DialogFragment
|
||||||
|
import bypass.whitelist.R
|
||||||
|
import bypass.whitelist.tunnel.SplitTunnelingMode
|
||||||
|
import bypass.whitelist.tunnel.TunnelMode
|
||||||
|
import bypass.whitelist.tunnel.TunnelVpnService
|
||||||
|
import bypass.whitelist.util.Prefs
|
||||||
|
|
||||||
|
class SettingsDialogFragment : DialogFragment() {
|
||||||
|
|
||||||
|
interface Listener {
|
||||||
|
fun onTunnelModeChanged(mode: TunnelMode)
|
||||||
|
fun onShowLogsChanged(visible: Boolean)
|
||||||
|
fun onShareLogs()
|
||||||
|
fun onReset()
|
||||||
|
}
|
||||||
|
|
||||||
|
private var listener: Listener? = null
|
||||||
|
|
||||||
|
private var tunnelMode: TunnelMode = Prefs.tunnelMode
|
||||||
|
private var splitTunnelingMode: SplitTunnelingMode = Prefs.splitTunnelingMode
|
||||||
|
private var splitTunnelingPackages: MutableSet<String> = Prefs.splitTunnelingPackages.toMutableSet()
|
||||||
|
|
||||||
|
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
|
||||||
|
val dialog = super.onCreateDialog(savedInstanceState)
|
||||||
|
dialog.setTitle(R.string.cd_settings)
|
||||||
|
return dialog
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreateView(
|
||||||
|
inflater: LayoutInflater,
|
||||||
|
container: ViewGroup?,
|
||||||
|
savedInstanceState: Bundle?,
|
||||||
|
): View = inflater.inflate(R.layout.fragment_settings, container, false)
|
||||||
|
|
||||||
|
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||||
|
listener = activity as? Listener
|
||||||
|
|
||||||
|
val tunnelModeItem = view.findViewById<TextView>(R.id.tunnelModeItem)
|
||||||
|
val splitTunnelingItem = view.findViewById<TextView>(R.id.splitTunnelingItem)
|
||||||
|
val splitTunnelingAppsItem = view.findViewById<TextView>(R.id.splitTunnelingAppsItem)
|
||||||
|
val proxyItem = view.findViewById<TextView>(R.id.proxyItem)
|
||||||
|
val autoclickItem = view.findViewById<TextView>(R.id.autoclickItem)
|
||||||
|
val headlessCheckbox = view.findViewById<CheckBox>(R.id.headlessCheckbox)
|
||||||
|
val reconnectCheckbox = view.findViewById<CheckBox>(R.id.reconnectOnStartCheckbox)
|
||||||
|
val showLogsCheckbox = view.findViewById<CheckBox>(R.id.showLogsCheckbox)
|
||||||
|
val shareLogsItem = view.findViewById<TextView>(R.id.shareLogsItem)
|
||||||
|
val resetItem = view.findViewById<TextView>(R.id.resetItem)
|
||||||
|
val closeButton = view.findViewById<Button>(R.id.closeButton)
|
||||||
|
|
||||||
|
updateTunnelModeLabel(tunnelModeItem)
|
||||||
|
updateSplitTunnelingLabel(splitTunnelingItem)
|
||||||
|
updateSplitTunnelingAppsEnabled(splitTunnelingAppsItem)
|
||||||
|
|
||||||
|
headlessCheckbox.isChecked = Prefs.headless
|
||||||
|
reconnectCheckbox.isChecked = Prefs.connectOnStart
|
||||||
|
showLogsCheckbox.isChecked = Prefs.showLogs
|
||||||
|
|
||||||
|
tunnelModeItem.setOnClickListener {
|
||||||
|
showModeDialog(tunnelModeItem)
|
||||||
|
}
|
||||||
|
|
||||||
|
splitTunnelingItem.setOnClickListener {
|
||||||
|
showSplitTunnelingDialog(splitTunnelingItem, splitTunnelingAppsItem)
|
||||||
|
}
|
||||||
|
|
||||||
|
splitTunnelingAppsItem.setOnClickListener {
|
||||||
|
if (splitTunnelingMode != SplitTunnelingMode.NONE) {
|
||||||
|
showSplitTunnelingAppSelection()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proxyItem.setOnClickListener {
|
||||||
|
ProxySettingsDialogFragment {
|
||||||
|
listener?.onReset()
|
||||||
|
dismiss()
|
||||||
|
}.show(childFragmentManager, ProxySettingsDialogFragment.TAG)
|
||||||
|
}
|
||||||
|
|
||||||
|
autoclickItem.setOnClickListener {
|
||||||
|
showAutoclickSettingsDialog()
|
||||||
|
}
|
||||||
|
|
||||||
|
headlessCheckbox.setOnCheckedChangeListener { _, checked ->
|
||||||
|
Prefs.headless = checked
|
||||||
|
listener?.onReset()
|
||||||
|
}
|
||||||
|
|
||||||
|
reconnectCheckbox.setOnCheckedChangeListener { _, checked ->
|
||||||
|
Prefs.connectOnStart = checked
|
||||||
|
}
|
||||||
|
|
||||||
|
showLogsCheckbox.setOnCheckedChangeListener { _, checked ->
|
||||||
|
Prefs.showLogs = checked
|
||||||
|
listener?.onShowLogsChanged(checked)
|
||||||
|
}
|
||||||
|
|
||||||
|
shareLogsItem.setOnClickListener {
|
||||||
|
listener?.onShareLogs()
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
|
||||||
|
resetItem.setOnClickListener {
|
||||||
|
listener?.onReset()
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
|
||||||
|
closeButton.setOnClickListener {
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateTunnelModeLabel(textView: TextView) {
|
||||||
|
textView.text = getString(R.string.menu_tunnel, tunnelMode.label)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateSplitTunnelingLabel(textView: TextView) {
|
||||||
|
textView.text = getString(R.string.menu_split_tunneling, splitTunnelingMode.label)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateSplitTunnelingAppsEnabled(textView: TextView) {
|
||||||
|
val enabled = splitTunnelingMode != SplitTunnelingMode.NONE
|
||||||
|
textView.isEnabled = enabled
|
||||||
|
textView.alpha = if (enabled) 1.0f else 0.4f
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showModeDialog(tunnelModeItem: TextView) {
|
||||||
|
val modes = TunnelMode.entries
|
||||||
|
val labels = modes.map { it.label }.toTypedArray()
|
||||||
|
val current = modes.indexOf(tunnelMode)
|
||||||
|
AlertDialog.Builder(requireContext())
|
||||||
|
.setSingleChoiceItems(labels, current) { dialog, which ->
|
||||||
|
dialog.dismiss()
|
||||||
|
val mode = modes[which]
|
||||||
|
if (mode != tunnelMode) {
|
||||||
|
tunnelMode = mode
|
||||||
|
Prefs.tunnelMode = mode
|
||||||
|
updateTunnelModeLabel(tunnelModeItem)
|
||||||
|
listener?.onTunnelModeChanged(mode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showSplitTunnelingDialog(
|
||||||
|
splitTunnelingItem: TextView,
|
||||||
|
splitTunnelingAppsItem: TextView,
|
||||||
|
) {
|
||||||
|
val modes = SplitTunnelingMode.entries.toTypedArray()
|
||||||
|
val labels = modes.map { it.label }.toTypedArray()
|
||||||
|
val selectedIndex = modes.indexOf(splitTunnelingMode)
|
||||||
|
|
||||||
|
AlertDialog.Builder(requireContext())
|
||||||
|
.setTitle(R.string.split_tunneling_mode_prompt)
|
||||||
|
.setSingleChoiceItems(labels, selectedIndex) { dialog, which ->
|
||||||
|
splitTunnelingMode = modes[which]
|
||||||
|
Prefs.splitTunnelingMode = splitTunnelingMode
|
||||||
|
updateSplitTunnelingLabel(splitTunnelingItem)
|
||||||
|
updateSplitTunnelingAppsEnabled(splitTunnelingAppsItem)
|
||||||
|
dialog.dismiss()
|
||||||
|
if (TunnelVpnService.instance?.isRunning == true) {
|
||||||
|
Toast.makeText(requireContext(), R.string.split_tunneling_mode_changed, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.setNegativeButton(android.R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showSplitTunnelingAppSelection() {
|
||||||
|
val dialogLayout = layoutInflater.inflate(R.layout.split_tunneling_app_list_dialog, null)
|
||||||
|
val loadingProgressBar = dialogLayout.findViewById<ProgressBar>(R.id.loading_progress_bar)
|
||||||
|
val appListContainer = dialogLayout.findViewById<LinearLayout>(R.id.app_list_container)
|
||||||
|
val searchEditText = dialogLayout.findViewById<EditText>(R.id.search_input)
|
||||||
|
val systemAppsCheckbox = dialogLayout.findViewById<CheckBox>(R.id.system_apps_checkbox)
|
||||||
|
val listView = dialogLayout.findViewById<ListView>(R.id.app_list_view)
|
||||||
|
|
||||||
|
AlertDialog.Builder(requireContext())
|
||||||
|
.setTitle(R.string.split_tunneling_apps_prompt)
|
||||||
|
.setView(dialogLayout)
|
||||||
|
.setPositiveButton(android.R.string.ok) { _, _ ->
|
||||||
|
Prefs.splitTunnelingMode = splitTunnelingMode
|
||||||
|
Prefs.splitTunnelingPackages = splitTunnelingPackages
|
||||||
|
if (TunnelVpnService.instance?.isRunning == true) {
|
||||||
|
Toast.makeText(requireContext(), R.string.split_tunneling_mode_changed, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.setNegativeButton(android.R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
|
||||||
|
loadingProgressBar.visibility = View.VISIBLE
|
||||||
|
appListContainer.visibility = View.GONE
|
||||||
|
|
||||||
|
Thread {
|
||||||
|
var includeSystemApps = false
|
||||||
|
val context = requireContext()
|
||||||
|
val pm = context.packageManager
|
||||||
|
val ownPackage = context.packageName
|
||||||
|
|
||||||
|
val installedApps = pm.getInstalledApplications(PackageManager.GET_META_DATA)
|
||||||
|
.filter { it.packageName != ownPackage }
|
||||||
|
.mapNotNull { appInfo ->
|
||||||
|
val pkg = appInfo.packageName
|
||||||
|
if (pkg.isBlank()) return@mapNotNull null
|
||||||
|
val label = appInfo.loadLabel(pm).toString().takeIf { it.isNotBlank() } ?: pkg
|
||||||
|
SplitTunnelingAppItem(
|
||||||
|
pkg, label, pm.getApplicationIcon(pkg),
|
||||||
|
splitTunnelingPackages.contains(pkg),
|
||||||
|
(appInfo.flags and ApplicationInfo.FLAG_SYSTEM) == 0,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.distinctBy { it.packageName }
|
||||||
|
.sortedWith(compareByDescending<SplitTunnelingAppItem> { it.isSelected }.thenBy { it.label.lowercase() })
|
||||||
|
|
||||||
|
activity?.runOnUiThread {
|
||||||
|
loadingProgressBar.visibility = View.GONE
|
||||||
|
appListContainer.visibility = View.VISIBLE
|
||||||
|
|
||||||
|
fun buildAppList(query: String, includeSystemApps: Boolean): List<SplitTunnelingAppItem> {
|
||||||
|
val baseList = installedApps.filter { includeSystemApps || it.isUserApp }
|
||||||
|
return if (query.isBlank()) {
|
||||||
|
baseList
|
||||||
|
} else {
|
||||||
|
baseList.filter {
|
||||||
|
it.label.contains(query, ignoreCase = true) ||
|
||||||
|
it.packageName.contains(query, ignoreCase = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val adapter = SplitTunnelingAdapter(layoutInflater, splitTunnelingPackages)
|
||||||
|
adapter.items = buildAppList("", includeSystemApps)
|
||||||
|
|
||||||
|
if (adapter.items.isEmpty()) return@runOnUiThread
|
||||||
|
|
||||||
|
listView.choiceMode = ListView.CHOICE_MODE_MULTIPLE
|
||||||
|
listView.adapter = adapter
|
||||||
|
|
||||||
|
systemAppsCheckbox.isChecked = includeSystemApps
|
||||||
|
systemAppsCheckbox.setOnCheckedChangeListener { _, checked ->
|
||||||
|
includeSystemApps = checked
|
||||||
|
adapter.items = buildAppList(searchEditText.text.toString(), includeSystemApps)
|
||||||
|
}
|
||||||
|
|
||||||
|
searchEditText.addTextChangedListener(object : TextWatcher {
|
||||||
|
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
|
||||||
|
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
|
||||||
|
adapter.items = buildAppList(s.toString(), includeSystemApps)
|
||||||
|
}
|
||||||
|
override fun afterTextChanged(s: Editable?) {}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showAutoclickSettingsDialog() {
|
||||||
|
val dialogLayout = layoutInflater.inflate(R.layout.autoclick_settings_dialog, null)
|
||||||
|
val autoclickCheckbox = dialogLayout.findViewById<CheckBox>(R.id.autoclick_checkbox)
|
||||||
|
val nameInput = dialogLayout.findViewById<EditText>(R.id.autoclick_name_input)
|
||||||
|
val generateButton = dialogLayout.findViewById<Button>(R.id.autoclick_generate_random_button)
|
||||||
|
|
||||||
|
autoclickCheckbox.isChecked = Prefs.autoclickEnabled
|
||||||
|
nameInput.setText(Prefs.autoclickName)
|
||||||
|
|
||||||
|
generateButton.setOnClickListener {
|
||||||
|
val names = requireContext().assets.open("names.txt").bufferedReader().readLines()
|
||||||
|
val randomName = names.random()
|
||||||
|
nameInput.setText(randomName)
|
||||||
|
}
|
||||||
|
|
||||||
|
AlertDialog.Builder(requireContext())
|
||||||
|
.setTitle(R.string.autoclick_settings_title)
|
||||||
|
.setView(dialogLayout)
|
||||||
|
.setPositiveButton(android.R.string.ok) { _, _ ->
|
||||||
|
Prefs.autoclickEnabled = autoclickCheckbox.isChecked
|
||||||
|
Prefs.autoclickName = nameInput.text.toString()
|
||||||
|
}
|
||||||
|
.setNegativeButton(android.R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val TAG = "SettingsDialogFragment"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,198 +0,0 @@
|
|||||||
package bypass.whitelist.ui
|
|
||||||
|
|
||||||
import android.content.pm.ApplicationInfo
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.view.View
|
|
||||||
import android.widget.CheckBox
|
|
||||||
import android.widget.LinearLayout
|
|
||||||
import android.widget.ListView
|
|
||||||
import android.widget.PopupMenu
|
|
||||||
import android.widget.Toast
|
|
||||||
import androidx.appcompat.app.AlertDialog
|
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
|
||||||
import bypass.whitelist.R
|
|
||||||
import bypass.whitelist.tunnel.SplitTunnelingMode
|
|
||||||
import bypass.whitelist.tunnel.TunnelMode
|
|
||||||
import bypass.whitelist.tunnel.TunnelVpnService
|
|
||||||
import bypass.whitelist.util.Callback
|
|
||||||
import bypass.whitelist.util.ParamCallback
|
|
||||||
import bypass.whitelist.util.Prefs
|
|
||||||
|
|
||||||
class SettingsMenuController(
|
|
||||||
private val activity: AppCompatActivity,
|
|
||||||
private val onModeChanged: ParamCallback<TunnelMode>,
|
|
||||||
private val onShareLogs: Callback,
|
|
||||||
private val onReset: Callback,
|
|
||||||
) {
|
|
||||||
var tunnelMode: TunnelMode = Prefs.tunnelMode
|
|
||||||
var splitTunnelingMode: SplitTunnelingMode = Prefs.splitTunnelingMode
|
|
||||||
var splitTunnelingPackages: MutableSet<String> = Prefs.splitTunnelingPackages.toMutableSet()
|
|
||||||
var showLogs: Boolean = Prefs.showLogs
|
|
||||||
|
|
||||||
var onShowLogsChanged: ParamCallback<Boolean> = {}
|
|
||||||
|
|
||||||
private enum class MenuItem(val id: Int, val stringRes: Int) {
|
|
||||||
MODE(99, R.string.menu_tunnel),
|
|
||||||
SPLIT_TUNNELING(98, R.string.menu_split_tunneling),
|
|
||||||
SPLIT_TUNNELING_APPS(97, R.string.menu_split_tunneling_manage),
|
|
||||||
RECONNECT_ON_START(100, R.string.menu_reconnect_on_start),
|
|
||||||
SHOW_LOGS(101, R.string.menu_show_logs),
|
|
||||||
SHARE_LOGS(102, R.string.menu_share_logs),
|
|
||||||
RESET(200, R.string.menu_reset),
|
|
||||||
}
|
|
||||||
|
|
||||||
fun show(anchor: View) {
|
|
||||||
val popup = PopupMenu(activity, anchor)
|
|
||||||
val menu = popup.menu
|
|
||||||
|
|
||||||
menu.add(0, MenuItem.MODE.id, 0, activity.getString(MenuItem.MODE.stringRes, tunnelMode.label))
|
|
||||||
menu.add(0, MenuItem.SPLIT_TUNNELING.id, 0, activity.getString(MenuItem.SPLIT_TUNNELING.stringRes, splitTunnelingMode.label))
|
|
||||||
menu.add(0, MenuItem.SPLIT_TUNNELING_APPS.id, 0, MenuItem.SPLIT_TUNNELING_APPS.stringRes).apply {
|
|
||||||
isEnabled = splitTunnelingMode != SplitTunnelingMode.NONE
|
|
||||||
}
|
|
||||||
menu.add(0, MenuItem.RECONNECT_ON_START.id, 0, MenuItem.RECONNECT_ON_START.stringRes).apply {
|
|
||||||
isCheckable = true
|
|
||||||
isChecked = Prefs.connectOnStart
|
|
||||||
}
|
|
||||||
menu.add(0, MenuItem.SHOW_LOGS.id, 0, MenuItem.SHOW_LOGS.stringRes).apply {
|
|
||||||
isCheckable = true
|
|
||||||
isChecked = showLogs
|
|
||||||
}
|
|
||||||
menu.add(0, MenuItem.SHARE_LOGS.id, 0, MenuItem.SHARE_LOGS.stringRes)
|
|
||||||
menu.add(0, MenuItem.RESET.id, 0, MenuItem.RESET.stringRes)
|
|
||||||
|
|
||||||
popup.setOnMenuItemClickListener { item ->
|
|
||||||
when (item.itemId) {
|
|
||||||
MenuItem.RECONNECT_ON_START.id -> {
|
|
||||||
Prefs.connectOnStart = !item.isChecked
|
|
||||||
true
|
|
||||||
}
|
|
||||||
MenuItem.SPLIT_TUNNELING.id -> {
|
|
||||||
showSplitTunnelingDialog()
|
|
||||||
true
|
|
||||||
}
|
|
||||||
MenuItem.SPLIT_TUNNELING_APPS.id -> {
|
|
||||||
showSplitTunnelingAppSelection()
|
|
||||||
true
|
|
||||||
}
|
|
||||||
MenuItem.SHOW_LOGS.id -> {
|
|
||||||
showLogs = !item.isChecked
|
|
||||||
Prefs.showLogs = showLogs
|
|
||||||
onShowLogsChanged(showLogs)
|
|
||||||
true
|
|
||||||
}
|
|
||||||
MenuItem.SHARE_LOGS.id -> {
|
|
||||||
onShareLogs()
|
|
||||||
true
|
|
||||||
}
|
|
||||||
MenuItem.RESET.id -> {
|
|
||||||
onReset()
|
|
||||||
true
|
|
||||||
}
|
|
||||||
MenuItem.MODE.id -> {
|
|
||||||
showModeDialog()
|
|
||||||
true
|
|
||||||
}
|
|
||||||
else -> false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
popup.show()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun showModeDialog() {
|
|
||||||
val modes = TunnelMode.entries
|
|
||||||
val labels = modes.map { it.label }.toTypedArray()
|
|
||||||
val current = modes.indexOf(tunnelMode)
|
|
||||||
AlertDialog.Builder(activity)
|
|
||||||
.setSingleChoiceItems(labels, current) { dialog, which ->
|
|
||||||
dialog.dismiss()
|
|
||||||
val mode = modes[which]
|
|
||||||
if (mode != tunnelMode) {
|
|
||||||
tunnelMode = mode
|
|
||||||
Prefs.tunnelMode = mode
|
|
||||||
onModeChanged(mode)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.show()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun showSplitTunnelingDialog() {
|
|
||||||
val modes = SplitTunnelingMode.entries.toTypedArray()
|
|
||||||
val labels = modes.map { it.label }.toTypedArray()
|
|
||||||
val selectedIndex = modes.indexOf(splitTunnelingMode)
|
|
||||||
|
|
||||||
AlertDialog.Builder(activity)
|
|
||||||
.setTitle(R.string.split_tunneling_mode_prompt)
|
|
||||||
.setSingleChoiceItems(labels, selectedIndex) { dialog, which ->
|
|
||||||
splitTunnelingMode = modes[which]
|
|
||||||
Prefs.splitTunnelingMode = splitTunnelingMode
|
|
||||||
dialog.dismiss()
|
|
||||||
if (TunnelVpnService.instance?.isRunning == true) {
|
|
||||||
Toast.makeText(activity, R.string.split_tunneling_mode_changed, Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.setNegativeButton(android.R.string.cancel, null)
|
|
||||||
.show()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun showSplitTunnelingAppSelection() {
|
|
||||||
var includeSystemApps = false
|
|
||||||
val pm = activity.packageManager
|
|
||||||
|
|
||||||
val installedApps = pm.getInstalledApplications(PackageManager.GET_META_DATA)
|
|
||||||
.filter { it.packageName != activity.packageName }
|
|
||||||
.mapNotNull { appInfo ->
|
|
||||||
val pkg = appInfo.packageName
|
|
||||||
if (pkg.isBlank()) return@mapNotNull null
|
|
||||||
val label = appInfo.loadLabel(pm).toString().takeIf { it.isNotBlank() } ?: pkg
|
|
||||||
SplitTunnelingAppItem(
|
|
||||||
pkg, label, pm.getApplicationIcon(pkg),
|
|
||||||
splitTunnelingPackages.contains(pkg),
|
|
||||||
(appInfo.flags and ApplicationInfo.FLAG_SYSTEM) == 0,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
.distinctBy { it.packageName }
|
|
||||||
.sortedWith(compareByDescending<SplitTunnelingAppItem> { it.isSelected }.thenBy { it.label.lowercase() })
|
|
||||||
|
|
||||||
fun buildAppList() = installedApps.filter { includeSystemApps || it.isUserApp }
|
|
||||||
|
|
||||||
val adapter = SplitTunnelingAdapter(activity.layoutInflater, splitTunnelingPackages)
|
|
||||||
adapter.items = buildAppList()
|
|
||||||
|
|
||||||
if (adapter.items.isEmpty()) return
|
|
||||||
|
|
||||||
val listView = ListView(activity).apply {
|
|
||||||
choiceMode = ListView.CHOICE_MODE_MULTIPLE
|
|
||||||
this.adapter = adapter
|
|
||||||
}
|
|
||||||
|
|
||||||
val systemAppsCheckbox = CheckBox(activity).apply {
|
|
||||||
text = activity.getString(R.string.split_tunneling_show_system_apps)
|
|
||||||
isChecked = includeSystemApps
|
|
||||||
setOnCheckedChangeListener { _, checked ->
|
|
||||||
includeSystemApps = checked
|
|
||||||
adapter.items = buildAppList()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val dialogLayout = LinearLayout(activity).apply {
|
|
||||||
orientation = LinearLayout.VERTICAL
|
|
||||||
setPadding(24, 24, 24, 24)
|
|
||||||
addView(systemAppsCheckbox)
|
|
||||||
addView(listView)
|
|
||||||
}
|
|
||||||
|
|
||||||
AlertDialog.Builder(activity)
|
|
||||||
.setTitle(R.string.split_tunneling_apps_prompt)
|
|
||||||
.setView(dialogLayout)
|
|
||||||
.setPositiveButton(android.R.string.ok) { _, _ ->
|
|
||||||
Prefs.splitTunnelingMode = splitTunnelingMode
|
|
||||||
Prefs.splitTunnelingPackages = splitTunnelingPackages
|
|
||||||
if (TunnelVpnService.instance?.isRunning == true) {
|
|
||||||
Toast.makeText(activity, R.string.split_tunneling_mode_changed, Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.setNegativeButton(android.R.string.cancel, null)
|
|
||||||
.show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,6 +7,7 @@ import bypass.whitelist.R
|
|||||||
import bypass.whitelist.tunnel.TunnelMode
|
import bypass.whitelist.tunnel.TunnelMode
|
||||||
import bypass.whitelist.tunnel.VpnStatus
|
import bypass.whitelist.tunnel.VpnStatus
|
||||||
import bypass.whitelist.util.Callback
|
import bypass.whitelist.util.Callback
|
||||||
|
import bypass.whitelist.util.Prefs
|
||||||
|
|
||||||
class StatusBarController(
|
class StatusBarController(
|
||||||
private val activity: AppCompatActivity,
|
private val activity: AppCompatActivity,
|
||||||
@@ -29,21 +30,33 @@ class StatusBarController(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun setStatus(status: VpnStatus) {
|
fun setStatus(status: VpnStatus) {
|
||||||
statusBar.text = activity.getString(R.string.status_format, tunnelMode.label, activity.getString(status.labelRes))
|
val label = if (status == VpnStatus.PORT_BUSY) {
|
||||||
|
activity.getString(status.labelRes, Prefs.socksPort)
|
||||||
|
} else {
|
||||||
|
activity.getString(status.labelRes)
|
||||||
|
}
|
||||||
|
statusBar.text = activity.getString(R.string.status_format, tunnelMode.label, label)
|
||||||
val colorRes = when (status) {
|
val colorRes = when (status) {
|
||||||
VpnStatus.TUNNEL_ACTIVE -> R.color.status_active
|
VpnStatus.TUNNEL_ACTIVE -> R.color.status_active
|
||||||
VpnStatus.CONNECTING,
|
VpnStatus.CONNECTING,
|
||||||
VpnStatus.CALL_CONNECTED,
|
VpnStatus.CALL_CONNECTED,
|
||||||
VpnStatus.DATACHANNEL_OPEN -> R.color.status_connecting
|
VpnStatus.DATACHANNEL_OPEN -> R.color.status_connecting
|
||||||
VpnStatus.TUNNEL_LOST,
|
VpnStatus.TUNNEL_LOST,
|
||||||
VpnStatus.DATACHANNEL_LOST -> R.color.status_warning
|
VpnStatus.DATACHANNEL_LOST,
|
||||||
|
VpnStatus.ACTION_REQUIRED_CAPTCHA -> R.color.status_warning
|
||||||
VpnStatus.CALL_DISCONNECTED,
|
VpnStatus.CALL_DISCONNECTED,
|
||||||
VpnStatus.CALL_FAILED -> R.color.status_error
|
VpnStatus.CALL_FAILED,
|
||||||
|
VpnStatus.PORT_BUSY -> R.color.status_error
|
||||||
VpnStatus.STARTING -> R.color.status_idle
|
VpnStatus.STARTING -> R.color.status_idle
|
||||||
}
|
}
|
||||||
statusBar.setBackgroundColor(activity.getColor(colorRes))
|
statusBar.setBackgroundColor(activity.getColor(colorRes))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun setStatusText(text: String) {
|
||||||
|
statusBar.text = text
|
||||||
|
statusBar.setBackgroundColor(activity.getColor(R.color.status_connecting))
|
||||||
|
}
|
||||||
|
|
||||||
fun setIdle() {
|
fun setIdle() {
|
||||||
statusBar.text = activity.getString(R.string.status_format, tunnelMode.label, activity.getString(R.string.status_idle))
|
statusBar.text = activity.getString(R.string.status_format, tunnelMode.label, activity.getString(R.string.status_idle))
|
||||||
statusBar.setBackgroundColor(activity.getColor(R.color.status_idle))
|
statusBar.setBackgroundColor(activity.getColor(R.color.status_idle))
|
||||||
|
|||||||
@@ -0,0 +1,159 @@
|
|||||||
|
package bypass.whitelist.ui
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.util.Log
|
||||||
|
import android.webkit.ConsoleMessage
|
||||||
|
import android.webkit.JavascriptInterface
|
||||||
|
import android.webkit.WebChromeClient
|
||||||
|
import android.webkit.WebResourceRequest
|
||||||
|
import android.webkit.WebResourceResponse
|
||||||
|
import android.webkit.WebView
|
||||||
|
import android.webkit.WebViewClient
|
||||||
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import bypass.whitelist.util.DESKTOP_USER_AGENT
|
||||||
|
import bypass.whitelist.util.ParamCallback
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.net.HttpURLConnection
|
||||||
|
import java.net.URL
|
||||||
|
|
||||||
|
@SuppressLint("SetJavaScriptEnabled")
|
||||||
|
class VkCaptchaWebView(
|
||||||
|
private val activity: AppCompatActivity,
|
||||||
|
private val webView: WebView,
|
||||||
|
private val onStatus: ParamCallback<String>,
|
||||||
|
private val onToken: ParamCallback<String>,
|
||||||
|
) {
|
||||||
|
|
||||||
|
private val authScript by lazy {
|
||||||
|
activity.assets.open("headless-auth-vk.js").bufferedReader().readText()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val authPageHTML = """
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
<iframe id="captcha" style="width:100%;height:100vh;border:none;display:none;"></iframe>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
private var pendingHTML: String? = null
|
||||||
|
private var pendingJoinLink = ""
|
||||||
|
private var pendingAnonName = ""
|
||||||
|
|
||||||
|
fun setup() {
|
||||||
|
webView.settings.apply {
|
||||||
|
javaScriptEnabled = true
|
||||||
|
domStorageEnabled = true
|
||||||
|
allowContentAccess = true
|
||||||
|
userAgentString = DESKTOP_USER_AGENT
|
||||||
|
}
|
||||||
|
|
||||||
|
webView.addJavascriptInterface(CaptchaBridge(), "AndroidBridge")
|
||||||
|
webView.addJavascriptInterface(AuthBridge(), "AndroidCaptchaBridge")
|
||||||
|
|
||||||
|
webView.webChromeClient = object : WebChromeClient() {
|
||||||
|
override fun onConsoleMessage(msg: ConsoleMessage): Boolean {
|
||||||
|
Log.d("CAPTCHA", "${msg.sourceId()?.takeLast(30)}:${msg.lineNumber()} ${msg.message()}")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
webView.webViewClient = object : WebViewClient() {
|
||||||
|
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
|
||||||
|
val url = request.url.toString()
|
||||||
|
if (url.contains("vk.com/blank.php") && pendingHTML != null) {
|
||||||
|
val html = pendingHTML!!
|
||||||
|
pendingHTML = null
|
||||||
|
return WebResourceResponse(
|
||||||
|
"text/html", "utf-8", 200, "OK",
|
||||||
|
mapOf("Access-Control-Allow-Origin" to "*"),
|
||||||
|
html.byteInputStream()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (url.contains("id.vk.com") || url.contains("okcdn.ru")) {
|
||||||
|
Log.d("CAPTCHA", "REQ: $url")
|
||||||
|
return stripHeaders(url, request)
|
||||||
|
}
|
||||||
|
if (url.contains("captchaNotRobot") || url.contains("captcha")) {
|
||||||
|
Log.d("CAPTCHA", "REQ: $url")
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPageFinished(view: WebView, url: String) {
|
||||||
|
if (!url.contains("blank.php")) return
|
||||||
|
view.evaluateJavascript("window.JOIN_LINK='${escapeJs(pendingJoinLink)}';window.ANON_NAME='${escapeJs(pendingAnonName)}';", null)
|
||||||
|
view.evaluateJavascript(authScript, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun start(joinLink: String, anonName: String) {
|
||||||
|
pendingJoinLink = joinLink
|
||||||
|
pendingAnonName = anonName
|
||||||
|
pendingHTML = authPageHTML
|
||||||
|
webView.loadUrl("https://vk.com/blank.php")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
inner class AuthBridge {
|
||||||
|
@JavascriptInterface
|
||||||
|
fun onJoined(json: String) {
|
||||||
|
Log.d("CAPTCHA", "onJoined: ${json.take(200)}")
|
||||||
|
onToken(json)
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun setStatus(message: String) {
|
||||||
|
Log.d("CAPTCHA", "status: $message")
|
||||||
|
activity.runOnUiThread { onStatus(message) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("unused", "FunctionName")
|
||||||
|
inner class CaptchaBridge {
|
||||||
|
@JavascriptInterface
|
||||||
|
fun VKCaptchaGetResult(json: String) {
|
||||||
|
Log.d("CAPTCHA", "VKCaptchaGetResult: ${json.take(200)}")
|
||||||
|
val token = try {
|
||||||
|
JSONObject(json).getString("token")
|
||||||
|
} catch (e: Exception) { json }
|
||||||
|
webView.post {
|
||||||
|
webView.evaluateJavascript("if(typeof retryCaptcha==='function')retryCaptcha('${token.replace("'", "\\'")}');", null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun VKCaptchaClose(json: String) {
|
||||||
|
Log.d("CAPTCHA", "VKCaptchaClose: $json")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun escapeJs(value: String): String =
|
||||||
|
value.replace("\\", "\\\\").replace("'", "\\'").replace("\n", "\\n")
|
||||||
|
|
||||||
|
private fun stripHeaders(url: String, request: WebResourceRequest): WebResourceResponse? {
|
||||||
|
return try {
|
||||||
|
val conn = URL(url).openConnection() as HttpURLConnection
|
||||||
|
conn.requestMethod = request.method ?: "GET"
|
||||||
|
request.requestHeaders?.forEach { (key, value) -> conn.setRequestProperty(key, value) }
|
||||||
|
val headers = mutableMapOf<String, String>()
|
||||||
|
conn.headerFields?.forEach { (key, values) ->
|
||||||
|
if (key != null
|
||||||
|
&& !key.equals("content-security-policy", ignoreCase = true)
|
||||||
|
&& !key.equals("content-security-policy-report-only", ignoreCase = true)
|
||||||
|
&& !key.equals("x-frame-options", ignoreCase = true)
|
||||||
|
) {
|
||||||
|
headers[key] = values.joinToString(", ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
headers["Access-Control-Allow-Origin"] = "*"
|
||||||
|
WebResourceResponse(
|
||||||
|
conn.contentType?.split(";")?.firstOrNull() ?: "text/html",
|
||||||
|
"utf-8", conn.responseCode, conn.responseMessage ?: "OK",
|
||||||
|
headers, conn.inputStream
|
||||||
|
)
|
||||||
|
} catch (_: Exception) { null }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,178 +0,0 @@
|
|||||||
package bypass.whitelist.ui
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.graphics.Bitmap
|
|
||||||
import android.util.Log
|
|
||||||
import android.view.View
|
|
||||||
import android.webkit.ConsoleMessage
|
|
||||||
import android.webkit.PermissionRequest
|
|
||||||
import android.webkit.WebChromeClient
|
|
||||||
import android.webkit.WebResourceRequest
|
|
||||||
import android.webkit.WebResourceResponse
|
|
||||||
import android.webkit.WebView
|
|
||||||
import android.webkit.WebViewClient
|
|
||||||
import android.widget.ImageView
|
|
||||||
import android.widget.TextView
|
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
|
||||||
import bypass.whitelist.R
|
|
||||||
import bypass.whitelist.tunnel.CallPlatform
|
|
||||||
import bypass.whitelist.tunnel.TunnelMode
|
|
||||||
import bypass.whitelist.tunnel.VpnStatus
|
|
||||||
import bypass.whitelist.util.ParamCallback
|
|
||||||
import bypass.whitelist.util.maskUrl
|
|
||||||
|
|
||||||
private data class HookKey(val isPion: Boolean, val platform: CallPlatform)
|
|
||||||
|
|
||||||
class WebViewManager(
|
|
||||||
private val activity: AppCompatActivity,
|
|
||||||
private val webView: WebView,
|
|
||||||
private val toggleButton: View,
|
|
||||||
private val toggleArrow: ImageView,
|
|
||||||
private val toggleLabel: TextView,
|
|
||||||
private val onLog: ParamCallback<String>,
|
|
||||||
private val onStatus: ParamCallback<VpnStatus>,
|
|
||||||
) {
|
|
||||||
var tunnelMode: TunnelMode = TunnelMode.DC
|
|
||||||
private var expanded = false
|
|
||||||
private var callUrl = ""
|
|
||||||
|
|
||||||
private val hooks = mapOf(
|
|
||||||
HookKey(false, CallPlatform.VK) to lazy { loadAsset("dc-joiner-vk.js") },
|
|
||||||
HookKey(false, CallPlatform.TELEMOST) to lazy { loadAsset("dc-joiner-telemost.js") },
|
|
||||||
HookKey(true, CallPlatform.VK) to lazy { loadAsset("video-vk.js") },
|
|
||||||
HookKey(true, CallPlatform.TELEMOST) to lazy { loadAsset("video-telemost.js") },
|
|
||||||
)
|
|
||||||
|
|
||||||
private val autoclickers = mapOf(
|
|
||||||
CallPlatform.VK to lazy { loadAsset("autoclick-vk.js") },
|
|
||||||
CallPlatform.TELEMOST to lazy { loadAsset("autoclick-telemost.js") },
|
|
||||||
)
|
|
||||||
|
|
||||||
private val muteAudioContext by lazy { loadAsset("mute-audio-context.js") }
|
|
||||||
|
|
||||||
private fun loadAsset(name: String): String =
|
|
||||||
activity.assets.open(name).bufferedReader().readText()
|
|
||||||
|
|
||||||
private fun setExpanded(value: Boolean) {
|
|
||||||
expanded = value
|
|
||||||
webView.visibility = if (value) View.VISIBLE else View.GONE
|
|
||||||
toggleArrow.rotation = if (value) 180f else 0f
|
|
||||||
toggleLabel.setText(if (value) R.string.collapse_webview else R.string.expand_webview)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun collapse() {
|
|
||||||
setExpanded(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressLint("SetJavaScriptEnabled")
|
|
||||||
fun setup(jsBridge: Any) {
|
|
||||||
toggleButton.setOnClickListener { setExpanded(!expanded) }
|
|
||||||
webView.settings.apply {
|
|
||||||
javaScriptEnabled = true
|
|
||||||
domStorageEnabled = true
|
|
||||||
mediaPlaybackRequiresUserGesture = false
|
|
||||||
allowContentAccess = true
|
|
||||||
allowFileAccess = true
|
|
||||||
databaseEnabled = true
|
|
||||||
setSupportMultipleWindows(false)
|
|
||||||
useWideViewPort = true
|
|
||||||
loadWithOverviewMode = true
|
|
||||||
builtInZoomControls = true
|
|
||||||
displayZoomControls = false
|
|
||||||
userAgentString = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
|
||||||
}
|
|
||||||
|
|
||||||
webView.addJavascriptInterface(jsBridge, "AndroidBridge")
|
|
||||||
|
|
||||||
webView.webChromeClient = object : WebChromeClient() {
|
|
||||||
override fun onPermissionRequest(request: PermissionRequest) {
|
|
||||||
activity.runOnUiThread { request.grant(request.resources) }
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onConsoleMessage(msg: ConsoleMessage): Boolean {
|
|
||||||
val text = msg.message()
|
|
||||||
Log.d("HOOK", text)
|
|
||||||
if (text.contains("[HOOK]")) {
|
|
||||||
onLog(text)
|
|
||||||
when {
|
|
||||||
text.contains("CALL CONNECTED") -> onStatus(VpnStatus.CALL_CONNECTED)
|
|
||||||
text.contains("DataChannel open") -> onStatus(VpnStatus.DATACHANNEL_OPEN)
|
|
||||||
text.contains("DataChannel closed") -> onStatus(VpnStatus.DATACHANNEL_LOST)
|
|
||||||
text.contains("WebSocket connected") -> onStatus(VpnStatus.TUNNEL_ACTIVE)
|
|
||||||
text.contains("WebSocket disconnected") -> onStatus(VpnStatus.TUNNEL_LOST)
|
|
||||||
text.contains("Connection state: connecting") -> onStatus(VpnStatus.CONNECTING)
|
|
||||||
text.contains("Connection state: disconnected") -> onStatus(VpnStatus.CALL_DISCONNECTED)
|
|
||||||
text.contains("Connection state: failed") -> onStatus(VpnStatus.CALL_FAILED)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
webView.webViewClient = object : WebViewClient() {
|
|
||||||
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
|
|
||||||
val url = request.url.toString()
|
|
||||||
val platform = CallPlatform.fromUrl(url)
|
|
||||||
if (platform != CallPlatform.TELEMOST || !url.contains("/j/") || request.method != "GET") return null
|
|
||||||
return stripCsp(url, request)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
|
|
||||||
if (url.contains("about:blank")) return
|
|
||||||
view.evaluateJavascript(muteAudioContext, null)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onPageFinished(view: WebView, url: String) {
|
|
||||||
if (url.contains("about:blank")) return
|
|
||||||
if (!expanded && url != callUrl) activity.runOnUiThread { setExpanded(true) }
|
|
||||||
view.evaluateJavascript("!!window.__hookInstalled") { result ->
|
|
||||||
if (result == "true") {
|
|
||||||
Log.d("HOOK", "Hook already injected, skipping")
|
|
||||||
return@evaluateJavascript
|
|
||||||
}
|
|
||||||
val platform = CallPlatform.fromUrl(url)
|
|
||||||
onLog("Page loaded, injecting hook for ${maskUrl(url)}")
|
|
||||||
view.evaluateJavascript("window.WS_PORT=${mobile.Mobile.activeWsPort()}", null)
|
|
||||||
view.evaluateJavascript(hookForPlatform(platform), null)
|
|
||||||
onLog("Injecting autoclick for ${maskUrl(url)}")
|
|
||||||
view.evaluateJavascript(autoclickers[platform]!!.value, null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun loadUrl(url: String) {
|
|
||||||
callUrl = url
|
|
||||||
webView.loadUrl(url)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun loadBlank() {
|
|
||||||
callUrl = ""
|
|
||||||
webView.loadUrl("about:blank")
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun hookForPlatform(platform: CallPlatform): String =
|
|
||||||
hooks[HookKey(tunnelMode.isPion, platform)]!!.value
|
|
||||||
|
|
||||||
private fun stripCsp(url: String, request: WebResourceRequest): WebResourceResponse? {
|
|
||||||
return try {
|
|
||||||
val conn = java.net.URL(url).openConnection() as java.net.HttpURLConnection
|
|
||||||
conn.requestMethod = "GET"
|
|
||||||
request.requestHeaders?.forEach { (k, v) -> conn.setRequestProperty(k, v) }
|
|
||||||
val headers = mutableMapOf<String, String>()
|
|
||||||
conn.headerFields?.forEach { (k, v) ->
|
|
||||||
if (k != null
|
|
||||||
&& !k.equals("content-security-policy", ignoreCase = true)
|
|
||||||
&& !k.equals("content-security-policy-report-only", ignoreCase = true)
|
|
||||||
) {
|
|
||||||
headers[k] = v.joinToString(", ")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
WebResourceResponse(
|
|
||||||
conn.contentType?.split(";")?.firstOrNull() ?: "text/html",
|
|
||||||
"utf-8", conn.responseCode, conn.responseMessage ?: "OK",
|
|
||||||
headers, conn.inputStream
|
|
||||||
)
|
|
||||||
} catch (_: Exception) { null }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,36 @@
|
|||||||
package bypass.whitelist.util
|
package bypass.whitelist.util
|
||||||
|
|
||||||
|
import java.security.SecureRandom
|
||||||
|
|
||||||
object Ports {
|
object Ports {
|
||||||
const val SOCKS = 1080L
|
const val DEFAULT_SOCKS = 1080L
|
||||||
const val DC_WS = 9000L
|
const val DC_WS = 9000L
|
||||||
const val PION_SIGNALING = 9001L
|
const val PION_SIGNALING = 9001L
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum class SocksAuthMode { AUTO, MANUAL }
|
||||||
|
|
||||||
|
object SocksAuth {
|
||||||
|
private val autoUser: String
|
||||||
|
private val autoPass: String
|
||||||
|
|
||||||
|
init {
|
||||||
|
val random = SecureRandom()
|
||||||
|
val chars = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||||
|
fun randomString(length: Int) = buildString {
|
||||||
|
repeat(length) { append(chars[random.nextInt(chars.length)]) }
|
||||||
|
}
|
||||||
|
autoUser = randomString(16)
|
||||||
|
autoPass = randomString(24)
|
||||||
|
}
|
||||||
|
|
||||||
|
val user: String
|
||||||
|
get() = if (Prefs.socksAuthMode == SocksAuthMode.MANUAL) Prefs.socksUser else autoUser
|
||||||
|
|
||||||
|
val pass: String
|
||||||
|
get() = if (Prefs.socksAuthMode == SocksAuthMode.MANUAL) Prefs.socksPass else autoPass
|
||||||
|
}
|
||||||
|
|
||||||
object PrefsKeys {
|
object PrefsKeys {
|
||||||
const val CONNECT_ON_START = "connect_on_start"
|
const val CONNECT_ON_START = "connect_on_start"
|
||||||
const val URL = "url"
|
const val URL = "url"
|
||||||
@@ -13,8 +38,20 @@ object PrefsKeys {
|
|||||||
const val SHOW_LOGS = "show_logs"
|
const val SHOW_LOGS = "show_logs"
|
||||||
const val SPLIT_TUNNELING_MODE = "split_tunneling_mode"
|
const val SPLIT_TUNNELING_MODE = "split_tunneling_mode"
|
||||||
const val SPLIT_TUNNELING_PACKAGES = "split_tunneling_packages"
|
const val SPLIT_TUNNELING_PACKAGES = "split_tunneling_packages"
|
||||||
|
const val AUTOCLICK_ENABLED = "autoclick_enabled"
|
||||||
|
const val AUTOCLICK_NAME = "autoclick_name"
|
||||||
|
const val HEADLESS = "headless"
|
||||||
|
const val SOCKS_PORT = "socks_port"
|
||||||
|
const val SOCKS_AUTH_MODE = "socks_auth_mode"
|
||||||
|
const val SOCKS_USER = "socks_user"
|
||||||
|
const val SOCKS_PASS = "socks_pass"
|
||||||
|
const val PROXY_ONLY = "proxy_only"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const val BLANK_URL = "about:blank"
|
||||||
|
|
||||||
|
const val DESKTOP_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
||||||
|
|
||||||
object Vpn {
|
object Vpn {
|
||||||
const val ADDRESS = "10.0.0.2"
|
const val ADDRESS = "10.0.0.2"
|
||||||
const val PREFIX_LENGTH = 32
|
const val PREFIX_LENGTH = 32
|
||||||
|
|||||||
@@ -51,4 +51,43 @@ object Prefs {
|
|||||||
var splitTunnelingPackages: Set<String>
|
var splitTunnelingPackages: Set<String>
|
||||||
get() = prefs.getStringSet(PrefsKeys.SPLIT_TUNNELING_PACKAGES, emptySet()) ?: emptySet()
|
get() = prefs.getStringSet(PrefsKeys.SPLIT_TUNNELING_PACKAGES, emptySet()) ?: emptySet()
|
||||||
set(value) = prefs.edit { putStringSet(PrefsKeys.SPLIT_TUNNELING_PACKAGES, value) }
|
set(value) = prefs.edit { putStringSet(PrefsKeys.SPLIT_TUNNELING_PACKAGES, value) }
|
||||||
|
|
||||||
|
var autoclickEnabled: Boolean
|
||||||
|
get() = prefs.getBoolean(PrefsKeys.AUTOCLICK_ENABLED, true)
|
||||||
|
set(value) = prefs.edit { putBoolean(PrefsKeys.AUTOCLICK_ENABLED, value) }
|
||||||
|
|
||||||
|
var autoclickName: String
|
||||||
|
get() = prefs.getString(PrefsKeys.AUTOCLICK_NAME, "Hello")!!
|
||||||
|
set(value) = prefs.edit { putString(PrefsKeys.AUTOCLICK_NAME, value) }
|
||||||
|
|
||||||
|
var headless: Boolean
|
||||||
|
get() = prefs.getBoolean(PrefsKeys.HEADLESS, true)
|
||||||
|
set(value) = prefs.edit { putBoolean(PrefsKeys.HEADLESS, value) }
|
||||||
|
|
||||||
|
var socksPort: Long
|
||||||
|
get() = prefs.getLong(PrefsKeys.SOCKS_PORT, Ports.DEFAULT_SOCKS)
|
||||||
|
set(value) = prefs.edit { putLong(PrefsKeys.SOCKS_PORT, value) }
|
||||||
|
|
||||||
|
var socksAuthMode: SocksAuthMode
|
||||||
|
get() {
|
||||||
|
val name = prefs.getString(PrefsKeys.SOCKS_AUTH_MODE, SocksAuthMode.AUTO.name)!!
|
||||||
|
return try {
|
||||||
|
SocksAuthMode.valueOf(name)
|
||||||
|
} catch (_: IllegalArgumentException) {
|
||||||
|
SocksAuthMode.AUTO
|
||||||
|
}
|
||||||
|
}
|
||||||
|
set(value) = prefs.edit { putString(PrefsKeys.SOCKS_AUTH_MODE, value.name) }
|
||||||
|
|
||||||
|
var socksUser: String
|
||||||
|
get() = prefs.getString(PrefsKeys.SOCKS_USER, "")!!
|
||||||
|
set(value) = prefs.edit { putString(PrefsKeys.SOCKS_USER, value) }
|
||||||
|
|
||||||
|
var socksPass: String
|
||||||
|
get() = prefs.getString(PrefsKeys.SOCKS_PASS, "")!!
|
||||||
|
set(value) = prefs.edit { putString(PrefsKeys.SOCKS_PASS, value) }
|
||||||
|
|
||||||
|
var proxyOnly: Boolean
|
||||||
|
get() = prefs.getBoolean(PrefsKeys.PROXY_ONLY, false)
|
||||||
|
set(value) = prefs.edit { putBoolean(PrefsKeys.PROXY_ONLY, value) }
|
||||||
}
|
}
|
||||||
Binary file not shown.
Binary file not shown.
@@ -97,46 +97,10 @@
|
|||||||
app:tint="#888888" />
|
app:tint="#888888" />
|
||||||
</FrameLayout>
|
</FrameLayout>
|
||||||
|
|
||||||
<LinearLayout
|
<FrameLayout
|
||||||
android:id="@+id/webViewContainer"
|
android:id="@+id/joinFragmentContainer"
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
android:layout_height="0dp"
|
android:layout_height="0dp"
|
||||||
android:layout_weight="1"
|
android:layout_weight="1" />
|
||||||
android:orientation="vertical">
|
|
||||||
|
|
||||||
<LinearLayout
|
|
||||||
android:id="@+id/toggleWebViewButton"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:background="?attr/selectableItemBackground"
|
|
||||||
android:gravity="center"
|
|
||||||
android:orientation="horizontal"
|
|
||||||
android:paddingVertical="6dp">
|
|
||||||
|
|
||||||
<ImageView
|
|
||||||
android:id="@+id/toggleWebViewArrow"
|
|
||||||
android:layout_width="16dp"
|
|
||||||
android:layout_height="16dp"
|
|
||||||
android:src="@drawable/ic_arrow_down"
|
|
||||||
app:tint="?android:attr/textColorPrimary" />
|
|
||||||
|
|
||||||
<TextView
|
|
||||||
android:id="@+id/toggleWebViewLabel"
|
|
||||||
android:layout_width="wrap_content"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:layout_marginStart="6dp"
|
|
||||||
android:text="@string/expand_webview"
|
|
||||||
android:textSize="13sp" />
|
|
||||||
|
|
||||||
</LinearLayout>
|
|
||||||
|
|
||||||
<WebView
|
|
||||||
android:id="@+id/webView"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="0dp"
|
|
||||||
android:layout_weight="1"
|
|
||||||
android:visibility="gone" />
|
|
||||||
|
|
||||||
</LinearLayout>
|
|
||||||
|
|
||||||
</LinearLayout>
|
</LinearLayout>
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:padding="12dp">
|
||||||
|
|
||||||
|
<CheckBox
|
||||||
|
android:id="@+id/autoclick_checkbox"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/autoclick_checkbox" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="8dp"
|
||||||
|
android:text="@string/autoclick_name_input_hint"
|
||||||
|
android:textSize="14sp" />
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/autoclick_name_input"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:hint="@string/autoclick_name_input_hint" />
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/autoclick_generate_random_button"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_gravity="end"
|
||||||
|
android:text="@string/autoclick_generate_random" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:padding="12dp">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/proxy_port_label"
|
||||||
|
android:textSize="14sp" />
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/proxyPortInput"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:inputType="number"
|
||||||
|
android:hint="1080" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="12dp"
|
||||||
|
android:text="@string/proxy_auth_mode_label"
|
||||||
|
android:textSize="14sp" />
|
||||||
|
|
||||||
|
<RadioGroup
|
||||||
|
android:id="@+id/authModeGroup"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal">
|
||||||
|
|
||||||
|
<RadioButton
|
||||||
|
android:id="@+id/authModeAuto"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/proxy_auth_auto" />
|
||||||
|
|
||||||
|
<RadioButton
|
||||||
|
android:id="@+id/authModeManual"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginStart="16dp"
|
||||||
|
android:text="@string/proxy_auth_manual" />
|
||||||
|
|
||||||
|
</RadioGroup>
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:id="@+id/manualAuthContainer"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:visibility="gone">
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/proxyUserInput"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:hint="@string/proxy_username_hint"
|
||||||
|
android:inputType="text" />
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/proxyPassInput"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:hint="@string/proxy_password_hint"
|
||||||
|
android:inputType="textPassword" />
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/copyProxyButton"
|
||||||
|
style="?android:attr/buttonBarButtonStyle"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_gravity="end"
|
||||||
|
android:text="@string/proxy_copy" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<View
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="1dp"
|
||||||
|
android:layout_marginVertical="8dp"
|
||||||
|
android:background="?android:attr/listDivider" />
|
||||||
|
|
||||||
|
<CheckBox
|
||||||
|
android:id="@+id/proxyOnlyCheckbox"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/proxy_only_label" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent" />
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:id="@+id/captchaWebView"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent" />
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
android:orientation="vertical">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:id="@+id/toggleWebViewButton"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:background="?attr/selectableItemBackground"
|
||||||
|
android:gravity="center"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:paddingVertical="6dp">
|
||||||
|
|
||||||
|
<ImageView
|
||||||
|
android:id="@+id/toggleWebViewArrow"
|
||||||
|
android:layout_width="16dp"
|
||||||
|
android:layout_height="16dp"
|
||||||
|
android:src="@drawable/ic_arrow_down"
|
||||||
|
app:tint="?android:attr/textColorPrimary" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/toggleWebViewLabel"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginStart="6dp"
|
||||||
|
android:text="@string/expand_webview"
|
||||||
|
android:textSize="13sp" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<WebView
|
||||||
|
android:id="@+id/webView"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="0dp"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:visibility="gone" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="vertical">
|
||||||
|
|
||||||
|
<ScrollView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:paddingTop="8dp">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="vertical">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/tunnelModeItem"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:background="?attr/selectableItemBackground"
|
||||||
|
android:paddingHorizontal="24dp"
|
||||||
|
android:paddingVertical="14dp"
|
||||||
|
android:textSize="16sp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/splitTunnelingItem"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:background="?attr/selectableItemBackground"
|
||||||
|
android:paddingHorizontal="24dp"
|
||||||
|
android:paddingVertical="14dp"
|
||||||
|
android:textSize="16sp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/splitTunnelingAppsItem"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:background="?attr/selectableItemBackground"
|
||||||
|
android:paddingHorizontal="24dp"
|
||||||
|
android:paddingVertical="14dp"
|
||||||
|
android:text="@string/menu_split_tunneling_manage"
|
||||||
|
android:textSize="16sp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/proxyItem"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:background="?attr/selectableItemBackground"
|
||||||
|
android:paddingHorizontal="24dp"
|
||||||
|
android:paddingVertical="14dp"
|
||||||
|
android:text="@string/menu_proxy_settings"
|
||||||
|
android:textSize="16sp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/autoclickItem"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:background="?attr/selectableItemBackground"
|
||||||
|
android:paddingHorizontal="24dp"
|
||||||
|
android:paddingVertical="14dp"
|
||||||
|
android:text="@string/menu_autoclick_settings"
|
||||||
|
android:textSize="16sp" />
|
||||||
|
|
||||||
|
<View
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="1dp"
|
||||||
|
android:layout_marginVertical="4dp"
|
||||||
|
android:background="?android:attr/listDivider" />
|
||||||
|
|
||||||
|
<CheckBox
|
||||||
|
android:id="@+id/headlessCheckbox"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginStart="20dp"
|
||||||
|
android:paddingStart="8dp"
|
||||||
|
android:paddingEnd="24dp"
|
||||||
|
android:paddingVertical="10dp"
|
||||||
|
android:text="@string/menu_headless"
|
||||||
|
android:textSize="16sp" />
|
||||||
|
|
||||||
|
<CheckBox
|
||||||
|
android:id="@+id/reconnectOnStartCheckbox"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginStart="20dp"
|
||||||
|
android:paddingStart="8dp"
|
||||||
|
android:paddingEnd="24dp"
|
||||||
|
android:paddingVertical="10dp"
|
||||||
|
android:text="@string/menu_reconnect_on_start"
|
||||||
|
android:textSize="16sp" />
|
||||||
|
|
||||||
|
<CheckBox
|
||||||
|
android:id="@+id/showLogsCheckbox"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginStart="20dp"
|
||||||
|
android:paddingStart="8dp"
|
||||||
|
android:paddingEnd="24dp"
|
||||||
|
android:paddingVertical="10dp"
|
||||||
|
android:text="@string/menu_show_logs"
|
||||||
|
android:textSize="16sp" />
|
||||||
|
|
||||||
|
<View
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="1dp"
|
||||||
|
android:layout_marginVertical="4dp"
|
||||||
|
android:background="?android:attr/listDivider" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/shareLogsItem"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:background="?attr/selectableItemBackground"
|
||||||
|
android:paddingHorizontal="24dp"
|
||||||
|
android:paddingVertical="14dp"
|
||||||
|
android:text="@string/menu_share_logs"
|
||||||
|
android:textSize="16sp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/resetItem"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:background="?attr/selectableItemBackground"
|
||||||
|
android:paddingHorizontal="24dp"
|
||||||
|
android:paddingVertical="14dp"
|
||||||
|
android:text="@string/menu_reset"
|
||||||
|
android:textSize="16sp" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
|
</ScrollView>
|
||||||
|
|
||||||
|
<View
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="1dp"
|
||||||
|
android:background="?android:attr/listDivider" />
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/closeButton"
|
||||||
|
style="?android:attr/buttonBarButtonStyle"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/settings_close"
|
||||||
|
android:textSize="16sp" />
|
||||||
|
|
||||||
|
</LinearLayout>
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:padding="6dp">
|
||||||
|
|
||||||
|
<ProgressBar
|
||||||
|
android:id="@+id/loading_progress_bar"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_gravity="center"
|
||||||
|
android:visibility="gone" />
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:id="@+id/app_list_container"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:visibility="gone">
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/search_input"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:hint="@string/split_tunneling_search_apps_hint"
|
||||||
|
android:singleLine="true" />
|
||||||
|
|
||||||
|
<CheckBox
|
||||||
|
android:id="@+id/system_apps_checkbox"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/split_tunneling_show_system_apps" />
|
||||||
|
|
||||||
|
<ListView
|
||||||
|
android:id="@+id/app_list_view"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
android:choiceMode="multipleChoice" />
|
||||||
|
</LinearLayout>
|
||||||
|
</LinearLayout>
|
||||||
@@ -12,10 +12,16 @@
|
|||||||
<string name="menu_tunnel">Tunnel: %1$s</string>
|
<string name="menu_tunnel">Tunnel: %1$s</string>
|
||||||
<string name="menu_split_tunneling">Split tunneling (%1$s)</string>
|
<string name="menu_split_tunneling">Split tunneling (%1$s)</string>
|
||||||
<string name="menu_split_tunneling_manage">Manage split tunneling apps</string>
|
<string name="menu_split_tunneling_manage">Manage split tunneling apps</string>
|
||||||
|
<string name="menu_autoclick_settings">Autoclick settings</string>
|
||||||
|
<string name="autoclick_settings_title">Autoclick settings</string>
|
||||||
|
<string name="autoclick_checkbox">Autoclick</string>
|
||||||
|
<string name="autoclick_name_input_hint">Autofill name</string>
|
||||||
|
<string name="autoclick_generate_random">Random</string>
|
||||||
<string name="split_tunneling_mode_prompt">Split tunneling mode</string>
|
<string name="split_tunneling_mode_prompt">Split tunneling mode</string>
|
||||||
<string name="split_tunneling_apps_prompt">Select apps</string>
|
<string name="split_tunneling_apps_prompt">Select apps</string>
|
||||||
<string name="split_tunneling_show_system_apps">Show system apps</string>
|
<string name="split_tunneling_show_system_apps">Show system apps</string>
|
||||||
<string name="split_tunneling_mode_changed">Reconnect for changes to take effect</string>
|
<string name="split_tunneling_mode_changed">Reconnect for changes to take effect</string>
|
||||||
|
<string name="split_tunneling_search_apps_hint">Search</string>
|
||||||
<string name="hint_call_link">Paste call link</string>
|
<string name="hint_call_link">Paste call link</string>
|
||||||
<string name="cd_clear">Clear</string>
|
<string name="cd_clear">Clear</string>
|
||||||
<string name="cd_settings">Settings</string>
|
<string name="cd_settings">Settings</string>
|
||||||
@@ -30,4 +36,22 @@
|
|||||||
<string name="vpn_tunnel_lost">Tunnel lost, reconnecting…</string>
|
<string name="vpn_tunnel_lost">Tunnel lost, reconnecting…</string>
|
||||||
<string name="vpn_call_disconnected">Call disconnected</string>
|
<string name="vpn_call_disconnected">Call disconnected</string>
|
||||||
<string name="vpn_call_failed">Call failed</string>
|
<string name="vpn_call_failed">Call failed</string>
|
||||||
|
<string name="vpn_port_busy">Port %1$d busy</string>
|
||||||
|
<string name="action_required_captcha">Action required (captcha)</string>
|
||||||
|
<string name="menu_headless">Headless</string>
|
||||||
|
<string name="menu_proxy_settings">Proxy settings</string>
|
||||||
|
<string name="proxy_settings_title">Proxy</string>
|
||||||
|
<string name="proxy_port_label">SOCKS5 port</string>
|
||||||
|
<string name="proxy_auth_mode_label">Authentication</string>
|
||||||
|
<string name="proxy_auth_auto">Auto</string>
|
||||||
|
<string name="proxy_auth_manual">Manual</string>
|
||||||
|
<string name="proxy_username_hint">Username</string>
|
||||||
|
<string name="proxy_password_hint">Password</string>
|
||||||
|
<string name="proxy_copy">Copy proxy URL</string>
|
||||||
|
<string name="proxy_copied">Copied to clipboard</string>
|
||||||
|
<string name="proxy_only_label">Proxy only (no VPN)</string>
|
||||||
|
<string name="notification_vpn_title">VPN active</string>
|
||||||
|
<string name="notification_proxy_title">Proxy active</string>
|
||||||
|
<string name="notification_disconnect">Disconnect</string>
|
||||||
|
<string name="settings_close">Close</string>
|
||||||
</resources>
|
</resources>
|
||||||
+1
-1
@@ -7,7 +7,7 @@ cd "$ROOT/android-app"
|
|||||||
[ -f "./gradlew" ] || { echo "gradlew not found"; exit 1; }
|
[ -f "./gradlew" ] || { echo "gradlew not found"; exit 1; }
|
||||||
|
|
||||||
echo "Cleaning..."
|
echo "Cleaning..."
|
||||||
find app/build -name .DS_Store -delete 2>/dev/null
|
find app/build -name .DS_Store -delete 2>/dev/null || true # dont fail trying to clean last build!
|
||||||
./gradlew clean 2>&1 | tail -3
|
./gradlew clean 2>&1 | tail -3
|
||||||
|
|
||||||
echo "Building APK..."
|
echo "Building APK..."
|
||||||
|
|||||||
+49
-20
@@ -4,8 +4,9 @@ set -e
|
|||||||
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||||
RELAY_DIR="$ROOT/relay"
|
RELAY_DIR="$ROOT/relay"
|
||||||
CREATOR_DIR="$ROOT/creator-app"
|
CREATOR_DIR="$ROOT/creator-app"
|
||||||
|
|
||||||
HEADLESS_DIR="$ROOT/headless"
|
HEADLESS_DIR="$ROOT/headless"
|
||||||
|
HEADLESS_VK_DIR="$HEADLESS_DIR/vk"
|
||||||
|
HEADLESS_TM_DIR="$HEADLESS_DIR/telemost"
|
||||||
|
|
||||||
echo "=== Building relay binaries ==="
|
echo "=== Building relay binaries ==="
|
||||||
cd "$RELAY_DIR"
|
cd "$RELAY_DIR"
|
||||||
@@ -29,70 +30,98 @@ GOOS=linux GOARCH=386 go build -o relay-linux-ia32 .
|
|||||||
ls -lh relay-darwin relay-windows-*.exe relay-linux-*
|
ls -lh relay-darwin relay-windows-*.exe relay-linux-*
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "=== Building headless-creator ==="
|
echo "=== Building headless-vk-creator ==="
|
||||||
cd "$HEADLESS_DIR"
|
cd "$HEADLESS_VK_DIR"
|
||||||
|
|
||||||
echo "macOS (universal)..."
|
echo "macOS (universal)..."
|
||||||
GOOS=darwin GOARCH=amd64 go build -o headless-darwin-amd64 .
|
GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-vk-darwin-amd64" .
|
||||||
GOOS=darwin GOARCH=arm64 go build -o headless-darwin-arm64 .
|
GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-vk-darwin-arm64" .
|
||||||
lipo -create -output headless-darwin headless-darwin-amd64 headless-darwin-arm64
|
lipo -create -output "$HEADLESS_DIR/headless-vk-darwin" "$HEADLESS_DIR/headless-vk-darwin-amd64" "$HEADLESS_DIR/headless-vk-darwin-arm64"
|
||||||
rm headless-darwin-amd64 headless-darwin-arm64
|
rm "$HEADLESS_DIR/headless-vk-darwin-amd64" "$HEADLESS_DIR/headless-vk-darwin-arm64"
|
||||||
|
|
||||||
echo "Windows x64..."
|
echo "Windows x64..."
|
||||||
GOOS=windows GOARCH=amd64 go build -o headless-windows-x64.exe .
|
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-vk-windows-x64.exe" .
|
||||||
echo "Windows x86..."
|
echo "Windows x86..."
|
||||||
GOOS=windows GOARCH=386 go build -o headless-windows-ia32.exe .
|
GOOS=windows GOARCH=386 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-vk-windows-ia32.exe" .
|
||||||
|
|
||||||
echo "Linux x64..."
|
echo "Linux x64..."
|
||||||
GOOS=linux GOARCH=amd64 go build -o headless-linux-x64 .
|
GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-vk-linux-x64" .
|
||||||
echo "Linux x86..."
|
echo "Linux x86..."
|
||||||
GOOS=linux GOARCH=386 go build -o headless-linux-ia32 .
|
GOOS=linux GOARCH=386 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-vk-linux-ia32" .
|
||||||
|
|
||||||
ls -lh headless-darwin headless-windows-*.exe headless-linux-*
|
echo ""
|
||||||
|
echo "=== Building headless-telemost-creator ==="
|
||||||
|
cd "$HEADLESS_TM_DIR"
|
||||||
|
|
||||||
|
echo "macOS (universal)..."
|
||||||
|
GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-telemost-darwin-amd64" .
|
||||||
|
GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-telemost-darwin-arm64" .
|
||||||
|
lipo -create -output "$HEADLESS_DIR/headless-telemost-darwin" "$HEADLESS_DIR/headless-telemost-darwin-amd64" "$HEADLESS_DIR/headless-telemost-darwin-arm64"
|
||||||
|
rm "$HEADLESS_DIR/headless-telemost-darwin-amd64" "$HEADLESS_DIR/headless-telemost-darwin-arm64"
|
||||||
|
|
||||||
|
echo "Windows x64..."
|
||||||
|
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-telemost-windows-x64.exe" .
|
||||||
|
echo "Windows x86..."
|
||||||
|
GOOS=windows GOARCH=386 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-telemost-windows-ia32.exe" .
|
||||||
|
|
||||||
|
echo "Linux x64..."
|
||||||
|
GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-telemost-linux-x64" .
|
||||||
|
echo "Linux x86..."
|
||||||
|
GOOS=linux GOARCH=386 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-telemost-linux-ia32" .
|
||||||
|
|
||||||
|
ls -lh "$HEADLESS_DIR"/headless-vk-darwin "$HEADLESS_DIR"/headless-telemost-darwin
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "=== Building Electron apps ==="
|
echo "=== Building Electron apps ==="
|
||||||
cd "$CREATOR_DIR"
|
cd "$CREATOR_DIR"
|
||||||
npm install --quiet 2>&1
|
npm install --quiet 2>&1
|
||||||
|
npm run build 2>&1
|
||||||
|
|
||||||
# macOS (universal binary already)
|
# macOS (universal binary already)
|
||||||
echo ""
|
echo ""
|
||||||
echo "--- macOS ---"
|
echo "--- macOS ---"
|
||||||
npx electron-builder --mac
|
npx electron-builder --mac || true
|
||||||
|
|
||||||
# Windows x64
|
# Windows x64
|
||||||
echo ""
|
echo ""
|
||||||
echo "--- Windows x64 ---"
|
echo "--- Windows x64 ---"
|
||||||
cp "$RELAY_DIR/relay-windows-x64.exe" "$RELAY_DIR/relay-bundle.exe"
|
cp "$RELAY_DIR/relay-windows-x64.exe" "$RELAY_DIR/relay-bundle.exe"
|
||||||
cp "$HEADLESS_DIR/headless-windows-x64.exe" "$HEADLESS_DIR/headless-bundle.exe"
|
cp "$HEADLESS_DIR/headless-vk-windows-x64.exe" "$HEADLESS_DIR/headless-vk-bundle.exe"
|
||||||
|
cp "$HEADLESS_DIR/headless-telemost-windows-x64.exe" "$HEADLESS_DIR/headless-telemost-bundle.exe"
|
||||||
npx electron-builder --win --x64
|
npx electron-builder --win --x64
|
||||||
|
|
||||||
# Windows x86
|
# Windows x86
|
||||||
echo ""
|
echo ""
|
||||||
echo "--- Windows x86 ---"
|
echo "--- Windows x86 ---"
|
||||||
cp "$RELAY_DIR/relay-windows-ia32.exe" "$RELAY_DIR/relay-bundle.exe"
|
cp "$RELAY_DIR/relay-windows-ia32.exe" "$RELAY_DIR/relay-bundle.exe"
|
||||||
cp "$HEADLESS_DIR/headless-windows-ia32.exe" "$HEADLESS_DIR/headless-bundle.exe"
|
cp "$HEADLESS_DIR/headless-vk-windows-ia32.exe" "$HEADLESS_DIR/headless-vk-bundle.exe"
|
||||||
|
cp "$HEADLESS_DIR/headless-telemost-windows-ia32.exe" "$HEADLESS_DIR/headless-telemost-bundle.exe"
|
||||||
npx electron-builder --win --ia32
|
npx electron-builder --win --ia32
|
||||||
|
|
||||||
# Linux x64
|
# Linux x64
|
||||||
echo ""
|
echo ""
|
||||||
echo "--- Linux x64 ---"
|
echo "--- Linux x64 ---"
|
||||||
cp "$RELAY_DIR/relay-linux-x64" "$RELAY_DIR/relay-bundle"
|
cp "$RELAY_DIR/relay-linux-x64" "$RELAY_DIR/relay-bundle"
|
||||||
cp "$HEADLESS_DIR/headless-linux-x64" "$HEADLESS_DIR/headless-bundle"
|
cp "$HEADLESS_DIR/headless-vk-linux-x64" "$HEADLESS_DIR/headless-vk-bundle"
|
||||||
|
cp "$HEADLESS_DIR/headless-telemost-linux-x64" "$HEADLESS_DIR/headless-telemost-bundle"
|
||||||
npx electron-builder --linux --x64
|
npx electron-builder --linux --x64
|
||||||
|
|
||||||
# Copy standalone headless binaries to prebuilts
|
# Copy standalone headless binaries to prebuilts
|
||||||
echo ""
|
echo ""
|
||||||
echo "=== Copying headless binaries ==="
|
echo "=== Copying headless binaries ==="
|
||||||
mkdir -p "$ROOT/prebuilts"
|
mkdir -p "$ROOT/prebuilts"
|
||||||
cp "$HEADLESS_DIR/headless-linux-x64" "$ROOT/prebuilts/headless-creator-linux-x64"
|
cp "$HEADLESS_DIR/headless-vk-linux-x64" "$ROOT/prebuilts/headless-vk-creator-linux-x64"
|
||||||
cp "$HEADLESS_DIR/headless-linux-ia32" "$ROOT/prebuilts/headless-creator-linux-ia32"
|
cp "$HEADLESS_DIR/headless-vk-linux-ia32" "$ROOT/prebuilts/headless-vk-creator-linux-ia32"
|
||||||
|
cp "$HEADLESS_DIR/headless-telemost-linux-x64" "$ROOT/prebuilts/headless-telemost-creator-linux-x64"
|
||||||
|
cp "$HEADLESS_DIR/headless-telemost-linux-ia32" "$ROOT/prebuilts/headless-telemost-creator-linux-ia32"
|
||||||
|
|
||||||
# Cleanup build artifacts
|
# Cleanup build artifacts
|
||||||
rm -f "$RELAY_DIR"/relay-darwin "$RELAY_DIR"/relay-windows-*.exe "$RELAY_DIR"/relay-linux-*
|
rm -f "$RELAY_DIR"/relay-darwin "$RELAY_DIR"/relay-windows-*.exe "$RELAY_DIR"/relay-linux-*
|
||||||
rm -f "$RELAY_DIR"/relay-bundle "$RELAY_DIR"/relay-bundle.exe
|
rm -f "$RELAY_DIR"/relay-bundle "$RELAY_DIR"/relay-bundle.exe
|
||||||
rm -f "$HEADLESS_DIR"/headless-darwin "$HEADLESS_DIR"/headless-windows-*.exe "$HEADLESS_DIR"/headless-linux-*
|
rm -f "$HEADLESS_DIR"/headless-vk-darwin "$HEADLESS_DIR"/headless-vk-windows-*.exe "$HEADLESS_DIR"/headless-vk-linux-*
|
||||||
rm -f "$HEADLESS_DIR"/headless-bundle "$HEADLESS_DIR"/headless-bundle.exe
|
rm -f "$HEADLESS_DIR"/headless-vk-bundle "$HEADLESS_DIR"/headless-vk-bundle.exe
|
||||||
|
rm -f "$HEADLESS_DIR"/headless-telemost-darwin "$HEADLESS_DIR"/headless-telemost-windows-*.exe "$HEADLESS_DIR"/headless-telemost-linux-*
|
||||||
|
rm -f "$HEADLESS_DIR"/headless-telemost-bundle "$HEADLESS_DIR"/headless-telemost-bundle.exe
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "=== Done ==="
|
echo "=== Done ==="
|
||||||
|
|||||||
+6
-10
@@ -27,21 +27,17 @@ GOOS=linux GOARCH=arm64 go build -o ../android-app/app/src/main/jniLibs/arm64-v8
|
|||||||
GOOS=linux GOARCH=arm go build -o ../android-app/app/src/main/jniLibs/armeabi-v7a/librelay.so .
|
GOOS=linux GOARCH=arm go build -o ../android-app/app/src/main/jniLibs/armeabi-v7a/librelay.so .
|
||||||
echo "Pion relay built"
|
echo "Pion relay built"
|
||||||
|
|
||||||
echo "Copying hooks to assets..."
|
|
||||||
mkdir -p ../android-app/app/src/main/assets
|
|
||||||
cp ../hooks/dc-joiner-vk.js ../android-app/app/src/main/assets/dc-joiner-vk.js
|
|
||||||
cp ../hooks/dc-joiner-telemost.js ../android-app/app/src/main/assets/dc-joiner-telemost.js
|
|
||||||
cp ../hooks/video-vk.js ../android-app/app/src/main/assets/video-vk.js
|
|
||||||
cp ../hooks/video-telemost.js ../android-app/app/src/main/assets/video-telemost.js
|
|
||||||
|
|
||||||
echo "Done. .aar size: $(du -h mobile.aar | cut -f1)"
|
echo "Done. .aar size: $(du -h mobile.aar | cut -f1)"
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "Building desktop relay..."
|
echo "Building desktop relay..."
|
||||||
go -C "$ROOT/relay" build -o relay .
|
go -C "$ROOT/relay" build -o relay .
|
||||||
|
|
||||||
echo "Building headless-creator..."
|
echo "Building headless-vk-creator..."
|
||||||
go -C "$ROOT/headless" build -o headless-creator .
|
go -C "$ROOT/headless/vk" build -ldflags="-s -w" -o headless-vk-creator .
|
||||||
|
|
||||||
|
echo "Building headless-telemost-creator-creator..."
|
||||||
|
go -C "$ROOT/headless/telemost" build -ldflags="-s -w" -o headless-telemost-creator .
|
||||||
|
|
||||||
echo "Done."
|
echo "Done."
|
||||||
ls -lh "$ROOT/relay/relay" "$ROOT/headless/headless-creator"
|
ls -lh "$ROOT/relay/relay" "$ROOT/headless/vk/headless-vk-creator" "$ROOT/headless/telemost/headless-telemost-creator"
|
||||||
Executable
+12
@@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
|
||||||
|
echo "Building headless-vk-creator..."
|
||||||
|
go -C "$ROOT/headless/vk" build -ldflags="-s -w" -o headless-vk-creator .
|
||||||
|
|
||||||
|
echo "Building headless-telemost-creator..."
|
||||||
|
go -C "$ROOT/headless/telemost" build -ldflags="-s -w" -o headless-telemost-creator .
|
||||||
|
|
||||||
|
echo "Done."
|
||||||
|
ls -lh "$ROOT/headless/vk/headless-vk-creator" "$ROOT/headless/telemost/headless-telemost-creator"
|
||||||
@@ -10,4 +10,5 @@ cp "$ROOT/hooks/video-telemost.js" "$ASSETS/video-telemost.js"
|
|||||||
cp "$ROOT/hooks/autoclick-telemost.js" "$ASSETS/autoclick-telemost.js"
|
cp "$ROOT/hooks/autoclick-telemost.js" "$ASSETS/autoclick-telemost.js"
|
||||||
cp "$ROOT/hooks/autoclick-vk.js" "$ASSETS/autoclick-vk.js"
|
cp "$ROOT/hooks/autoclick-vk.js" "$ASSETS/autoclick-vk.js"
|
||||||
cp "$ROOT/hooks/mute-audio-context.js" "$ASSETS/mute-audio-context.js"
|
cp "$ROOT/hooks/mute-audio-context.js" "$ASSETS/mute-audio-context.js"
|
||||||
|
cp "$ROOT/hooks/headless-auth-vk.js" "$ASSETS/headless-auth-vk.js"
|
||||||
echo "Hooks copied to assets"
|
echo "Hooks copied to assets"
|
||||||
@@ -1,271 +0,0 @@
|
|||||||
const fetch = require('node-fetch');
|
|
||||||
|
|
||||||
function generateTabId(tabId) {
|
|
||||||
var hash = 0;
|
|
||||||
for (var i = 0; i < tabId.length; i++) {
|
|
||||||
hash = ((hash << 5) - hash) + tabId.charCodeAt(i);
|
|
||||||
hash = hash & hash;
|
|
||||||
}
|
|
||||||
return Math.abs(hash) % 10000;
|
|
||||||
}
|
|
||||||
|
|
||||||
function findTabById(tabsList, shortId) {
|
|
||||||
var targetId = parseInt(shortId, 10);
|
|
||||||
for (var i = 0; i < tabsList.length; i++) {
|
|
||||||
var t = tabsList[i];
|
|
||||||
if (generateTabId(t.id) === targetId) {
|
|
||||||
return t;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function createKeyboard() {
|
|
||||||
return {
|
|
||||||
one_time: false,
|
|
||||||
buttons: [
|
|
||||||
[
|
|
||||||
{ action: { type: 'text', label: '📞 VK DC', payload: JSON.stringify({ cmd: 'vk', mode: 'dc' }) } },
|
|
||||||
{ action: { type: 'text', label: '📹 VK Video', payload: JSON.stringify({ cmd: 'vk', mode: 'video' }) } }
|
|
||||||
],
|
|
||||||
[
|
|
||||||
{ action: { type: 'text', label: '📞 TM DC', payload: JSON.stringify({ cmd: 'tm', mode: 'dc' }) } },
|
|
||||||
{ action: { type: 'text', label: '📹 TM Video', payload: JSON.stringify({ cmd: 'tm', mode: 'video' }) } }
|
|
||||||
],
|
|
||||||
[
|
|
||||||
{ action: { type: 'text', label: '📋 Active Tabs', payload: JSON.stringify({ cmd: 'list' }) } }
|
|
||||||
]
|
|
||||||
]
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function createListKeyboard(tabsList) {
|
|
||||||
var buttons = [];
|
|
||||||
for (var i = 0; i < tabsList.length; i++) {
|
|
||||||
var t = tabsList[i];
|
|
||||||
var shortId = generateTabId(t.id);
|
|
||||||
var paddedId = ('000' + shortId).slice(-4);
|
|
||||||
var prefix = t.isBot ? 'bot' : 'user';
|
|
||||||
var status = t.callStatus === 'active' ? '🟢' : '⚪';
|
|
||||||
buttons.push([
|
|
||||||
{ action: { type: 'text', label: prefix + ' ' + t.platform + ' ' + t.mode + ' ' + paddedId + ' ' + status, payload: JSON.stringify({ cmd: 'close', id: t.id }) } }
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
buttons.push([{ action: { type: 'text', label: '◀️ Back', payload: JSON.stringify({ cmd: 'menu' }) } }]);
|
|
||||||
return {
|
|
||||||
one_time: false,
|
|
||||||
buttons: buttons
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
class BotManager {
|
|
||||||
constructor(settings, onCreateTab, onGetTabs, onCloseTab) {
|
|
||||||
this.settings = settings;
|
|
||||||
this.onCreateTab = onCreateTab;
|
|
||||||
this.onGetTabs = onGetTabs;
|
|
||||||
this.onCloseTab = onCloseTab;
|
|
||||||
this.baseUrl = 'https://api.vk.com/method';
|
|
||||||
this.ts = null;
|
|
||||||
this.key = null;
|
|
||||||
this.server = null;
|
|
||||||
this.running = false;
|
|
||||||
}
|
|
||||||
async api(method, params = {}) {
|
|
||||||
params.v = '5.131';
|
|
||||||
params.access_token = this.settings.token;
|
|
||||||
const url = new URL(`${this.baseUrl}/${method}`);
|
|
||||||
Object.keys(params).forEach(k => url.searchParams.set(k, params[k]));
|
|
||||||
const res = await fetch(url);
|
|
||||||
const data = await res.json();
|
|
||||||
|
|
||||||
if (data.error) {
|
|
||||||
var errMsg = method + ' code: ' + data.error.error_code + ' msg: ' + (data.error.error_msg || 'VK API error') + ' params: ' + JSON.stringify(data.error.request_params || []);
|
|
||||||
console.error('[BOT] API error:', errMsg);
|
|
||||||
throw new Error(errMsg);
|
|
||||||
}
|
|
||||||
return data.response;
|
|
||||||
}
|
|
||||||
|
|
||||||
async getLongPollServer() {
|
|
||||||
const data = await this.api('groups.getLongPollServer', { group_id: parseInt(this.settings.groupId) });
|
|
||||||
this.server = data.server;
|
|
||||||
this.key = data.key;
|
|
||||||
this.ts = data.ts;
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
async start() {
|
|
||||||
this.running = true;
|
|
||||||
console.log('[BOT] Starting with settings:', this.settings);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await this.getLongPollServer();
|
|
||||||
console.log('[BOT] LongPoll server:', this.server);
|
|
||||||
this.pollLoop();
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[BOT] Failed to start:', err.message);
|
|
||||||
this.running = false;
|
|
||||||
if (this.onError) this.onError(err.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stop() {
|
|
||||||
this.running = false;
|
|
||||||
console.log('[BOT] Stopped');
|
|
||||||
}
|
|
||||||
|
|
||||||
async pollLoop() {
|
|
||||||
while (this.running) {
|
|
||||||
try {
|
|
||||||
const url = `${this.server}?act=a_check&key=${this.key}&ts=${this.ts}&wait=25`;
|
|
||||||
const res = await fetch(url);
|
|
||||||
const data = await res.json();
|
|
||||||
|
|
||||||
if (data.failed) {
|
|
||||||
console.log('[BOT] LongPoll failed, reconnecting...');
|
|
||||||
await this.getLongPollServer();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
this.ts = data.ts;
|
|
||||||
for (const update of data.updates) {
|
|
||||||
await this.handleUpdate(update);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[BOT] Poll error:', err.message);
|
|
||||||
await new Promise(r => setTimeout(r, 1000));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async handleUpdate(update) {
|
|
||||||
if (update.type === 'message_new') {
|
|
||||||
const message = update.object.message;
|
|
||||||
var text = (message.text || '').trim();
|
|
||||||
const fromId = message.from_id;
|
|
||||||
const peerId = message.peer_id;
|
|
||||||
|
|
||||||
var payload = null;
|
|
||||||
if (message.payload) {
|
|
||||||
try {
|
|
||||||
payload = JSON.parse(message.payload);
|
|
||||||
console.log('[BOT] Payload from button:', payload);
|
|
||||||
} catch (e) {
|
|
||||||
console.log('[BOT] Failed to parse payload:', message.payload);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('[BOT] Message from', fromId, ':', text, 'payload:', payload);
|
|
||||||
|
|
||||||
if (this.settings.userId && fromId.toString() !== this.settings.userId.toString()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (text === '/start' || text === 'start') {
|
|
||||||
await this.showMenu(peerId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (payload && payload.cmd) {
|
|
||||||
if (payload.cmd === 'list') {
|
|
||||||
await this.showList(peerId);
|
|
||||||
return;
|
|
||||||
} else if (payload.cmd === 'menu') {
|
|
||||||
await this.showMenu(peerId);
|
|
||||||
return;
|
|
||||||
} else if (payload.cmd === 'close') {
|
|
||||||
if (payload.id) {
|
|
||||||
var tabsList = this.onGetTabs ? this.onGetTabs() : [];
|
|
||||||
var foundTab = null;
|
|
||||||
for (var i = 0; i < tabsList.length; i++) {
|
|
||||||
if (tabsList[i].id === payload.id) {
|
|
||||||
foundTab = tabsList[i];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (foundTab && this.onCloseTab) {
|
|
||||||
var shortId = generateTabId(foundTab.id);
|
|
||||||
var paddedId = ('000' + shortId).slice(-4);
|
|
||||||
this.onCloseTab(foundTab.id);
|
|
||||||
await this.sendMessage(peerId, foundTab.platform + ' ' + foundTab.mode + ' ' + paddedId + ' closed', createKeyboard());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
} else if (payload.cmd === 'vk') {
|
|
||||||
text = '/vk' + (payload.mode === 'video' ? ' video' : '');
|
|
||||||
} else if (payload.cmd === 'tm') {
|
|
||||||
text = '/tm' + (payload.mode === 'video' ? ' video' : '');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (text.startsWith('/vk')) {
|
|
||||||
const mode = text.includes('video') ? 'pion-video' : 'dc';
|
|
||||||
console.log('[BOT] Creating VK tab with mode:', mode);
|
|
||||||
|
|
||||||
this.onCreateTab({ mode: mode, peerId: peerId, platform: 'vk' });
|
|
||||||
await this.sendMessage(peerId, 'Creating VK call (' + (mode === 'dc' ? 'DC' : 'Video') + ')', createKeyboard());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (text.startsWith('/tm')) {
|
|
||||||
const mode = text.includes('video') ? 'pion-video' : 'dc';
|
|
||||||
console.log('[BOT] Creating Telemost tab with mode:', mode);
|
|
||||||
|
|
||||||
this.onCreateTab({ mode: mode, peerId: peerId, platform: 'telemost' });
|
|
||||||
|
|
||||||
await this.sendMessage(peerId, 'Creating Telemost call (' + (mode === 'dc' ? 'DC' : 'Video') + ')', createKeyboard());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (text === '/list') {
|
|
||||||
await this.showList(peerId);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (text.startsWith('/close ')) {
|
|
||||||
var parts = text.split(' ');
|
|
||||||
var targetShortId = parts[1];
|
|
||||||
console.log('[BOT] Close request for ID:', targetShortId, 'from peer:', peerId);
|
|
||||||
|
|
||||||
var tabsList = this.onGetTabs ? this.onGetTabs() : [];
|
|
||||||
var foundTab = findTabById(tabsList, targetShortId);
|
|
||||||
|
|
||||||
if (!foundTab) {
|
|
||||||
await this.sendMessage(peerId, 'Tab ' + targetShortId + ' not found', createKeyboard());
|
|
||||||
} else if (this.onCloseTab) {
|
|
||||||
this.onCloseTab(foundTab.id);
|
|
||||||
await this.sendMessage(peerId, foundTab.platform + ' ' + foundTab.mode + ' ' + targetShortId + ' closed', createKeyboard());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async sendMessage(peerId, text, keyboard = null) {
|
|
||||||
try {
|
|
||||||
var params = {
|
|
||||||
peer_id: peerId,
|
|
||||||
message: text,
|
|
||||||
random_id: Math.floor(Math.random() * 1e9)
|
|
||||||
};
|
|
||||||
if (keyboard) {
|
|
||||||
params.keyboard = JSON.stringify(keyboard);
|
|
||||||
}
|
|
||||||
await this.api('messages.send', params);
|
|
||||||
console.log('[BOT] Sent message to', peerId);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('[BOT] Send message error:', err.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async showMenu(peerId) {
|
|
||||||
await this.sendMessage(peerId, '🤖 Select mode:', createKeyboard());
|
|
||||||
}
|
|
||||||
|
|
||||||
async showList(peerId) {
|
|
||||||
var tabsList = this.onGetTabs ? this.onGetTabs() : [];
|
|
||||||
if (tabsList.length === 0) {
|
|
||||||
await this.sendMessage(peerId, 'No active tabs', createKeyboard());
|
|
||||||
} else {
|
|
||||||
await this.sendMessage(peerId, 'Select tab to close:', createListKeyboard(tabsList));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = BotManager;
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
(function() {
|
|
||||||
if (window.__callCheckerStarted) return;
|
|
||||||
window.__callCheckerStarted = true;
|
|
||||||
|
|
||||||
var tabId = window.__CALL_CHECKER_TAB_ID || 'unknown';
|
|
||||||
|
|
||||||
console.log('[CALL_STATUS] Checker started for ' + tabId);
|
|
||||||
|
|
||||||
const checkCallStatus = () => {
|
|
||||||
var vkBtn = document.querySelector('button[data-testid="calls_call_footer_button_leave_call"]') ||
|
|
||||||
document.querySelector('[data-testid="calls_call_footer_button_leave_call"]');
|
|
||||||
|
|
||||||
var tmBtn = document.querySelector('[data-testid="end-call-alt-button"]') ||
|
|
||||||
document.querySelector('button[data-testid="end-call-alt-button"]');
|
|
||||||
|
|
||||||
var status = (vkBtn || tmBtn) ? 'active' : 'inactive';
|
|
||||||
|
|
||||||
console.log('[CALL_STATUS] ' + tabId + ':' + status);
|
|
||||||
};
|
|
||||||
setTimeout(function() {
|
|
||||||
checkCallStatus();
|
|
||||||
setInterval(checkCallStatus, 10000);
|
|
||||||
}, 10000);
|
|
||||||
})();
|
|
||||||
+36
-486
@@ -1,111 +1,63 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<style>
|
<link rel="stylesheet" href="styles/main.css">
|
||||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
||||||
body { font-family: -apple-system, sans-serif; background: #1a1a1a; color: #e0e0e0; height: 100vh; display: flex; flex-direction: column; }
|
|
||||||
.tab-bar { display: flex; align-items: center; background: #222; border-bottom: 1px solid #333; height: 36px; flex-shrink: 0; }
|
|
||||||
.tab-bar-tabs { display: flex; align-items: center; height: 100%; flex: 1; overflow-x: auto; }
|
|
||||||
.tab-bar-actions { display: flex; align-items: center; height: 100%; border-left: 1px solid #333; }
|
|
||||||
.tab { display: flex; align-items: center; gap: 6px; padding: 0 12px; height: 100%; font-size: 12px; cursor: pointer; border-right: 1px solid #333; white-space: nowrap; color: #888; }
|
|
||||||
.tab.active { background: #1a1a1a; color: #e0e0e0; }
|
|
||||||
.tab .close { font-size: 14px; opacity: 0.5; cursor: pointer; margin-left: 4px; }
|
|
||||||
.tab .close:hover { opacity: 1; }
|
|
||||||
.tab .edit { width: 12px; height: 12px; opacity: 0; cursor: pointer; filter: invert(1) brightness(2); margin-left: 2px; }
|
|
||||||
.tab:hover .edit { opacity: 0.4; }
|
|
||||||
.tab .edit:hover { opacity: 1; }
|
|
||||||
.tab-add { padding: 0 12px; height: 100%; display: flex; align-items: center; font-size: 16px; cursor: pointer; color: #888; }
|
|
||||||
.tab-add:hover { color: #e0e0e0; }
|
|
||||||
.tab-settings { padding: 0 12px; height: 100%; display: flex; align-items: center; font-size: 14px; cursor: pointer; color: #888; }
|
|
||||||
.tab-settings:hover { color: #e0e0e0; }
|
|
||||||
.tab-bot { padding: 0 12px; height: 100%; display: flex; align-items: center; font-size: 12px; cursor: pointer; color: #888; font-weight: 500; }
|
|
||||||
.tab-bot:hover { color: #e0e0e0; }
|
|
||||||
.tab-bot.running { color: #dc3545; }
|
|
||||||
.toolbar { display: flex; align-items: center; gap: 8px; padding: 6px 12px; background: #252525; border-bottom: 1px solid #333; height: 36px; flex-shrink: 0; }
|
|
||||||
.toolbar button { padding: 3px 12px; border: none; border-radius: 6px; font-size: 12px; cursor: pointer; font-weight: 500; }
|
|
||||||
.btn-vk { background: #0077ff; color: white; }
|
|
||||||
.btn-telemost { background: #fc3f1d; color: white; }
|
|
||||||
.content { flex: 1; position: relative; }
|
|
||||||
.content webview { width: 100%; height: 100%; border: none; position: absolute; top: 0; left: 0; }
|
|
||||||
.content webview.hidden { display: none; }
|
|
||||||
.welcome { display: flex; align-items: center; justify-content: center; height: 100%; flex-direction: column; gap: 16px; }
|
|
||||||
.welcome h1 { font-size: 22px; font-weight: 500; }
|
|
||||||
.welcome p { color: #888; font-size: 14px; }
|
|
||||||
.logs { display: flex; gap: 0; border-top: 1px solid #333; height: 120px; flex-shrink: 0; }
|
|
||||||
.log-panel { flex: 1; display: flex; flex-direction: column; }
|
|
||||||
.log-panel:first-child { border-right: 1px solid #333; }
|
|
||||||
.log-title { font-size: 10px; font-weight: 600; color: #888; padding: 3px 8px; background: #1e1e1e; border-bottom: 1px solid #333; }
|
|
||||||
.log-content { flex: 1; overflow-y: auto; padding: 3px 8px; font-family: monospace; font-size: 10px; background: #111; white-space: pre-wrap; word-break: break-all; }
|
|
||||||
.log-content.relay { color: #4fc3f7; }
|
|
||||||
.log-content.hook { color: #66bb6a; }
|
|
||||||
|
|
||||||
/* Settings Popup */
|
|
||||||
.popup-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 1000; display: none; align-items: center; justify-content: center; }
|
|
||||||
.popup-overlay.visible { display: flex; }
|
|
||||||
.popup { background: #2a2a2a; border-radius: 12px; padding: 24px; width: 400px; box-shadow: 0 8px 32px rgba(0,0,0,0.4); }
|
|
||||||
.popup h2 { margin: 0 0 20px; font-size: 18px; font-weight: 600; color: #e0e0e0; }
|
|
||||||
.popup label { display: block; margin-bottom: 6px; font-size: 12px; color: #888; font-weight: 500; }
|
|
||||||
.popup input { width: 100%; padding: 10px 12px; border: 1px solid #444; border-radius: 8px; font-size: 14px; background: #1a1a1a; color: #e0e0e0; outline: none; margin-bottom: 16px; box-sizing: border-box; }
|
|
||||||
.popup input:focus { border-color: #0077ff; }
|
|
||||||
.popup-buttons { display: flex; gap: 8px; justify-content: flex-end; }
|
|
||||||
.popup button { padding: 8px 16px; border: none; border-radius: 8px; font-size: 13px; cursor: pointer; font-weight: 500; }
|
|
||||||
.btn-save { background: #0077ff; color: white; }
|
|
||||||
.btn-cancel { background: #444; color: #e0e0e0; }
|
|
||||||
.btn-bot { background: #6f42c1; color: white; }
|
|
||||||
.btn-bot.running { background: #dc3545; }
|
|
||||||
</style>
|
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="tab-bar">
|
<div class="tab-bar">
|
||||||
<div class="tab-bar-tabs" id="tabBar">
|
<div class="tab-bar-tabs" id="tabBar">
|
||||||
<div class="tab-add" onclick="addTab()" title="New tab">+</div>
|
<div class="tab-add" data-action="add-tab" title="New tab">+</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="tab-bar-actions">
|
<div class="tab-bar-actions">
|
||||||
<div class="tab-settings" onclick="copyCookies()" title="Export VK cookies to cookies.json for headless mode" style="cursor:pointer">Export Cookies</div>
|
<div class="tab-action-btn" id="btnVkCookies" title="Export VK cookies to vk-cookies.json for headless mode">VK Cookies</div>
|
||||||
<div class="tab-settings" onclick="openSettings()" title="Settings">Settings</div>
|
<div class="tab-action-btn" id="btnYandexCookies" title="Export Yandex cookies to cookies-yandex.json for headless mode">Yandex Cookies</div>
|
||||||
<div class="tab-bot" id="tabBot" onclick="toggleBot()">Bot: Off</div>
|
<div class="tab-action-btn settings" id="btnSettings" title="Settings">Settings</div>
|
||||||
|
<div class="tab-action-btn bot" id="tabBot">Bot: Off</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="toolbar" id="toolbar" style="display:none">
|
<div class="toolbar" id="toolbar" style="display:none">
|
||||||
<button class="btn-vk" onclick="loadURL('https://vk.com/im')">VK</button>
|
<button class="btn-vk" id="btnVk">VK</button>
|
||||||
<button class="btn-telemost" onclick="loadURL('https://telemost.yandex.ru/')">Telemost</button>
|
<button class="btn-telemost" id="btnTelemost">Telemost</button>
|
||||||
<button class="btn-vk" onclick="startHeadlessVK()" style="opacity:0.8">Headless VK</button>
|
<button class="btn-headless" id="btnHeadlessVK">Headless VK</button>
|
||||||
<span style="margin-left:auto;font-size:11px;color:#888">Tunnel:</span>
|
<button class="btn-headless-tm" id="btnHeadlessTM">Headless TM</button>
|
||||||
<select id="modeSelect" style="padding:2px 6px;border:1px solid #555;border-radius:6px;font-size:11px;cursor:pointer;font-weight:500;background:#333;color:#e0e0e0;outline:none" onchange="onModeChange(this.value)">
|
<span class="toolbar-spacer"></span>
|
||||||
|
<span class="toolbar-label">Tunnel:</span>
|
||||||
|
<select id="modeSelect" class="toolbar-select">
|
||||||
<option value="dc">DC</option>
|
<option value="dc">DC</option>
|
||||||
<option value="pion-video">Video</option>
|
<option value="pion-video">Video</option>
|
||||||
</select>
|
</select>
|
||||||
<span onclick="saveLogs()" style="cursor:pointer;margin-left:8px" title="Save logs"><img src="resources/icons8-download-64.png" style="height:16px;vertical-align:middle;filter:invert(1) brightness(2)"></span>
|
<span class="toolbar-icon" id="btnSaveLogs" title="Save logs"><img src="resources/icons8-download-64.png"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="content" id="content">
|
<div class="content" id="content">
|
||||||
<div class="welcome" id="welcome">
|
<div class="welcome" id="welcome">
|
||||||
<h1>Whitelist Bypass - Creator</h1>
|
<h1>Whitelist Bypass - Creator</h1>
|
||||||
<p>Click + to add a tab</p>
|
<p>Click + to add a tab</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="headless-info" id="headlessInfo" style="display:none;padding:24px;color:#e0e0e0;font-family:monospace;font-size:14px">
|
<div class="headless-info" id="headlessInfo">
|
||||||
<div style="font-size:18px;font-weight:bold;margin-bottom:16px">Headless VK</div>
|
<div class="headless-title" id="headlessTitle">Headless</div>
|
||||||
<div id="headlessStatus" style="color:#888">Starting...</div>
|
<div class="headless-status" id="headlessStatus">Starting...</div>
|
||||||
<div id="headlessCallInfo" style="margin-top:16px;display:none">
|
<div class="headless-call-info" id="headlessCallInfo">
|
||||||
<div style="margin-bottom:8px"><span style="color:#888">Join link:</span> <a id="headlessJoinLink" href="#" style="color:#4fc3f7;cursor:pointer" onclick="copyToClipboard(this.textContent)"></a></div>
|
<div class="headless-row"><span class="headless-label">Join link:</span> <a id="headlessJoinLink" href="#" class="headless-link"></a><img class="headless-copy" src="resources/icons8-copy-50.png" data-copy="headlessJoinLink" title="Copy"></div>
|
||||||
<div style="margin-bottom:8px"><span style="color:#888">Short:</span> <a id="headlessShortLink" href="#" style="color:#4fc3f7;cursor:pointer" onclick="copyToClipboard(this.textContent)"></a></div>
|
<div class="headless-row"><span class="headless-label">Short:</span> <a id="headlessShortLink" href="#" class="headless-link"></a><img class="headless-copy" src="resources/icons8-copy-50.png" data-copy="headlessShortLink" title="Copy"></div>
|
||||||
<div style="margin-bottom:8px"><span style="color:#888">TURN:</span> <span id="headlessTurn"></span></div>
|
<div class="headless-row"><span class="headless-label">TURN:</span> <span id="headlessTurn"></span></div>
|
||||||
<div style="margin-bottom:8px"><span style="color:#888">Protocol:</span> <span id="headlessProtocol"></span></div>
|
<div class="headless-row"><span class="headless-label">Protocol:</span> <span id="headlessProtocol"></span></div>
|
||||||
|
</div>
|
||||||
|
<div class="headless-call-info" id="headlessCallInfoTM">
|
||||||
|
<div class="headless-row"><span class="headless-label">Join link:</span> <a id="headlessTMJoinLink" href="#" class="headless-link"></a><img class="headless-copy" src="resources/icons8-copy-50.png" data-copy="headlessTMJoinLink" title="Copy"></div>
|
||||||
|
<div class="headless-row"><span class="headless-label">Protocol:</span> <span id="headlessTMProtocol"></span></div>
|
||||||
</div>
|
</div>
|
||||||
<div id="headlessTunnel" style="margin-top:16px;display:none;color:#4caf50;font-weight:bold;font-size:16px">TUNNEL CONNECTED</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="logs" id="logsPanel" style="display:none">
|
<div class="logs" id="logsPanel" style="display:none">
|
||||||
<div class="log-panel">
|
<div class="log-panel">
|
||||||
<div class="log-title">Relay <span onclick="clearLog('relay')" style="cursor:pointer;float:right" title="Clear"><span style="font-size:13px;line-height:13px">✕</span></span></div>
|
<div class="log-title">Relay <span class="log-clear-btn" id="btnClearRelay" title="Clear">✕</span></div>
|
||||||
<div class="log-content relay" id="relayLog"></div>
|
<div class="log-content relay" id="relayLog"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="log-panel">
|
<div class="log-panel">
|
||||||
<div class="log-title">Hook <span onclick="clearLog('hook')" style="cursor:pointer;float:right" title="Clear"><span style="font-size:13px;line-height:13px">✕</span></span></div>
|
<div class="log-title">Hook <span class="log-clear-btn" id="btnClearHook" title="Clear">✕</span></div>
|
||||||
<div class="log-content hook" id="hookLog"></div>
|
<div class="log-content hook" id="hookLog"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Settings Popup -->
|
|
||||||
<div class="popup-overlay" id="settingsPopup">
|
<div class="popup-overlay" id="settingsPopup">
|
||||||
<div class="popup">
|
<div class="popup">
|
||||||
<h2>VK bot settings</h2>
|
<h2>VK bot settings</h2>
|
||||||
@@ -116,422 +68,20 @@ body { font-family: -apple-system, sans-serif; background: #1a1a1a; color: #e0e0
|
|||||||
<label for="vkUserId">User ID</label>
|
<label for="vkUserId">User ID</label>
|
||||||
<input type="number" id="vkUserId" placeholder="123456789">
|
<input type="number" id="vkUserId" placeholder="123456789">
|
||||||
<div class="popup-buttons">
|
<div class="popup-buttons">
|
||||||
<button class="btn-cancel" onclick="closeSettings()">Cancel</button>
|
<button class="btn-cancel" id="btnSettingsCancel">Cancel</button>
|
||||||
<button class="btn-save" onclick="saveSettings()">Save</button>
|
<button class="btn-save" id="btnSettingsSave">Save</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="popup-overlay" id="errorPopup" onclick="closeError()">
|
<div class="popup-overlay" id="errorPopup">
|
||||||
<div class="popup" style="padding:16px" onclick="event.stopPropagation()">
|
<div class="popup" style="padding:16px">
|
||||||
<h2 style="color:#dc3545;margin-bottom:12px;font-size:15px">Bot error</h2>
|
<h2 class="error-title">Bot error</h2>
|
||||||
<pre id="errorText" style="background:#111;padding:10px;border-radius:6px;font-size:11px;color:#e0e0e0;white-space:pre-wrap;word-break:break-all;max-height:200px;overflow-y:auto;user-select:text;cursor:text;margin:0"></pre>
|
<pre class="error-text" id="errorText"></pre>
|
||||||
<div class="popup-buttons" style="margin-top:12px">
|
<div class="popup-buttons" style="margin-top:12px">
|
||||||
<button class="btn-cancel" onclick="closeError()">Close</button>
|
<button class="btn-cancel" id="btnErrorClose">Close</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script>
|
<script>require('./dist/renderer/index.js')</script>
|
||||||
function showError(msg) {
|
|
||||||
document.getElementById('errorText').textContent = msg;
|
|
||||||
document.getElementById('errorPopup').classList.add('visible');
|
|
||||||
}
|
|
||||||
function closeError() {
|
|
||||||
document.getElementById('errorPopup').classList.remove('visible');
|
|
||||||
}
|
|
||||||
|
|
||||||
window.bridge.onBotError(function(msg) {
|
|
||||||
showError(msg);
|
|
||||||
botRunning = false;
|
|
||||||
localStorage.setItem('botEnabled', 'false');
|
|
||||||
var btn = document.getElementById('tabBot');
|
|
||||||
btn.textContent = 'Bot: Off';
|
|
||||||
btn.classList.remove('running');
|
|
||||||
});
|
|
||||||
|
|
||||||
function copyCookies() {
|
|
||||||
window.bridge.getCookies('.vk.com').then(function(cookies) {
|
|
||||||
if (!cookies.length) {
|
|
||||||
showError('No VK cookies found.\nPlease log into VK first.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
var simple = cookies.map(function(c) { return { name: c.name, value: c.value }; });
|
|
||||||
var blob = new Blob([JSON.stringify(simple, null, 2)], { type: 'application/json' });
|
|
||||||
var link = document.createElement('a');
|
|
||||||
link.href = URL.createObjectURL(blob);
|
|
||||||
link.download = 'cookies.json';
|
|
||||||
link.click();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
var tabsState = {}; // tabId -> { wv, mode, relayLogs, hookLogs }
|
|
||||||
var activeTabId = null;
|
|
||||||
var nextTabId = 1;
|
|
||||||
var botRunning = false;
|
|
||||||
|
|
||||||
var savedSettings = localStorage.getItem('botSettings');
|
|
||||||
var botSettings = savedSettings ? JSON.parse(savedSettings) : { token: '', groupId: '', userId: '' };
|
|
||||||
|
|
||||||
if (localStorage.getItem('botEnabled') === 'true' && botSettings.token && botSettings.groupId) {
|
|
||||||
botRunning = true;
|
|
||||||
var btn = document.getElementById('tabBot');
|
|
||||||
btn.textContent = 'Bot: On';
|
|
||||||
btn.classList.add('running');
|
|
||||||
window.bridge.startBot(botSettings);
|
|
||||||
}
|
|
||||||
|
|
||||||
function openSettings() {
|
|
||||||
document.getElementById('settingsPopup').classList.add('visible');
|
|
||||||
document.getElementById('vkToken').value = botSettings.token;
|
|
||||||
document.getElementById('vkGroupId').value = botSettings.groupId;
|
|
||||||
document.getElementById('vkUserId').value = botSettings.userId;
|
|
||||||
}
|
|
||||||
|
|
||||||
function closeSettings() {
|
|
||||||
document.getElementById('settingsPopup').classList.remove('visible');
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveSettings() {
|
|
||||||
botSettings.token = document.getElementById('vkToken').value.trim();
|
|
||||||
botSettings.groupId = document.getElementById('vkGroupId').value.trim();
|
|
||||||
botSettings.userId = document.getElementById('vkUserId').value.trim();
|
|
||||||
localStorage.setItem('botSettings', JSON.stringify(botSettings));
|
|
||||||
closeSettings();
|
|
||||||
console.log('[BOT] Settings saved:', botSettings);
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleBot() {
|
|
||||||
if (!botSettings.token || !botSettings.groupId) {
|
|
||||||
openSettings();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
botRunning = !botRunning;
|
|
||||||
localStorage.setItem('botEnabled', botRunning ? 'true' : 'false');
|
|
||||||
var btn = document.getElementById('tabBot');
|
|
||||||
if (botRunning) {
|
|
||||||
btn.textContent = 'Bot: On';
|
|
||||||
btn.classList.add('running');
|
|
||||||
window.bridge.startBot(botSettings);
|
|
||||||
} else {
|
|
||||||
btn.textContent = 'Bot: Off';
|
|
||||||
btn.classList.remove('running');
|
|
||||||
window.bridge.stopBot();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addTab() {
|
|
||||||
var tabId = 'tab-' + (nextTabId++);
|
|
||||||
tabsState[tabId] = { wv: null, url: '', mode: 'dc', relayLogs: '', hookLogs: '', name: '', isBot: false };
|
|
||||||
window.bridge.startRelay(tabId);
|
|
||||||
renderTabs();
|
|
||||||
selectTab(tabId);
|
|
||||||
}
|
|
||||||
|
|
||||||
function startHeadlessVK() {
|
|
||||||
var tabId = 'tab-' + (nextTabId++);
|
|
||||||
tabsState[tabId] = { wv: null, url: '', mode: 'headless-vk', relayLogs: '', hookLogs: '', name: 'Headless VK', isBot: false, headless: true };
|
|
||||||
window.bridge.startHeadless(tabId);
|
|
||||||
renderTabs();
|
|
||||||
selectTab(tabId);
|
|
||||||
}
|
|
||||||
|
|
||||||
function closeTab(tabId, e) {
|
|
||||||
if (e) e.stopPropagation();
|
|
||||||
var t = tabsState[tabId];
|
|
||||||
if (t && t.wv) t.wv.remove();
|
|
||||||
window.bridge.closeTab(tabId);
|
|
||||||
delete tabsState[tabId];
|
|
||||||
if (activeTabId === tabId) {
|
|
||||||
var ids = Object.keys(tabsState);
|
|
||||||
activeTabId = ids.length > 0 ? ids[ids.length - 1] : null;
|
|
||||||
}
|
|
||||||
renderTabs();
|
|
||||||
renderContent();
|
|
||||||
}
|
|
||||||
|
|
||||||
function selectTab(tabId) {
|
|
||||||
if (activeTabId && tabsState[activeTabId]) {
|
|
||||||
tabsState[activeTabId].relayLogs = document.getElementById('relayLog').textContent;
|
|
||||||
tabsState[activeTabId].hookLogs = document.getElementById('hookLog').textContent;
|
|
||||||
}
|
|
||||||
activeTabId = tabId;
|
|
||||||
renderTabs();
|
|
||||||
renderContent();
|
|
||||||
}
|
|
||||||
|
|
||||||
function getTabLabel(t) {
|
|
||||||
if (t.name) return t.name;
|
|
||||||
if (t.url) {
|
|
||||||
if (t.url.includes('vk.com')) return 'VK';
|
|
||||||
if (t.url.includes('telemost')) return 'Telemost';
|
|
||||||
}
|
|
||||||
return 'New';
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderTabs() {
|
|
||||||
var bar = document.getElementById('tabBar');
|
|
||||||
var html = '';
|
|
||||||
Object.keys(tabsState).forEach(function(id) {
|
|
||||||
var t = tabsState[id];
|
|
||||||
var label = getTabLabel(t);
|
|
||||||
var cls = id === activeTabId ? 'tab active' : 'tab';
|
|
||||||
html += '<div class="' + cls + '" onclick="selectTab(\'' + id + '\')"><span class="tab-label">' + label + '</span><img class="edit" src="resources/icons8-pencil-50.png" onclick="renameTab(\'' + id + '\', event)"> <span class="close" onclick="closeTab(\'' + id + '\', event)">✕</span></div>';
|
|
||||||
});
|
|
||||||
html += '<div class="tab-add" onclick="addTab()" title="New tab">+</div>';
|
|
||||||
bar.innerHTML = html;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renameTab(tabId, e) {
|
|
||||||
e.stopPropagation();
|
|
||||||
var tab = e.target.closest('.tab');
|
|
||||||
var span = tab.querySelector('.tab-label');
|
|
||||||
var inp = document.createElement('input');
|
|
||||||
inp.type = 'text';
|
|
||||||
inp.value = tabsState[tabId].name || '';
|
|
||||||
inp.placeholder = getTabLabel(tabsState[tabId]);
|
|
||||||
inp.style.cssText = 'width:80px;padding:0 4px;border:1px solid #555;border-radius:4px;font-size:12px;background:#111;color:#e0e0e0;outline:none';
|
|
||||||
span.replaceWith(inp);
|
|
||||||
inp.focus();
|
|
||||||
inp.select();
|
|
||||||
var done = function() {
|
|
||||||
tabsState[tabId].name = inp.value.trim();
|
|
||||||
renderTabs();
|
|
||||||
};
|
|
||||||
inp.addEventListener('blur', done);
|
|
||||||
inp.addEventListener('keydown', function(ev) {
|
|
||||||
if (ev.key === 'Enter') inp.blur();
|
|
||||||
if (ev.key === 'Escape') { inp.value = ''; inp.blur(); }
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderContent() {
|
|
||||||
var content = document.getElementById('content');
|
|
||||||
var welcome = document.getElementById('welcome');
|
|
||||||
var toolbar = document.getElementById('toolbar');
|
|
||||||
var logsPanel = document.getElementById('logsPanel');
|
|
||||||
var wvs = content.querySelectorAll('webview');
|
|
||||||
for (var i = 0; i < wvs.length; i++) wvs[i].classList.add('hidden');
|
|
||||||
|
|
||||||
if (!activeTabId || !tabsState[activeTabId]) {
|
|
||||||
welcome.style.display = 'flex';
|
|
||||||
toolbar.style.display = 'none';
|
|
||||||
logsPanel.style.display = 'none';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
welcome.style.display = 'none';
|
|
||||||
logsPanel.style.display = 'flex';
|
|
||||||
|
|
||||||
var t = tabsState[activeTabId];
|
|
||||||
var headlessInfo = document.getElementById('headlessInfo');
|
|
||||||
if (t.headless) {
|
|
||||||
toolbar.style.display = 'none';
|
|
||||||
headlessInfo.style.display = 'block';
|
|
||||||
document.getElementById('headlessStatus').textContent = t.headlessStatus || 'Starting...';
|
|
||||||
var ci = t.callInfo;
|
|
||||||
if (ci) {
|
|
||||||
document.getElementById('headlessCallInfo').style.display = 'block';
|
|
||||||
document.getElementById('headlessJoinLink').textContent = ci.joinLink || '';
|
|
||||||
document.getElementById('headlessShortLink').textContent = ci.shortLink || '';
|
|
||||||
document.getElementById('headlessTurn').textContent = ci.turn || '';
|
|
||||||
document.getElementById('headlessProtocol').textContent = ci.protocol || '';
|
|
||||||
} else {
|
|
||||||
document.getElementById('headlessCallInfo').style.display = 'none';
|
|
||||||
}
|
|
||||||
document.getElementById('headlessTunnel').style.display = t.tunnelConnected ? 'block' : 'none';
|
|
||||||
} else {
|
|
||||||
toolbar.style.display = 'flex';
|
|
||||||
headlessInfo.style.display = 'none';
|
|
||||||
document.getElementById('modeSelect').value = t.mode;
|
|
||||||
if (t.wv) t.wv.classList.remove('hidden');
|
|
||||||
}
|
|
||||||
document.getElementById('relayLog').textContent = t.relayLogs || '';
|
|
||||||
document.getElementById('hookLog').textContent = t.hookLogs || '';
|
|
||||||
scrollLogs();
|
|
||||||
}
|
|
||||||
|
|
||||||
function scrollLogs() {
|
|
||||||
var r = document.getElementById('relayLog');
|
|
||||||
var h = document.getElementById('hookLog');
|
|
||||||
r.scrollTop = r.scrollHeight;
|
|
||||||
h.scrollTop = h.scrollHeight;
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadURL(url) {
|
|
||||||
if (!activeTabId) return;
|
|
||||||
var t = tabsState[activeTabId];
|
|
||||||
if (t.wv) t.wv.remove();
|
|
||||||
var wv = document.createElement('webview');
|
|
||||||
wv.setAttribute('src', url);
|
|
||||||
wv.setAttribute('partition', 'persist:creator');
|
|
||||||
wv.setAttribute('nodeintegration', '');
|
|
||||||
wv.setAttribute('nodeintegrationinsubframes', '');
|
|
||||||
wv.style.width = '100%';
|
|
||||||
wv.style.height = '100%';
|
|
||||||
wv.style.position = 'absolute';
|
|
||||||
wv.style.top = '0';
|
|
||||||
wv.style.left = '0';
|
|
||||||
wv.dataset.tabId = activeTabId;
|
|
||||||
document.getElementById('content').appendChild(wv);
|
|
||||||
wv.addEventListener('dom-ready', function() {
|
|
||||||
wv.setAudioMuted(true);
|
|
||||||
var tabId = wv.dataset.tabId;
|
|
||||||
window.bridge.getHookCode(tabId, wv.getURL()).then(function(code) {
|
|
||||||
wv.executeJavaScript(code).catch(function() {});
|
|
||||||
});
|
|
||||||
|
|
||||||
window.bridge.getCallCreatorCode('call-checker.js').then(function(checkerCode) {
|
|
||||||
console.log('[UI] Injecting call checker for tab:', tabId);
|
|
||||||
var injectCode = 'window.__CALL_CHECKER_TAB_ID = "' + tabId + '"; ' + checkerCode;
|
|
||||||
wv.executeJavaScript(injectCode).catch(function(err) {
|
|
||||||
console.log('[UI] Call checker inject error:', err);
|
|
||||||
});
|
|
||||||
}).catch(function(err) {
|
|
||||||
console.log('[UI] Failed to get call-checker.js:', err);
|
|
||||||
});
|
|
||||||
|
|
||||||
if (tabsState[tabId] && tabsState[tabId].isBot) {
|
|
||||||
setTimeout(function() {
|
|
||||||
var scriptFile = tabsState[tabId].platform === 'telemost' ? 'tm-call-creator.js' : 'vk-call-creator.js';
|
|
||||||
window.bridge.getCallCreatorCode(scriptFile).then(function(callCreatorCode) {
|
|
||||||
wv.executeJavaScript(callCreatorCode).catch(function() {});
|
|
||||||
});
|
|
||||||
}, 1000);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
wv.addEventListener('did-navigate', function() {
|
|
||||||
t.url = wv.getURL() || t.url;
|
|
||||||
renderTabs();
|
|
||||||
var tabId = wv.dataset.tabId;
|
|
||||||
wv.executeJavaScript('window.__hookInstalled = false').catch(function() {});
|
|
||||||
window.bridge.getHookCode(tabId, wv.getURL()).then(function(code) {
|
|
||||||
wv.executeJavaScript(code).catch(function() {});
|
|
||||||
});
|
|
||||||
window.bridge.getCallCreatorCode('call-checker.js').then(function(checkerCode) {
|
|
||||||
var injectCode = 'window.__CALL_CHECKER_TAB_ID = "' + tabId + '"; ' + checkerCode;
|
|
||||||
wv.executeJavaScript(injectCode).catch(function() {});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
t.wv = wv;
|
|
||||||
t.url = url;
|
|
||||||
renderTabs();
|
|
||||||
}
|
|
||||||
|
|
||||||
function onModeChange(mode) {
|
|
||||||
if (!activeTabId) return;
|
|
||||||
var t = tabsState[activeTabId];
|
|
||||||
t.mode = mode;
|
|
||||||
window.bridge.setTunnelMode(activeTabId, mode).then(function() {
|
|
||||||
if (t.wv) {
|
|
||||||
t.wv.executeJavaScript('window.__hookInstalled = false').catch(function() {});
|
|
||||||
t.wv.reload();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearLog(type) {
|
|
||||||
document.getElementById(type === 'relay' ? 'relayLog' : 'hookLog').textContent = '';
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveLogs() {
|
|
||||||
var relay = document.getElementById('relayLog').textContent;
|
|
||||||
var hook = document.getElementById('hookLog').textContent;
|
|
||||||
var text = '=== RELAY ===\n' + relay + '\n\n=== HOOK ===\n' + hook;
|
|
||||||
var blob = new Blob([text], { type: 'text/plain' });
|
|
||||||
var a = document.createElement('a');
|
|
||||||
a.href = URL.createObjectURL(blob);
|
|
||||||
a.download = 'tunnel-logs-' + new Date().toISOString().replace(/[:.]/g, '-') + '.txt';
|
|
||||||
a.click();
|
|
||||||
}
|
|
||||||
|
|
||||||
setInterval(function() {
|
|
||||||
if (!activeTabId || !tabsState[activeTabId] || !tabsState[activeTabId].wv) return;
|
|
||||||
tabsState[activeTabId].wv.executeJavaScript('(window.__hookLogs && window.__hookLogs.length) ? window.__hookLogs.splice(0) : []')
|
|
||||||
.then(function(logs) {
|
|
||||||
if (!logs.length) return;
|
|
||||||
var el = document.getElementById('hookLog');
|
|
||||||
logs.forEach(function(msg) {
|
|
||||||
if (el.textContent.length > 0) el.textContent += '\n';
|
|
||||||
el.textContent += msg.replace('[HOOK] ', '');
|
|
||||||
});
|
|
||||||
el.scrollTop = el.scrollHeight;
|
|
||||||
}).catch(function() {});
|
|
||||||
}, 500);
|
|
||||||
|
|
||||||
window.bridge.onRelayLog(function(tabId, msg) {
|
|
||||||
if (tabsState[tabId]) {
|
|
||||||
tabsState[tabId].relayLogs += (tabsState[tabId].relayLogs ? '\n' : '') + msg;
|
|
||||||
if (tabsState[tabId].headless) parseHeadlessLog(tabId, msg);
|
|
||||||
}
|
|
||||||
if (tabId === activeTabId) {
|
|
||||||
var el = document.getElementById('relayLog');
|
|
||||||
if (el.textContent.length > 0) el.textContent += '\n';
|
|
||||||
el.textContent += msg;
|
|
||||||
el.scrollTop = el.scrollHeight;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
function parseHeadlessLog(tabId, msg) {
|
|
||||||
var t = tabsState[tabId];
|
|
||||||
if (!t) return;
|
|
||||||
var trimmed = msg.trim();
|
|
||||||
if (trimmed === 'CALL CREATED') {
|
|
||||||
t.callInfo = {};
|
|
||||||
t.headlessStatus = 'Call created';
|
|
||||||
}
|
|
||||||
if (trimmed.indexOf('join_link:') !== -1) {
|
|
||||||
if (!t.callInfo) t.callInfo = {};
|
|
||||||
t.callInfo.joinLink = trimmed.split('join_link:')[1].trim();
|
|
||||||
}
|
|
||||||
if (trimmed.indexOf('short:') !== -1) {
|
|
||||||
if (!t.callInfo) t.callInfo = {};
|
|
||||||
t.callInfo.shortLink = trimmed.split('short:')[1].trim();
|
|
||||||
}
|
|
||||||
if (trimmed.indexOf('TURN:') !== -1) {
|
|
||||||
if (!t.callInfo) t.callInfo = {};
|
|
||||||
t.callInfo.turn = trimmed.split('TURN:')[1].trim();
|
|
||||||
}
|
|
||||||
if (trimmed.indexOf('protocol:') !== -1) {
|
|
||||||
if (!t.callInfo) t.callInfo = {};
|
|
||||||
t.callInfo.protocol = trimmed.split('protocol:')[1].trim();
|
|
||||||
}
|
|
||||||
if (trimmed === 'TUNNEL CONNECTED') {
|
|
||||||
t.tunnelConnected = true;
|
|
||||||
t.headlessStatus = 'Tunnel connected';
|
|
||||||
}
|
|
||||||
if (tabId === activeTabId) renderContent();
|
|
||||||
}
|
|
||||||
|
|
||||||
function copyToClipboard(text) {
|
|
||||||
navigator.clipboard.writeText(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
window.bridge.onCreateBotTab(function(data) {
|
|
||||||
console.log('[BOT] Creating tab:', data);
|
|
||||||
var tabId = data.tabId;
|
|
||||||
var mode = data.mode;
|
|
||||||
var peerId = data.peerId;
|
|
||||||
var platform = data.platform || 'vk';
|
|
||||||
|
|
||||||
if (!tabsState[tabId]) {
|
|
||||||
var botName = platform === 'telemost' ? 'Bot-Telemost' : 'Bot-VK';
|
|
||||||
tabsState[tabId] = { wv: null, url: '', mode: mode, relayLogs: '', hookLogs: '', name: botName, isBot: true, peerId: peerId, platform: platform };
|
|
||||||
}
|
|
||||||
|
|
||||||
selectTab(tabId);
|
|
||||||
|
|
||||||
document.getElementById('modeSelect').value = mode;
|
|
||||||
window.bridge.setTunnelMode(tabId, mode);
|
|
||||||
|
|
||||||
if (platform === 'telemost') {
|
|
||||||
loadURL('https://telemost.yandex.ru/');
|
|
||||||
} else {
|
|
||||||
loadURL('https://vk.com/im');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
window.bridge.onCloseBotTab(function(data) {
|
|
||||||
console.log('[BOT] Closing tab:', data.tabId);
|
|
||||||
closeTab(data.tabId);
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -1,387 +0,0 @@
|
|||||||
const { app, BrowserWindow, session, ipcMain } = require('electron');
|
|
||||||
const { spawn } = require('child_process');
|
|
||||||
const path = require('path');
|
|
||||||
const fs = require('fs');
|
|
||||||
const TelemostAutoclick = require('./telemost-autoclick');
|
|
||||||
const VkAutoclick = require('./vk-autoclick');
|
|
||||||
const BotManager = require('./bot-manager');
|
|
||||||
|
|
||||||
var hooksDir = app.isPackaged
|
|
||||||
? path.join(process.resourcesPath, 'hooks')
|
|
||||||
: path.join(__dirname, '..', 'hooks');
|
|
||||||
var logCapture = "if(!window.__logCaptureInstalled){window.__logCaptureInstalled=true;window.__hookLogs=[];var _ol=console.log.bind(console);console.log=function(){_ol.apply(null,arguments);var m=Array.prototype.slice.call(arguments).join(' ');if(m.indexOf('[HOOK]')!==-1)window.__hookLogs.push(m)}}";
|
|
||||||
var relayPath = app.isPackaged
|
|
||||||
? path.join(process.resourcesPath, process.platform === 'win32' ? 'relay.exe' : 'relay')
|
|
||||||
: path.join(__dirname, '..', 'relay', process.platform === 'win32' ? 'relay.exe' : 'relay');
|
|
||||||
var headlessPath = app.isPackaged
|
|
||||||
? path.join(process.resourcesPath, process.platform === 'win32' ? 'headless-creator.exe' : 'headless-creator')
|
|
||||||
: path.join(__dirname, '..', 'headless', process.platform === 'win32' ? 'headless-creator.exe' : 'headless-creator');
|
|
||||||
var headlessPath = app.isPackaged
|
|
||||||
? path.join(process.resourcesPath, process.platform === 'win32' ? 'headless-creator.exe' : 'headless-creator')
|
|
||||||
: path.join(__dirname, '..', 'headless', process.platform === 'win32' ? 'headless-creator.exe' : 'headless-creator');
|
|
||||||
|
|
||||||
var tabs = new Map(); // tabId -> { relay, tunnelMode, platform, dcPort, pionPort, isBot }
|
|
||||||
var callStatusCache = new Map();
|
|
||||||
var nextPortBase = 10000;
|
|
||||||
var mainWindow = null;
|
|
||||||
var botManager = null;
|
|
||||||
var botTabs = new Set();
|
|
||||||
|
|
||||||
function isPortFree(port) {
|
|
||||||
return new Promise(function(resolve) {
|
|
||||||
var server = require('net').createServer();
|
|
||||||
server.once('error', function() { resolve(false); });
|
|
||||||
server.once('listening', function() { server.close(function() { resolve(true); }); });
|
|
||||||
server.listen(port, '127.0.0.1');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function allocPorts() {
|
|
||||||
while (true) {
|
|
||||||
var dc = nextPortBase;
|
|
||||||
var pion = nextPortBase + 1;
|
|
||||||
nextPortBase += 2;
|
|
||||||
var dcFree = await isPortFree(dc);
|
|
||||||
var pionFree = await isPortFree(pion);
|
|
||||||
if (dcFree && pionFree) return { dc: dc, pion: pion };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getTab(tabId) {
|
|
||||||
if (!tabs.has(tabId)) {
|
|
||||||
var ports = await allocPorts();
|
|
||||||
tabs.set(tabId, { relay: null, tunnelMode: 'dc', platform: 'vk', dcPort: ports.dc, pionPort: ports.pion });
|
|
||||||
}
|
|
||||||
return tabs.get(tabId);
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadHook(url, tab) {
|
|
||||||
var isTelemost = url.includes('telemost.yandex');
|
|
||||||
var newPlatform = isTelemost ? 'telemost' : 'vk';
|
|
||||||
if (newPlatform !== tab.platform && tab.tunnelMode.startsWith('pion')) {
|
|
||||||
tab.platform = newPlatform;
|
|
||||||
killRelay(tab);
|
|
||||||
setTimeout(function() { startRelay(tab); }, 500);
|
|
||||||
} else {
|
|
||||||
tab.platform = newPlatform;
|
|
||||||
}
|
|
||||||
if (tab.tunnelMode === 'pion-video') {
|
|
||||||
var hookFile = isTelemost ? 'video-telemost.js' : 'video-vk.js';
|
|
||||||
var hook = fs.readFileSync(path.join(hooksDir, hookFile), 'utf8');
|
|
||||||
return logCapture + 'window.PION_PORT=' + tab.pionPort + ';window.IS_CREATOR=true;' + hook;
|
|
||||||
}
|
|
||||||
var hookFile = isTelemost ? 'dc-creator-telemost.js' : 'dc-creator-vk.js';
|
|
||||||
var hook = fs.readFileSync(path.join(hooksDir, hookFile), 'utf8');
|
|
||||||
return logCapture + 'window.WS_PORT=' + tab.dcPort + ';' + hook;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getVKCookieString() {
|
|
||||||
var ses = session.fromPartition('persist:creator');
|
|
||||||
var all = await ses.cookies.get({});
|
|
||||||
var vkCookies = all.filter(function(c) {
|
|
||||||
return c.domain && (c.domain.indexOf('vk.com') !== -1 || c.domain.indexOf('vk.ru') !== -1);
|
|
||||||
});
|
|
||||||
return vkCookies.map(function(c) { return c.name + '=' + c.value; }).join('; ');
|
|
||||||
}
|
|
||||||
|
|
||||||
function startRelay(tab) {
|
|
||||||
killRelay(tab);
|
|
||||||
var port = tab.tunnelMode.startsWith('pion') ? tab.pionPort : tab.dcPort;
|
|
||||||
var relayMode = 'dc-creator';
|
|
||||||
if (tab.tunnelMode === 'pion-video') {
|
|
||||||
relayMode = tab.platform === 'telemost' ? 'telemost-video-creator' : 'vk-video-creator';
|
|
||||||
}
|
|
||||||
var proc = spawn(relayPath, ['--mode', relayMode, '--ws-port', String(port)], {
|
|
||||||
stdio: ['ignore', 'pipe', 'pipe']
|
|
||||||
});
|
|
||||||
tab.relay = proc;
|
|
||||||
var tabId = null;
|
|
||||||
tabs.forEach(function(t, id) { if (t === tab) tabId = id; });
|
|
||||||
var onData = function(data) {
|
|
||||||
data.toString().trim().split('\n').forEach(function(msg) {
|
|
||||||
if (!msg) return;
|
|
||||||
console.log('[relay:' + tabId + ']', msg);
|
|
||||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
|
||||||
mainWindow.webContents.send('relay-log', { tabId: tabId, msg: msg });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
proc.stdout.on('data', onData);
|
|
||||||
proc.stderr.on('data', onData);
|
|
||||||
proc.on('close', function(code) {
|
|
||||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
|
||||||
mainWindow.webContents.send('relay-log', { tabId: tabId, msg: 'Relay exited with code ' + code });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function killRelay(tab) {
|
|
||||||
if (tab.relay) {
|
|
||||||
tab.relay.kill();
|
|
||||||
tab.relay = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function killAllRelays() {
|
|
||||||
tabs.forEach(function(tab) { killRelay(tab); });
|
|
||||||
}
|
|
||||||
|
|
||||||
function stripCSP(ses) {
|
|
||||||
ses.webRequest.onHeadersReceived(function(details, callback) {
|
|
||||||
var headers = Object.assign({}, details.responseHeaders);
|
|
||||||
delete headers['content-security-policy'];
|
|
||||||
delete headers['Content-Security-Policy'];
|
|
||||||
delete headers['content-security-policy-report-only'];
|
|
||||||
delete headers['Content-Security-Policy-Report-Only'];
|
|
||||||
callback({ responseHeaders: headers });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function createWindow() {
|
|
||||||
var ses = session.fromPartition('persist:creator');
|
|
||||||
stripCSP(ses);
|
|
||||||
ses.setPermissionRequestHandler(function(wc, perm, cb) { cb(true); });
|
|
||||||
ses.setPermissionCheckHandler(function() { return true; });
|
|
||||||
ses.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
|
|
||||||
app.on('session-created', stripCSP);
|
|
||||||
|
|
||||||
mainWindow = new BrowserWindow({
|
|
||||||
width: 1200,
|
|
||||||
height: 800,
|
|
||||||
icon: path.join(__dirname, 'resources', 'icon.png'),
|
|
||||||
webPreferences: {
|
|
||||||
preload: path.join(__dirname, 'preload.js'),
|
|
||||||
nodeIntegration: false,
|
|
||||||
contextIsolation: true,
|
|
||||||
webviewTag: true
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
mainWindow.loadFile('index.html');
|
|
||||||
mainWindow.on('closed', function() { mainWindow = null; });
|
|
||||||
|
|
||||||
var autoclickers = new Map(); // tabId -> { telemost, vk }
|
|
||||||
|
|
||||||
mainWindow.webContents.on('did-attach-webview', function(e, wvContents) {
|
|
||||||
wvContents.on('before-input-event', function(e, input) {
|
|
||||||
if (input.key === 'F12') wvContents.openDevTools();
|
|
||||||
});
|
|
||||||
wvContents.on('did-navigate', function(e, url) {
|
|
||||||
var tabId = wvContents.id;
|
|
||||||
if (!autoclickers.has(tabId)) {
|
|
||||||
autoclickers.set(tabId, { telemost: new TelemostAutoclick(), vk: new VkAutoclick() });
|
|
||||||
}
|
|
||||||
var ac = autoclickers.get(tabId);
|
|
||||||
if (url.includes('telemost.yandex')) {
|
|
||||||
ac.vk.stop();
|
|
||||||
ac.telemost.attach(wvContents);
|
|
||||||
} else if (url.includes('vk.com')) {
|
|
||||||
ac.telemost.stop();
|
|
||||||
ac.vk.attach(wvContents);
|
|
||||||
} else {
|
|
||||||
ac.telemost.stop();
|
|
||||||
ac.vk.stop();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
wvContents.on('console-message', function(e, level, msg) {
|
|
||||||
if (msg.indexOf('state: disconnected') !== -1 || msg.indexOf('state: failed') !== -1) {
|
|
||||||
var ac = autoclickers.get(wvContents.id);
|
|
||||||
if (ac) ac.vk.kickDisconnected();
|
|
||||||
}
|
|
||||||
if (msg.indexOf('[BOT] VKCalls: call link:') !== -1) {
|
|
||||||
var link = msg.split('[BOT] VKCalls: call link:')[1].trim();
|
|
||||||
console.log('[MAIN] VK call link captured:', link);
|
|
||||||
|
|
||||||
var foundPeerId = null;
|
|
||||||
tabs.forEach(function(t, id) {
|
|
||||||
if (botTabs.has(id) && t.platform === 'vk') {
|
|
||||||
foundPeerId = t.peerId;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (foundPeerId && botManager) {
|
|
||||||
console.log('[MAIN] Sending VK link to peer:', foundPeerId);
|
|
||||||
botManager.sendMessage(foundPeerId, 'Call created!\n ' + link);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (msg.indexOf('[BOT] Telemost: call link:') !== -1) {
|
|
||||||
var link = msg.split('[BOT] Telemost: call link:')[1].trim();
|
|
||||||
console.log('[MAIN] Telemost call link captured:', link);
|
|
||||||
|
|
||||||
var foundPeerId = null;
|
|
||||||
tabs.forEach(function(t, id) {
|
|
||||||
if (botTabs.has(id) && t.platform === 'telemost') {
|
|
||||||
foundPeerId = t.peerId;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (foundPeerId && botManager) {
|
|
||||||
console.log('[MAIN] Sending Telemost link to peer:', foundPeerId);
|
|
||||||
botManager.sendMessage(foundPeerId, 'Call created!\n ' + link);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (msg.indexOf('[CALL_STATUS]') !== -1) {
|
|
||||||
console.log('[MAIN] Received call status:', msg);
|
|
||||||
if (msg.indexOf(':') !== -1) {
|
|
||||||
var parts = msg.split('[CALL_STATUS] ')[1];
|
|
||||||
var colonIndex = parts.indexOf(':');
|
|
||||||
if (colonIndex !== -1) {
|
|
||||||
var tabId = parts.substring(0, colonIndex);
|
|
||||||
var status = parts.substring(colonIndex + 1);
|
|
||||||
callStatusCache.set(tabId, status);
|
|
||||||
console.log('[MAIN] Cached status for', tabId, ':', status);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
wvContents.on('destroyed', function() {
|
|
||||||
var ac = autoclickers.get(wvContents.id);
|
|
||||||
if (ac) { ac.telemost.stop(); ac.vk.stop(); autoclickers.delete(wvContents.id); }
|
|
||||||
callStatusCache.forEach(function(status, tabId) {
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
ipcMain.handle('get-hook-code', async function(e, tabId, url) {
|
|
||||||
var tab = await getTab(tabId);
|
|
||||||
return loadHook(url, tab);
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.handle('get-call-creator-code', function(e, scriptFile) {
|
|
||||||
var filePath = path.join(__dirname, scriptFile || 'vk-call-creator.js');
|
|
||||||
return fs.readFileSync(filePath, 'utf8');
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.handle('set-tunnel-mode', function(e, tabId, mode) {
|
|
||||||
var tab = tabs.get(tabId);
|
|
||||||
if (!tab) return;
|
|
||||||
if (['dc', 'pion-video'].indexOf(mode) === -1) return;
|
|
||||||
tab.tunnelMode = mode;
|
|
||||||
if (tab.relay) killRelay(tab);
|
|
||||||
setTimeout(function() { startRelay(tab); }, 500);
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.handle('start-relay', async function(e, tabId) {
|
|
||||||
var tab = await getTab(tabId);
|
|
||||||
startRelay(tab);
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.handle('start-headless', async function(e, tabId) {
|
|
||||||
var tab = await getTab(tabId);
|
|
||||||
tab.tunnelMode = 'headless-vk';
|
|
||||||
var cookieStr = await getVKCookieString();
|
|
||||||
if (!cookieStr) {
|
|
||||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
|
||||||
mainWindow.webContents.send('relay-log', { tabId: tabId, msg: 'No VK cookies found. Please log into VK first.' });
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
killRelay(tab);
|
|
||||||
var args = ['--cookie-string', cookieStr, '--resources', 'default'];
|
|
||||||
var proc = spawn(headlessPath, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
||||||
tab.relay = proc;
|
|
||||||
var onData = function(data) {
|
|
||||||
data.toString().trim().split('\n').forEach(function(msg) {
|
|
||||||
if (!msg) return;
|
|
||||||
console.log('[headless:' + tabId + ']', msg);
|
|
||||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
|
||||||
mainWindow.webContents.send('relay-log', { tabId: tabId, msg: msg });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
proc.stdout.on('data', onData);
|
|
||||||
proc.stderr.on('data', onData);
|
|
||||||
proc.on('close', function(code) {
|
|
||||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
|
||||||
mainWindow.webContents.send('relay-log', { tabId: tabId, msg: 'Headless exited with code ' + code });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.handle('close-tab', function(e, tabId) {
|
|
||||||
var tab = tabs.get(tabId);
|
|
||||||
if (tab) {
|
|
||||||
killRelay(tab);
|
|
||||||
tabs.delete(tabId);
|
|
||||||
}
|
|
||||||
botTabs.delete(tabId);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Bot IPC
|
|
||||||
ipcMain.handle('start-bot', function(e, settings) {
|
|
||||||
if (botManager) {
|
|
||||||
botManager.stop();
|
|
||||||
}
|
|
||||||
botManager = new BotManager(settings, async function(tabConfig) {
|
|
||||||
if (!mainWindow || mainWindow.isDestroyed()) return;
|
|
||||||
|
|
||||||
var tabId = 'bot-tab-' + Date.now();
|
|
||||||
var ports = await allocPorts();
|
|
||||||
tabs.set(tabId, { relay: null, tunnelMode: tabConfig.mode, platform: tabConfig.platform || 'vk', dcPort: ports.dc, pionPort: ports.pion, peerId: tabConfig.peerId, isBot: true });
|
|
||||||
botTabs.add(tabId);
|
|
||||||
|
|
||||||
mainWindow.webContents.send('create-bot-tab', { tabId: tabId, mode: tabConfig.mode, peerId: tabConfig.peerId, platform: tabConfig.platform || 'vk' });
|
|
||||||
console.log('[BOT] Created tab:', tabId, 'mode:', tabConfig.mode, 'platform:', tabConfig.platform, 'peerId:', tabConfig.peerId);
|
|
||||||
}, function() {
|
|
||||||
var result = [];
|
|
||||||
tabs.forEach(function(tab, tabId) {
|
|
||||||
result.push({
|
|
||||||
id: tabId,
|
|
||||||
platform: tab.platform,
|
|
||||||
mode: tab.tunnelMode,
|
|
||||||
isBot: tab.isBot === true,
|
|
||||||
callStatus: callStatusCache.get(tabId) || 'inactive'
|
|
||||||
});
|
|
||||||
});
|
|
||||||
return result;
|
|
||||||
}, function(tabId) {
|
|
||||||
var tab = tabs.get(tabId);
|
|
||||||
if (tab) {
|
|
||||||
killRelay(tab);
|
|
||||||
tabs.delete(tabId);
|
|
||||||
botTabs.delete(tabId);
|
|
||||||
callStatusCache.delete(tabId);
|
|
||||||
console.log('[BOT] Closed tab:', tabId);
|
|
||||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
|
||||||
mainWindow.webContents.send('close-bot-tab', { tabId: tabId });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
botManager.onError = function(msg) {
|
|
||||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
|
||||||
mainWindow.webContents.send('bot-error', msg);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
botManager.start();
|
|
||||||
return { success: true };
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.handle('stop-bot', function() {
|
|
||||||
if (botManager) {
|
|
||||||
botManager.stop();
|
|
||||||
botManager = null;
|
|
||||||
}
|
|
||||||
return { success: true };
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.handle('get-cookies', async function(e, domain) {
|
|
||||||
var ses = session.fromPartition('persist:creator');
|
|
||||||
var all = await ses.cookies.get({});
|
|
||||||
var vkCookies = all.filter(function(c) {
|
|
||||||
return c.domain && (c.domain.indexOf('vk.com') !== -1 || c.domain.indexOf('vk.ru') !== -1);
|
|
||||||
});
|
|
||||||
console.log('[COOKIES] total:', all.length, 'vk:', vkCookies.length);
|
|
||||||
return vkCookies;
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
app.whenReady().then(createWindow);
|
|
||||||
|
|
||||||
app.on('window-all-closed', function() { killAllRelays(); app.quit(); });
|
|
||||||
app.on('before-quit', killAllRelays);
|
|
||||||
process.on('exit', killAllRelays);
|
|
||||||
process.on('SIGINT', function() { killAllRelays(); process.exit(); });
|
|
||||||
process.on('SIGTERM', function() { killAllRelays(); process.exit(); });
|
|
||||||
Generated
+30
-6
@@ -1,18 +1,21 @@
|
|||||||
{
|
{
|
||||||
"name": "whitelist-bypass-creator",
|
"name": "whitelist-bypass-creator",
|
||||||
"version": "0.1.9",
|
"version": "0.2.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "whitelist-bypass-creator",
|
"name": "whitelist-bypass-creator",
|
||||||
"version": "0.1.9",
|
"version": "0.2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"node-fetch": "^2.7.0"
|
"node-fetch": "^2.7.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"@types/node-fetch": "^2.6.13",
|
||||||
"electron": "^33.0.0",
|
"electron": "^33.0.0",
|
||||||
"electron-builder": "^25.0.0"
|
"electron-builder": "^25.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@develar/schema-utils": {
|
"node_modules/@develar/schema-utils": {
|
||||||
@@ -736,15 +739,26 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@types/node": {
|
"node_modules/@types/node": {
|
||||||
"version": "20.19.37",
|
"version": "22.19.17",
|
||||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.37.tgz",
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.17.tgz",
|
||||||
"integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==",
|
"integrity": "sha512-wGdMcf+vPYM6jikpS/qhg6WiqSV/OhG+jeeHT/KlVqxYfD40iYJf9/AE1uQxVWFvU7MipKRkRv8NSHiCGgPr8Q==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"undici-types": "~6.21.0"
|
"undici-types": "~6.21.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/node-fetch": {
|
||||||
|
"version": "2.6.13",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz",
|
||||||
|
"integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/node": "*",
|
||||||
|
"form-data": "^4.0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@types/plist": {
|
"node_modules/@types/plist": {
|
||||||
"version": "3.0.5",
|
"version": "3.0.5",
|
||||||
"resolved": "https://registry.npmjs.org/@types/plist/-/plist-3.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/@types/plist/-/plist-3.0.5.tgz",
|
||||||
@@ -2406,6 +2420,16 @@
|
|||||||
"node": ">= 10.0.0"
|
"node": ">= 10.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/electron/node_modules/@types/node": {
|
||||||
|
"version": "20.19.39",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.39.tgz",
|
||||||
|
"integrity": "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"undici-types": "~6.21.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/emoji-regex": {
|
"node_modules/emoji-regex": {
|
||||||
"version": "8.0.0",
|
"version": "8.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||||
|
|||||||
+68
-15
@@ -1,17 +1,21 @@
|
|||||||
{
|
{
|
||||||
"name": "whitelist-bypass-creator",
|
"name": "whitelist-bypass-creator",
|
||||||
"version": "0.1.9",
|
"version": "0.2.0",
|
||||||
"main": "main.js",
|
"main": "dist/main/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "electron .",
|
"build": "tsc",
|
||||||
"build": "electron-builder"
|
"start": "tsc && electron .",
|
||||||
|
"start:dev": "electron ."
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"node-fetch": "^2.7.0"
|
"node-fetch": "^2.7.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.0.0",
|
||||||
|
"@types/node-fetch": "^2.6.13",
|
||||||
"electron": "^33.0.0",
|
"electron": "^33.0.0",
|
||||||
"electron-builder": "^25.0.0"
|
"electron-builder": "^25.0.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
},
|
},
|
||||||
"build": {
|
"build": {
|
||||||
"appId": "whitelist.bypass.creator",
|
"appId": "whitelist.bypass.creator",
|
||||||
@@ -19,18 +23,47 @@
|
|||||||
"directories": {
|
"directories": {
|
||||||
"output": "../prebuilts"
|
"output": "../prebuilts"
|
||||||
},
|
},
|
||||||
|
"files": [
|
||||||
|
"dist/**/*",
|
||||||
|
"index.html",
|
||||||
|
"styles/**/*",
|
||||||
|
"scripts/**/*",
|
||||||
|
"resources/**/*"
|
||||||
|
],
|
||||||
"extraResources": [
|
"extraResources": [
|
||||||
{ "from": "../hooks/dc-creator-vk.js", "to": "hooks/dc-creator-vk.js" },
|
{
|
||||||
{ "from": "../hooks/dc-creator-telemost.js", "to": "hooks/dc-creator-telemost.js" },
|
"from": "../hooks/dc-creator-vk.js",
|
||||||
{ "from": "../hooks/video-vk.js", "to": "hooks/video-vk.js" },
|
"to": "hooks/dc-creator-vk.js"
|
||||||
{ "from": "../hooks/video-telemost.js", "to": "hooks/video-telemost.js" }
|
},
|
||||||
|
{
|
||||||
|
"from": "../hooks/dc-creator-telemost.js",
|
||||||
|
"to": "hooks/dc-creator-telemost.js"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "../hooks/video-vk.js",
|
||||||
|
"to": "hooks/video-vk.js"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "../hooks/video-telemost.js",
|
||||||
|
"to": "hooks/video-telemost.js"
|
||||||
|
}
|
||||||
],
|
],
|
||||||
"mac": {
|
"mac": {
|
||||||
"target": "dmg",
|
"target": "dmg",
|
||||||
"icon": "resources/icon.icns",
|
"icon": "resources/icon.icns",
|
||||||
"extraResources": [
|
"extraResources": [
|
||||||
{ "from": "../relay/relay-darwin", "to": "relay" },
|
{
|
||||||
{ "from": "../headless/headless-darwin", "to": "headless-creator" }
|
"from": "../relay/relay-darwin",
|
||||||
|
"to": "relay"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "../headless/headless-vk-darwin",
|
||||||
|
"to": "headless-vk-creator"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "../headless/headless-telemost-darwin",
|
||||||
|
"to": "headless-telemost-creator"
|
||||||
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"win": {
|
"win": {
|
||||||
@@ -38,16 +71,36 @@
|
|||||||
"artifactName": "${productName}-${version}-${arch}.${ext}",
|
"artifactName": "${productName}-${version}-${arch}.${ext}",
|
||||||
"icon": "resources/icon.ico",
|
"icon": "resources/icon.ico",
|
||||||
"extraResources": [
|
"extraResources": [
|
||||||
{ "from": "../relay/relay-bundle.exe", "to": "relay.exe" },
|
{
|
||||||
{ "from": "../headless/headless-bundle.exe", "to": "headless-creator.exe" }
|
"from": "../relay/relay-bundle.exe",
|
||||||
|
"to": "relay.exe"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "../headless/headless-vk-bundle.exe",
|
||||||
|
"to": "headless-vk-creator.exe"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "../headless/headless-telemost-bundle.exe",
|
||||||
|
"to": "headless-telemost-creator.exe"
|
||||||
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"linux": {
|
"linux": {
|
||||||
"target": "AppImage",
|
"target": "AppImage",
|
||||||
"icon": "resources/icon.png",
|
"icon": "resources/icon.png",
|
||||||
"extraResources": [
|
"extraResources": [
|
||||||
{ "from": "../relay/relay-bundle", "to": "relay" },
|
{
|
||||||
{ "from": "../headless/headless-bundle", "to": "headless-creator" }
|
"from": "../relay/relay-bundle",
|
||||||
|
"to": "relay"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "../headless/headless-vk-bundle",
|
||||||
|
"to": "headless-vk-creator"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "../headless/headless-telemost-bundle",
|
||||||
|
"to": "headless-telemost-creator"
|
||||||
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
const { contextBridge, ipcRenderer } = require('electron');
|
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld('bridge', {
|
|
||||||
onRelayLog: function(cb) { ipcRenderer.on('relay-log', function(e, data) { cb(data.tabId, data.msg); }); },
|
|
||||||
getHookCode: function(tabId, url) { return ipcRenderer.invoke('get-hook-code', tabId, url); },
|
|
||||||
setTunnelMode: function(tabId, mode) { return ipcRenderer.invoke('set-tunnel-mode', tabId, mode); },
|
|
||||||
startRelay: function(tabId) { return ipcRenderer.invoke('start-relay', tabId); },
|
|
||||||
closeTab: function(tabId) { return ipcRenderer.invoke('close-tab', tabId); },
|
|
||||||
startBot: function(settings) { return ipcRenderer.invoke('start-bot', settings); },
|
|
||||||
stopBot: function() { return ipcRenderer.invoke('stop-bot'); },
|
|
||||||
onCreateBotTab: function(cb) { ipcRenderer.on('create-bot-tab', function(e, data) { cb(data); }); },
|
|
||||||
getCallCreatorCode: function(scriptFile) { return ipcRenderer.invoke('get-call-creator-code', scriptFile); },
|
|
||||||
onBotError: function(cb) { ipcRenderer.on('bot-error', function(e, msg) { cb(msg); }); },
|
|
||||||
getCookies: function(domain) { return ipcRenderer.invoke('get-cookies', domain); },
|
|
||||||
startHeadless: function(tabId) { return ipcRenderer.invoke('start-headless', tabId); },
|
|
||||||
onCloseBotTab: function(cb) { ipcRenderer.on('close-bot-tab', function(e, data) { cb(data); }); }
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
(function() {
|
||||||
|
if (window.__callCheckerStarted) return;
|
||||||
|
window.__callCheckerStarted = true;
|
||||||
|
|
||||||
|
var tabId = window.__CALL_CHECKER_TAB_ID || 'unknown';
|
||||||
|
console.log('[CALL_STATUS] Checker started for ' + tabId);
|
||||||
|
|
||||||
|
var CHECK_INTERVAL = 10000;
|
||||||
|
var INITIAL_DELAY = 10000;
|
||||||
|
|
||||||
|
var VK_LEAVE_SELECTOR = '[data-testid="calls_call_footer_button_leave_call"]';
|
||||||
|
var TM_END_SELECTOR = '[data-testid="end-call-alt-button"]';
|
||||||
|
|
||||||
|
var checkCallStatus = function() {
|
||||||
|
var vkBtn = document.querySelector(VK_LEAVE_SELECTOR);
|
||||||
|
var tmBtn = document.querySelector(TM_END_SELECTOR);
|
||||||
|
var status = (vkBtn || tmBtn) ? 'active' : 'inactive';
|
||||||
|
console.log('[CALL_STATUS] ' + tabId + ':' + status);
|
||||||
|
};
|
||||||
|
|
||||||
|
setTimeout(function() {
|
||||||
|
checkCallStatus();
|
||||||
|
setInterval(checkCallStatus, CHECK_INTERVAL);
|
||||||
|
}, INITIAL_DELAY);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
(function() {
|
||||||
|
if (window.__tmCallCreatorStarted) return;
|
||||||
|
window.__tmCallCreatorStarted = true;
|
||||||
|
|
||||||
|
var CREATE_BUTTON_SELECTOR = '[data-testid="create-call-button"]';
|
||||||
|
var CALL_PATH_MARKER = '/j/';
|
||||||
|
var CHECK_INTERVAL = 300;
|
||||||
|
|
||||||
|
var start = function() {
|
||||||
|
console.log("[BOT] Telemost: DOM ready...");
|
||||||
|
|
||||||
|
var waitAndClick = function(fn) {
|
||||||
|
if (fn()) return;
|
||||||
|
var observer = new MutationObserver(function() {
|
||||||
|
if (fn()) observer.disconnect();
|
||||||
|
});
|
||||||
|
observer.observe(document.body, { childList: true, subtree: true });
|
||||||
|
};
|
||||||
|
|
||||||
|
waitAndClick(function() {
|
||||||
|
var btn = document.querySelector(CREATE_BUTTON_SELECTOR);
|
||||||
|
if (!btn) return false;
|
||||||
|
|
||||||
|
btn.click();
|
||||||
|
console.log("[BOT] Telemost: creating call...");
|
||||||
|
|
||||||
|
var check = setInterval(function() {
|
||||||
|
var url = location.href;
|
||||||
|
if (url.indexOf(CALL_PATH_MARKER) !== -1) {
|
||||||
|
console.log("[BOT] Telemost: call link:", url);
|
||||||
|
window.__CALL_LINK__ = url;
|
||||||
|
clearInterval(check);
|
||||||
|
}
|
||||||
|
}, CHECK_INTERVAL);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
if (document.readyState === "loading") {
|
||||||
|
document.addEventListener("DOMContentLoaded", start);
|
||||||
|
} else {
|
||||||
|
start();
|
||||||
|
}
|
||||||
|
})();
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
(function() {
|
||||||
|
if (window.__callCreatorStarted) return;
|
||||||
|
window.__callCreatorStarted = true;
|
||||||
|
|
||||||
|
var CALL_MENU_TRIGGER_ID = 'call-menu-trigger';
|
||||||
|
var CREATE_CALL_TEXT = 'Создать звонок по';
|
||||||
|
var CALL_IN_PROGRESS_KEY = 'call_in_progress';
|
||||||
|
var VK_CALL_BASE = 'https://vk.com/call/join/';
|
||||||
|
|
||||||
|
var start = function() {
|
||||||
|
console.log("[BOT] VKCalls: DOM ready...");
|
||||||
|
|
||||||
|
var waitAndClick = function(fn) {
|
||||||
|
if (fn()) return;
|
||||||
|
var observer = new MutationObserver(function() {
|
||||||
|
if (fn()) observer.disconnect();
|
||||||
|
});
|
||||||
|
observer.observe(document.body, { childList: true, subtree: true });
|
||||||
|
};
|
||||||
|
|
||||||
|
waitAndClick(function() {
|
||||||
|
var trigger = document.getElementById(CALL_MENU_TRIGGER_ID);
|
||||||
|
if (!trigger) return false;
|
||||||
|
|
||||||
|
trigger.click();
|
||||||
|
console.log("[BOT] VKCalls: opened call menu");
|
||||||
|
|
||||||
|
waitAndClick(function() {
|
||||||
|
var spans = document.querySelectorAll('span');
|
||||||
|
var el = null;
|
||||||
|
for (var i = 0; i < spans.length; i++) {
|
||||||
|
if (spans[i].textContent.indexOf(CREATE_CALL_TEXT) !== -1) {
|
||||||
|
el = spans[i];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var btn = el ? (el.closest('button') || el.closest('div')) : null;
|
||||||
|
if (!btn) return false;
|
||||||
|
|
||||||
|
btn.click();
|
||||||
|
console.log("[BOT] VKCalls: created call");
|
||||||
|
|
||||||
|
var origFetch = window.fetch;
|
||||||
|
window.fetch = function() {
|
||||||
|
var args = arguments;
|
||||||
|
return origFetch.apply(window, args).then(function(res) {
|
||||||
|
if (window.__CALL_LINK_CAPTURED__) return res;
|
||||||
|
try {
|
||||||
|
var clone = res.clone();
|
||||||
|
clone.text().then(function(text) {
|
||||||
|
if (text.indexOf(CALL_IN_PROGRESS_KEY) === -1) return;
|
||||||
|
var json = JSON.parse(text);
|
||||||
|
var items = json && json.response && json.response[1] && json.response[1].items;
|
||||||
|
if (!items) return;
|
||||||
|
for (var j = 0; j < items.length; j++) {
|
||||||
|
var join = items[j] && items[j].call_in_progress && items[j].call_in_progress.join_link;
|
||||||
|
if (join) {
|
||||||
|
var link = VK_CALL_BASE + join;
|
||||||
|
console.log("[BOT] VKCalls: call link:", link);
|
||||||
|
window.__CALL_LINK__ = link;
|
||||||
|
window.__CALL_LINK_CAPTURED__ = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {}
|
||||||
|
return res;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
if (document.readyState === "loading") {
|
||||||
|
document.addEventListener("DOMContentLoaded", start);
|
||||||
|
} else {
|
||||||
|
start();
|
||||||
|
}
|
||||||
|
})();
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import { SCAN_INTERVAL_MS, KICK_DELAY_MS, Selector } from '../constants';
|
||||||
|
|
||||||
|
export class TelemostAutoclick {
|
||||||
|
private interval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
private wvContents: Electron.WebContents | null = null;
|
||||||
|
|
||||||
|
attach(wvContents: Electron.WebContents): void {
|
||||||
|
this.stop();
|
||||||
|
this.wvContents = wvContents;
|
||||||
|
this.interval = setInterval(() => this.scan(), SCAN_INTERVAL_MS);
|
||||||
|
wvContents.on('destroyed', () => this.stop());
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
if (this.interval) {
|
||||||
|
clearInterval(this.interval);
|
||||||
|
this.interval = null;
|
||||||
|
}
|
||||||
|
this.wvContents = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private scan(): void {
|
||||||
|
if (!this.wvContents) return;
|
||||||
|
try {
|
||||||
|
this.wvContents.mainFrame.framesInSubtree.forEach((frame) => {
|
||||||
|
(frame
|
||||||
|
.executeJavaScript(
|
||||||
|
`(function() {
|
||||||
|
var buttons = document.querySelectorAll('.Orb-Button, button, [role="button"], [role="link"]');
|
||||||
|
var admitBtn = null;
|
||||||
|
for (var i = 0; i < buttons.length; i++) {
|
||||||
|
var txt = buttons[i].textContent.replace(/\\s+/g, ' ').trim();
|
||||||
|
if (txt.indexOf('Впустить') !== -1) {
|
||||||
|
admitBtn = buttons[i];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!admitBtn) return 'idle';
|
||||||
|
var names = document.querySelectorAll('[class*="participantName"]');
|
||||||
|
for (var j = 0; j < names.length; j++) {
|
||||||
|
if (names[j].closest('[class*="selfView"]')) continue;
|
||||||
|
var moreBtn = names[j].querySelector('${Selector.TM_MODERATION_POPUP}');
|
||||||
|
if (moreBtn) {
|
||||||
|
moreBtn.click();
|
||||||
|
return 'kick-open';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
admitBtn.click();
|
||||||
|
return 'admitted';
|
||||||
|
})()`,
|
||||||
|
) as Promise<string>)
|
||||||
|
.then((result) => {
|
||||||
|
if (result ==='kick-open') {
|
||||||
|
setTimeout(() => this.clickRemove(frame), KICK_DELAY_MS);
|
||||||
|
} else if (result ==='admitted') {
|
||||||
|
console.log('[auto-accept] guest admitted');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
private clickRemove(frame: Electron.WebFrameMain): void {
|
||||||
|
(frame
|
||||||
|
.executeJavaScript(
|
||||||
|
`(function() {
|
||||||
|
var el = document.querySelector('[title="Удалить со встречи"]');
|
||||||
|
if (el) { el.click(); return true; }
|
||||||
|
return false;
|
||||||
|
})()`,
|
||||||
|
) as Promise<boolean>)
|
||||||
|
.then((result) => {
|
||||||
|
if (result) setTimeout(() => this.confirmRemove(frame), KICK_DELAY_MS);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
private confirmRemove(frame: Electron.WebFrameMain): void {
|
||||||
|
(frame
|
||||||
|
.executeJavaScript(
|
||||||
|
`(function() {
|
||||||
|
var modal = document.querySelector('${Selector.TM_MODAL}');
|
||||||
|
if (!modal) return false;
|
||||||
|
var btns = modal.querySelectorAll('button');
|
||||||
|
for (var i = 0; i < btns.length; i++) {
|
||||||
|
var txt = btns[i].textContent.replace(/\\s+/g, ' ').trim();
|
||||||
|
if (txt === 'Удалить') {
|
||||||
|
btns[i].click();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
})()`,
|
||||||
|
) as Promise<boolean>)
|
||||||
|
.then((result) => {
|
||||||
|
if (result) console.log('[auto-accept] kicked previous participant');
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import { SCAN_INTERVAL_MS, KICK_DELAY_MS, Selector } from '../constants';
|
||||||
|
|
||||||
|
export class VkAutoclick {
|
||||||
|
private interval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
private wvContents: Electron.WebContents | null = null;
|
||||||
|
|
||||||
|
attach(wvContents: Electron.WebContents): void {
|
||||||
|
this.stop();
|
||||||
|
this.wvContents = wvContents;
|
||||||
|
this.interval = setInterval(() => this.scan(), SCAN_INTERVAL_MS);
|
||||||
|
wvContents.on('destroyed', () => this.stop());
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
if (this.interval) {
|
||||||
|
clearInterval(this.interval);
|
||||||
|
this.interval = null;
|
||||||
|
}
|
||||||
|
this.wvContents = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private scan(): void {
|
||||||
|
if (!this.wvContents) return;
|
||||||
|
try {
|
||||||
|
this.wvContents.mainFrame.framesInSubtree.forEach((frame) => {
|
||||||
|
(frame
|
||||||
|
.executeJavaScript(
|
||||||
|
`(function() {
|
||||||
|
var admitBtn = document.querySelector('${Selector.VK_ADMIT}');
|
||||||
|
if (!admitBtn) return 'idle';
|
||||||
|
var menuBtns = document.querySelectorAll('${Selector.VK_PARTICIPANT_MENU}');
|
||||||
|
if (menuBtns.length > 1) {
|
||||||
|
menuBtns[menuBtns.length - 1].click();
|
||||||
|
return 'kick-open';
|
||||||
|
}
|
||||||
|
admitBtn.click();
|
||||||
|
return 'admitted';
|
||||||
|
})()`,
|
||||||
|
) as Promise<string>)
|
||||||
|
.then((result) => {
|
||||||
|
if (result ==='kick-open') {
|
||||||
|
setTimeout(() => this.clickKick(frame), KICK_DELAY_MS);
|
||||||
|
} else if (result ==='admitted') {
|
||||||
|
console.log('[auto-accept] VK guest admitted');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
private clickKick(frame: Electron.WebFrameMain): void {
|
||||||
|
(frame
|
||||||
|
.executeJavaScript(
|
||||||
|
`(function() {
|
||||||
|
var btn = document.querySelector('${Selector.VK_KICK}');
|
||||||
|
if (btn) { btn.click(); return true; }
|
||||||
|
return false;
|
||||||
|
})()`,
|
||||||
|
) as Promise<boolean>)
|
||||||
|
.then((result) => {
|
||||||
|
if (result) setTimeout(() => this.confirmKick(frame), KICK_DELAY_MS);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
private confirmKick(frame: Electron.WebFrameMain): void {
|
||||||
|
(frame
|
||||||
|
.executeJavaScript(
|
||||||
|
`(function() {
|
||||||
|
var btn = document.querySelector('${Selector.VK_KICK_CONFIRM}');
|
||||||
|
if (btn) { btn.click(); return true; }
|
||||||
|
return false;
|
||||||
|
})()`,
|
||||||
|
) as Promise<boolean>)
|
||||||
|
.then((result) => {
|
||||||
|
if (result) console.log('[auto-accept] VK kicked previous participant');
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
kickDisconnected(): void {
|
||||||
|
if (!this.wvContents) return;
|
||||||
|
try {
|
||||||
|
this.wvContents.mainFrame.framesInSubtree.forEach((frame) => {
|
||||||
|
(frame
|
||||||
|
.executeJavaScript(
|
||||||
|
`(function() {
|
||||||
|
var menuBtns = document.querySelectorAll('${Selector.VK_PARTICIPANT_MENU}');
|
||||||
|
var menuBtn = menuBtns.length > 1 ? menuBtns[menuBtns.length - 1] : null;
|
||||||
|
if (menuBtn) { menuBtn.click(); return true; }
|
||||||
|
return false;
|
||||||
|
})()`,
|
||||||
|
) as Promise<boolean>)
|
||||||
|
.then((result) => {
|
||||||
|
if (result) setTimeout(() => this.clickKick(frame), KICK_DELAY_MS);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
import fetch from 'node-fetch';
|
||||||
|
import { BotSettings, TabConfig, TabListEntry, TunnelMode, Platform, BotCommand } from '../types';
|
||||||
|
import { VK_API_VERSION, VK_API_BASE_URL, BOT_POLL_RETRY_DELAY_MS, BOT_POLL_WAIT_SECONDS } from '../constants';
|
||||||
|
import {
|
||||||
|
createMainKeyboard,
|
||||||
|
createListKeyboard,
|
||||||
|
findTabByShortId,
|
||||||
|
generateShortId,
|
||||||
|
padShortId,
|
||||||
|
} from './keyboard';
|
||||||
|
|
||||||
|
type CreateTabFn = (config: TabConfig) => Promise<void> | void;
|
||||||
|
type GetTabsFn = () => TabListEntry[];
|
||||||
|
type CloseTabFn = (tabId: string) => void;
|
||||||
|
|
||||||
|
interface VkApiError {
|
||||||
|
error_code: number;
|
||||||
|
error_msg?: string;
|
||||||
|
request_params?: unknown[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface VkApiResponse {
|
||||||
|
response?: any;
|
||||||
|
error?: VkApiError;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LongPollData {
|
||||||
|
ts?: string;
|
||||||
|
failed?: number;
|
||||||
|
updates?: any[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface VkMessage {
|
||||||
|
text?: string;
|
||||||
|
from_id: number;
|
||||||
|
peer_id: number;
|
||||||
|
payload?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ButtonPayload {
|
||||||
|
cmd: BotCommand;
|
||||||
|
mode?: string;
|
||||||
|
id?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BotManager {
|
||||||
|
private settings: BotSettings;
|
||||||
|
private onCreateTab: CreateTabFn;
|
||||||
|
private onGetTabs: GetTabsFn;
|
||||||
|
private onCloseTab: CloseTabFn;
|
||||||
|
private ts: string | null = null;
|
||||||
|
private key: string | null = null;
|
||||||
|
private server: string | null = null;
|
||||||
|
private running = false;
|
||||||
|
onError: ((msg: string) => void) | null = null;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
settings: BotSettings,
|
||||||
|
onCreateTab: CreateTabFn,
|
||||||
|
onGetTabs: GetTabsFn,
|
||||||
|
onCloseTab: CloseTabFn,
|
||||||
|
) {
|
||||||
|
this.settings = settings;
|
||||||
|
this.onCreateTab = onCreateTab;
|
||||||
|
this.onGetTabs = onGetTabs;
|
||||||
|
this.onCloseTab = onCloseTab;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async api(method: string, params: Record<string, any> = {}): Promise<any> {
|
||||||
|
params.v = VK_API_VERSION;
|
||||||
|
params.access_token = this.settings.token;
|
||||||
|
const url = new URL(`${VK_API_BASE_URL}/${method}`);
|
||||||
|
Object.keys(params).forEach((k) => url.searchParams.set(k, String(params[k])));
|
||||||
|
const res = await fetch(url.toString());
|
||||||
|
const data = (await res.json()) as VkApiResponse;
|
||||||
|
if (data.error) {
|
||||||
|
const err = data.error;
|
||||||
|
const errMsg =
|
||||||
|
`${method} code: ${err.error_code} msg: ${err.error_msg || 'VK API error'}` +
|
||||||
|
` params: ${JSON.stringify(err.request_params || [])}`;
|
||||||
|
console.error('[BOT] API error:', errMsg);
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
|
return data.response;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getLongPollServer(): Promise<void> {
|
||||||
|
const data = await this.api('groups.getLongPollServer', {
|
||||||
|
group_id: parseInt(this.settings.groupId, 10),
|
||||||
|
});
|
||||||
|
this.server = data.server;
|
||||||
|
this.key = data.key;
|
||||||
|
this.ts = data.ts;
|
||||||
|
}
|
||||||
|
|
||||||
|
async start(): Promise<void> {
|
||||||
|
this.running = true;
|
||||||
|
console.log('[BOT] Starting with settings:', this.settings);
|
||||||
|
try {
|
||||||
|
await this.getLongPollServer();
|
||||||
|
console.log('[BOT] LongPoll server:', this.server);
|
||||||
|
this.pollLoop();
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('[BOT] Failed to start:', err.message);
|
||||||
|
this.running = false;
|
||||||
|
if (this.onError) this.onError(err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
this.running = false;
|
||||||
|
console.log('[BOT] Stopped');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async pollLoop(): Promise<void> {
|
||||||
|
while (this.running) {
|
||||||
|
try {
|
||||||
|
const url = `${this.server}?act=a_check&key=${this.key}&ts=${this.ts}&wait=${BOT_POLL_WAIT_SECONDS}`;
|
||||||
|
const res = await fetch(url);
|
||||||
|
const data = (await res.json()) as LongPollData;
|
||||||
|
if (data.failed) {
|
||||||
|
console.log('[BOT] LongPoll failed, reconnecting...');
|
||||||
|
await this.getLongPollServer();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
this.ts = data.ts || this.ts;
|
||||||
|
for (const update of data.updates || []) {
|
||||||
|
await this.handleUpdate(update);
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('[BOT] Poll error:', err.message);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, BOT_POLL_RETRY_DELAY_MS));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleUpdate(update: any): Promise<void> {
|
||||||
|
if (update.type !== 'message_new') return;
|
||||||
|
|
||||||
|
const message: VkMessage = update.object.message;
|
||||||
|
let text = (message.text || '').trim();
|
||||||
|
const fromId = message.from_id;
|
||||||
|
const peerId = message.peer_id;
|
||||||
|
|
||||||
|
let payload: ButtonPayload | null = null;
|
||||||
|
if (message.payload) {
|
||||||
|
try {
|
||||||
|
payload = JSON.parse(message.payload);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('[BOT] Message from', fromId, ':', text, 'payload:', payload);
|
||||||
|
|
||||||
|
if (this.settings.userId && fromId.toString() !== this.settings.userId.toString()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (text === '/start' || text === 'start') {
|
||||||
|
await this.showMenu(peerId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payload?.cmd) {
|
||||||
|
const handled = await this.handlePayloadCommand(payload, peerId);
|
||||||
|
if (handled) return;
|
||||||
|
if (payload.cmd === BotCommand.VK) {
|
||||||
|
text = '/vk' + (payload.mode === 'video' ? ' video' : '');
|
||||||
|
} else if (payload.cmd === BotCommand.TM) {
|
||||||
|
text = '/tm' + (payload.mode === 'video' ? ' video' : '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.handleTextCommand(text, peerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handlePayloadCommand(payload: ButtonPayload, peerId: number): Promise<boolean> {
|
||||||
|
if (payload.cmd === BotCommand.List) {
|
||||||
|
await this.showList(peerId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (payload.cmd === BotCommand.Menu) {
|
||||||
|
await this.showMenu(peerId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (payload.cmd === BotCommand.Close && payload.id) {
|
||||||
|
const tabsList = this.onGetTabs();
|
||||||
|
const tab = tabsList.find((entry) => entry.id === payload.id);
|
||||||
|
if (tab) {
|
||||||
|
const shortId = padShortId(generateShortId(tab.id));
|
||||||
|
this.onCloseTab(tab.id);
|
||||||
|
await this.sendMessage(peerId, `${tab.platform} ${tab.mode} ${shortId} closed`, createMainKeyboard());
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleTextCommand(text: string, peerId: number): Promise<void> {
|
||||||
|
if (text.startsWith('/vk')) {
|
||||||
|
const mode = text.includes('video') ? TunnelMode.PionVideo : TunnelMode.DC;
|
||||||
|
console.log('[BOT] Creating VK tab with mode:', mode);
|
||||||
|
this.onCreateTab({ mode, peerId, platform: Platform.VK });
|
||||||
|
const label = mode === TunnelMode.DC ? 'DC' : 'Video';
|
||||||
|
await this.sendMessage(peerId, `Creating VK call (${label})`, createMainKeyboard());
|
||||||
|
} else if (text.startsWith('/tm')) {
|
||||||
|
const mode = text.includes('video') ? TunnelMode.PionVideo : TunnelMode.DC;
|
||||||
|
console.log('[BOT] Creating Telemost tab with mode:', mode);
|
||||||
|
this.onCreateTab({ mode, peerId, platform: Platform.Telemost });
|
||||||
|
const label = mode === TunnelMode.DC ? 'DC' : 'Video';
|
||||||
|
await this.sendMessage(peerId, `Creating Telemost call (${label})`, createMainKeyboard());
|
||||||
|
} else if (text === '/list') {
|
||||||
|
await this.showList(peerId);
|
||||||
|
} else if (text.startsWith('/close ')) {
|
||||||
|
const targetShortId = text.split(' ')[1];
|
||||||
|
console.log('[BOT] Close request for ID:', targetShortId);
|
||||||
|
const tabsList = this.onGetTabs();
|
||||||
|
const tab = findTabByShortId(tabsList, targetShortId);
|
||||||
|
if (!tab) {
|
||||||
|
await this.sendMessage(peerId, `Tab ${targetShortId} not found`, createMainKeyboard());
|
||||||
|
} else {
|
||||||
|
this.onCloseTab(tab.id);
|
||||||
|
await this.sendMessage(
|
||||||
|
peerId,
|
||||||
|
`${tab.platform} ${tab.mode} ${targetShortId} closed`,
|
||||||
|
createMainKeyboard(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendMessage(peerId: number, text: string, keyboard?: any): Promise<void> {
|
||||||
|
try {
|
||||||
|
const params: Record<string, any> = {
|
||||||
|
peer_id: peerId,
|
||||||
|
message: text,
|
||||||
|
random_id: Math.floor(Math.random() * 1e9),
|
||||||
|
};
|
||||||
|
if (keyboard) {
|
||||||
|
params.keyboard = JSON.stringify(keyboard);
|
||||||
|
}
|
||||||
|
await this.api('messages.send', params);
|
||||||
|
console.log('[BOT] Sent message to', peerId);
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('[BOT] Send message error:', err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async showMenu(peerId: number): Promise<void> {
|
||||||
|
await this.sendMessage(peerId, 'Select mode:', createMainKeyboard());
|
||||||
|
}
|
||||||
|
|
||||||
|
private async showList(peerId: number): Promise<void> {
|
||||||
|
const tabsList = this.onGetTabs();
|
||||||
|
if (tabsList.length === 0) {
|
||||||
|
await this.sendMessage(peerId, 'No active tabs', createMainKeyboard());
|
||||||
|
} else {
|
||||||
|
await this.sendMessage(peerId, 'Select tab to close:', createListKeyboard(tabsList));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { TabListEntry, BotCommand, CallStatus } from '../types';
|
||||||
|
|
||||||
|
export function generateShortId(tabId: string): number {
|
||||||
|
let hash = 0;
|
||||||
|
for (let i = 0; i < tabId.length; i++) {
|
||||||
|
hash = ((hash << 5) - hash) + tabId.charCodeAt(i);
|
||||||
|
hash = hash & hash;
|
||||||
|
}
|
||||||
|
return Math.abs(hash) % 10000;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function padShortId(id: number): string {
|
||||||
|
return ('000' + id).slice(-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function findTabByShortId(tabsList: TabListEntry[], shortId: string): TabListEntry | null {
|
||||||
|
const target = parseInt(shortId, 10);
|
||||||
|
for (const tab of tabsList) {
|
||||||
|
if (generateShortId(tab.id) === target) return tab;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createMainKeyboard() {
|
||||||
|
return {
|
||||||
|
one_time: false,
|
||||||
|
buttons: [
|
||||||
|
[
|
||||||
|
{ action: { type: 'text', label: 'VK DC', payload: JSON.stringify({ cmd: BotCommand.VK, mode: 'dc' }) } },
|
||||||
|
{ action: { type: 'text', label: 'VK Video', payload: JSON.stringify({ cmd: BotCommand.VK, mode: 'video' }) } },
|
||||||
|
],
|
||||||
|
[
|
||||||
|
{ action: { type: 'text', label: 'TM DC', payload: JSON.stringify({ cmd: BotCommand.TM, mode: 'dc' }) } },
|
||||||
|
{ action: { type: 'text', label: 'TM Video', payload: JSON.stringify({ cmd: BotCommand.TM, mode: 'video' }) } },
|
||||||
|
],
|
||||||
|
[
|
||||||
|
{ action: { type: 'text', label: 'Active Tabs', payload: JSON.stringify({ cmd: BotCommand.List }) } },
|
||||||
|
],
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createListKeyboard(tabsList: TabListEntry[]) {
|
||||||
|
const buttons = tabsList.map((entry) => {
|
||||||
|
const shortId = padShortId(generateShortId(entry.id));
|
||||||
|
const prefix = entry.isBot ? 'bot' : 'user';
|
||||||
|
const status = entry.callStatus === CallStatus.Active ? '+' : '-';
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
action: {
|
||||||
|
type: 'text',
|
||||||
|
label: `${prefix} ${entry.platform} ${entry.mode} ${shortId} ${status}`,
|
||||||
|
payload: JSON.stringify({ cmd: BotCommand.Close, id: entry.id }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
buttons.push([
|
||||||
|
{ action: { type: 'text', label: 'Back', payload: JSON.stringify({ cmd: BotCommand.Menu }) } },
|
||||||
|
]);
|
||||||
|
return { one_time: false, buttons };
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
export const INITIAL_PORT_BASE = 10000;
|
||||||
|
|
||||||
|
export const SCAN_INTERVAL_MS = 2000;
|
||||||
|
export const KICK_DELAY_MS = 500;
|
||||||
|
export const RELAY_RESTART_DELAY_MS = 500;
|
||||||
|
export const HOOK_POLL_INTERVAL_MS = 500;
|
||||||
|
export const CALL_CREATOR_INJECT_DELAY_MS = 1000;
|
||||||
|
export const BOT_POLL_RETRY_DELAY_MS = 1000;
|
||||||
|
export const BOT_POLL_WAIT_SECONDS = 25;
|
||||||
|
|
||||||
|
export const VK_API_VERSION = '5.131';
|
||||||
|
export const VK_API_BASE_URL = 'https://api.vk.com/method';
|
||||||
|
export const VK_IM_URL = 'https://vk.com/im';
|
||||||
|
export const TELEMOST_URL = 'https://telemost.yandex.ru/';
|
||||||
|
|
||||||
|
export const SESSION_PARTITION = 'persist:creator';
|
||||||
|
export const WINDOW_WIDTH = 1200;
|
||||||
|
export const WINDOW_HEIGHT = 800;
|
||||||
|
|
||||||
|
export const USER_AGENT =
|
||||||
|
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ' +
|
||||||
|
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
|
||||||
|
|
||||||
|
export const VK_COOKIE_DOMAINS = ['vk.com', 'vk.ru'];
|
||||||
|
export const YANDEX_COOKIE_DOMAINS = ['yandex.ru', 'yandex.net', 'ya.ru'];
|
||||||
|
|
||||||
|
export enum Selector {
|
||||||
|
VK_ADMIT = '[data-testid="calls_waiting_hall_promote"]',
|
||||||
|
VK_PARTICIPANT_MENU = '[data-testid="calls_participant_list_item_menu_button"]',
|
||||||
|
VK_KICK = '[data-testid="calls_participant_actions_kick"]',
|
||||||
|
VK_KICK_CONFIRM = '[data-testid="calls_call_kick_submit"]',
|
||||||
|
VK_LEAVE_CALL = '[data-testid="calls_call_footer_button_leave_call"]',
|
||||||
|
VK_CALL_MENU_TRIGGER = 'call-menu-trigger',
|
||||||
|
TM_END_CALL = '[data-testid="end-call-alt-button"]',
|
||||||
|
TM_CREATE_CALL = '[data-testid="create-call-button"]',
|
||||||
|
TM_MODERATION_POPUP = '[data-testid="show-moderation-popup"]',
|
||||||
|
TM_MODAL = '[data-testid="orb-modal2"]',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum IPC {
|
||||||
|
GET_HOOK_CODE = 'get-hook-code',
|
||||||
|
GET_CALL_CREATOR_CODE = 'get-call-creator-code',
|
||||||
|
SET_TUNNEL_MODE = 'set-tunnel-mode',
|
||||||
|
START_RELAY = 'start-relay',
|
||||||
|
START_HEADLESS = 'start-headless',
|
||||||
|
CLOSE_TAB = 'close-tab',
|
||||||
|
START_BOT = 'start-bot',
|
||||||
|
STOP_BOT = 'stop-bot',
|
||||||
|
GET_COOKIES = 'get-cookies',
|
||||||
|
RELAY_LOG = 'relay-log',
|
||||||
|
CREATE_BOT_TAB = 'create-bot-tab',
|
||||||
|
CLOSE_BOT_TAB = 'close-bot-tab',
|
||||||
|
BOT_ERROR = 'bot-error',
|
||||||
|
}
|
||||||
|
|
||||||
|
export const LOG_CAPTURE_SNIPPET = [
|
||||||
|
'if(!window.__logCaptureInstalled){',
|
||||||
|
'window.__logCaptureInstalled=true;',
|
||||||
|
'window.__hookLogs=[];',
|
||||||
|
'var _ol=console.log.bind(console);',
|
||||||
|
'console.log=function(){',
|
||||||
|
'_ol.apply(null,arguments);',
|
||||||
|
"var m=Array.prototype.slice.call(arguments).join(' ');",
|
||||||
|
"if(m.indexOf('[HOOK]')!==-1)window.__hookLogs.push(m)",
|
||||||
|
'}}',
|
||||||
|
].join('');
|
||||||
|
|
||||||
|
export enum HeadlessLogMarker {
|
||||||
|
CALL_CREATED = 'CALL CREATED',
|
||||||
|
JOIN_LINK = 'join_link:',
|
||||||
|
SHORT_LINK = 'short:',
|
||||||
|
TURN = 'TURN:',
|
||||||
|
PROTOCOL = 'protocol:',
|
||||||
|
TUNNEL_CONNECTED = 'TUNNEL CONNECTED',
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { app } from 'electron';
|
||||||
|
import { TabManager } from './tab-manager';
|
||||||
|
import { createWindow } from './window';
|
||||||
|
import { registerIpcHandlers } from './ipc';
|
||||||
|
|
||||||
|
const tabManager = new TabManager();
|
||||||
|
|
||||||
|
registerIpcHandlers(tabManager);
|
||||||
|
|
||||||
|
app.whenReady().then(() => {
|
||||||
|
const win = createWindow(tabManager);
|
||||||
|
tabManager.mainWindow = win;
|
||||||
|
});
|
||||||
|
|
||||||
|
app.on('window-all-closed', () => {
|
||||||
|
tabManager.killAllRelays();
|
||||||
|
app.quit();
|
||||||
|
});
|
||||||
|
|
||||||
|
app.on('before-quit', () => tabManager.killAllRelays());
|
||||||
|
process.on('exit', () => tabManager.killAllRelays());
|
||||||
|
process.on('SIGINT', () => {
|
||||||
|
tabManager.killAllRelays();
|
||||||
|
process.exit();
|
||||||
|
});
|
||||||
|
process.on('SIGTERM', () => {
|
||||||
|
tabManager.killAllRelays();
|
||||||
|
process.exit();
|
||||||
|
});
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { ipcMain, session } from 'electron';
|
||||||
|
import * as path from 'path';
|
||||||
|
import * as fs from 'fs/promises';
|
||||||
|
import { TabManager } from './tab-manager';
|
||||||
|
import { BotManager } from '../bot/bot-manager';
|
||||||
|
import {
|
||||||
|
IPC,
|
||||||
|
SESSION_PARTITION,
|
||||||
|
VK_COOKIE_DOMAINS,
|
||||||
|
YANDEX_COOKIE_DOMAINS,
|
||||||
|
} from '../constants';
|
||||||
|
import { TunnelMode, Platform, BotSettings } from '../types';
|
||||||
|
|
||||||
|
export function registerIpcHandlers(tabManager: TabManager): void {
|
||||||
|
ipcMain.handle(IPC.GET_HOOK_CODE, async (_e, tabId: string, url: string) => {
|
||||||
|
const tab = await tabManager.getOrCreateTab(tabId);
|
||||||
|
return tabManager.loadHook(tabId, url, tab);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC.GET_CALL_CREATOR_CODE, async (_e, scriptFile: string) => {
|
||||||
|
const filePath = path.join(__dirname, '..', '..', 'scripts', scriptFile || 'vk-call-creator.js');
|
||||||
|
return fs.readFile(filePath, 'utf8');
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC.SET_TUNNEL_MODE, (_e, tabId: string, mode: string) => {
|
||||||
|
if (!Object.values(TunnelMode).includes(mode as TunnelMode)) return;
|
||||||
|
tabManager.setTunnelMode(tabId, mode as TunnelMode);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC.START_RELAY, async (_e, tabId: string) => {
|
||||||
|
const tab = await tabManager.getOrCreateTab(tabId);
|
||||||
|
tabManager.startRelay(tabId, tab);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC.START_HEADLESS, async (_e, tabId: string, platform: string) => {
|
||||||
|
await tabManager.startHeadless(tabId, platform as Platform);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC.CLOSE_TAB, (_e, tabId: string) => {
|
||||||
|
tabManager.deleteTab(tabId);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC.START_BOT, (_e, settings: BotSettings) => {
|
||||||
|
if (tabManager.botManager) {
|
||||||
|
tabManager.botManager.stop();
|
||||||
|
}
|
||||||
|
const bm = new BotManager(
|
||||||
|
settings,
|
||||||
|
async (tabConfig) => {
|
||||||
|
if (!tabManager.mainWindow || tabManager.mainWindow.isDestroyed()) return;
|
||||||
|
const tabId = 'bot-tab-' + Date.now();
|
||||||
|
const tab = await tabManager.getOrCreateTab(tabId);
|
||||||
|
tab.tunnelMode = tabConfig.mode;
|
||||||
|
tab.platform = tabConfig.platform || Platform.VK;
|
||||||
|
tab.peerId = tabConfig.peerId;
|
||||||
|
tab.isBot = true;
|
||||||
|
tabManager.addBotTab(tabId);
|
||||||
|
tabManager.mainWindow.webContents.send(IPC.CREATE_BOT_TAB, {
|
||||||
|
tabId,
|
||||||
|
mode: tabConfig.mode,
|
||||||
|
peerId: tabConfig.peerId,
|
||||||
|
platform: tabConfig.platform || Platform.VK,
|
||||||
|
});
|
||||||
|
console.log('[BOT] Created tab:', tabId, 'mode:', tabConfig.mode, 'platform:', tabConfig.platform);
|
||||||
|
},
|
||||||
|
() => tabManager.getTabList(),
|
||||||
|
(tabId) => {
|
||||||
|
tabManager.deleteTab(tabId);
|
||||||
|
console.log('[BOT] Closed tab:', tabId);
|
||||||
|
if (tabManager.mainWindow && !tabManager.mainWindow.isDestroyed()) {
|
||||||
|
tabManager.mainWindow.webContents.send(IPC.CLOSE_BOT_TAB, { tabId });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
bm.onError = (msg: string) => {
|
||||||
|
if (tabManager.mainWindow && !tabManager.mainWindow.isDestroyed()) {
|
||||||
|
tabManager.mainWindow.webContents.send(IPC.BOT_ERROR, msg);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
tabManager.botManager = bm;
|
||||||
|
bm.start();
|
||||||
|
return { success: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC.STOP_BOT, () => {
|
||||||
|
if (tabManager.botManager) {
|
||||||
|
tabManager.botManager.stop();
|
||||||
|
tabManager.botManager = null;
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(IPC.GET_COOKIES, async (_e, domain: string) => {
|
||||||
|
const ses = session.fromPartition(SESSION_PARTITION);
|
||||||
|
const all = await ses.cookies.get({});
|
||||||
|
const domains = domain === 'yandex' ? YANDEX_COOKIE_DOMAINS : VK_COOKIE_DOMAINS;
|
||||||
|
const filtered = all.filter((cookie) => {
|
||||||
|
return cookie.domain != null && domains.some((d) => cookie.domain!.includes(d));
|
||||||
|
});
|
||||||
|
console.log(`[COOKIES] total: ${all.length} ${domain}: ${filtered.length}`);
|
||||||
|
return filtered;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
import { app } from 'electron';
|
||||||
|
import { spawn, ChildProcess } from 'child_process';
|
||||||
|
import { BrowserWindow, session } from 'electron';
|
||||||
|
import * as net from 'net';
|
||||||
|
import * as path from 'path';
|
||||||
|
import * as fs from 'fs/promises';
|
||||||
|
import { TabState, PortPair, TabListEntry, Platform, TunnelMode, RelayMode, CallStatus } from '../types';
|
||||||
|
import {
|
||||||
|
INITIAL_PORT_BASE,
|
||||||
|
IPC,
|
||||||
|
RELAY_RESTART_DELAY_MS,
|
||||||
|
SESSION_PARTITION,
|
||||||
|
VK_COOKIE_DOMAINS,
|
||||||
|
YANDEX_COOKIE_DOMAINS,
|
||||||
|
LOG_CAPTURE_SNIPPET,
|
||||||
|
} from '../constants';
|
||||||
|
import { BotManager } from '../bot/bot-manager';
|
||||||
|
|
||||||
|
function resolveResourcePath(devRelative: string, packedName: string): string {
|
||||||
|
if (app.isPackaged) {
|
||||||
|
return path.join(process.resourcesPath!, packedName);
|
||||||
|
}
|
||||||
|
return path.join(__dirname, '..', '..', '..', devRelative);
|
||||||
|
}
|
||||||
|
|
||||||
|
function binaryName(base: string): string {
|
||||||
|
return process.platform === 'win32' ? base + '.exe' : base;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TabManager {
|
||||||
|
private tabs = new Map<string, TabState>();
|
||||||
|
private callStatusCache = new Map<string, CallStatus>();
|
||||||
|
private botTabIds = new Set<string>();
|
||||||
|
private nextPortBase = INITIAL_PORT_BASE;
|
||||||
|
private _mainWindow: BrowserWindow | null = null;
|
||||||
|
private _botManager: BotManager | null = null;
|
||||||
|
private relayPath: string;
|
||||||
|
private headlessVKPath: string;
|
||||||
|
private headlessTelemostPath: string;
|
||||||
|
private hooksDir: string;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.relayPath = resolveResourcePath(
|
||||||
|
path.join('relay', binaryName('relay')),
|
||||||
|
binaryName('relay'),
|
||||||
|
);
|
||||||
|
this.headlessVKPath = resolveResourcePath(
|
||||||
|
path.join('headless', 'vk', binaryName('headless-vk-creator')),
|
||||||
|
binaryName('headless-vk-creator'),
|
||||||
|
);
|
||||||
|
this.headlessTelemostPath = resolveResourcePath(
|
||||||
|
path.join('headless', 'telemost', binaryName('headless-telemost-creator')),
|
||||||
|
binaryName('headless-telemost-creator'),
|
||||||
|
);
|
||||||
|
this.hooksDir = app.isPackaged
|
||||||
|
? path.join(process.resourcesPath!, 'hooks')
|
||||||
|
: path.join(__dirname, '..', '..', '..', 'hooks');
|
||||||
|
}
|
||||||
|
|
||||||
|
get mainWindow(): BrowserWindow | null {
|
||||||
|
return this._mainWindow;
|
||||||
|
}
|
||||||
|
|
||||||
|
set mainWindow(w: BrowserWindow | null) {
|
||||||
|
this._mainWindow = w;
|
||||||
|
}
|
||||||
|
|
||||||
|
get botManager(): BotManager | null {
|
||||||
|
return this._botManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
set botManager(bm: BotManager | null) {
|
||||||
|
this._botManager = bm;
|
||||||
|
}
|
||||||
|
|
||||||
|
private isPortFree(port: number): Promise<boolean> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const server = net.createServer();
|
||||||
|
server.once('error', () => resolve(false));
|
||||||
|
server.once('listening', () => {
|
||||||
|
server.close(() => resolve(true));
|
||||||
|
});
|
||||||
|
server.listen(port, '127.0.0.1');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async allocPorts(): Promise<PortPair> {
|
||||||
|
while (true) {
|
||||||
|
const dc = this.nextPortBase;
|
||||||
|
const pion = this.nextPortBase + 1;
|
||||||
|
this.nextPortBase += 2;
|
||||||
|
if (await this.isPortFree(dc) && await this.isPortFree(pion)) {
|
||||||
|
return { dc, pion };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getOrCreateTab(tabId: string): Promise<TabState> {
|
||||||
|
if (!this.tabs.has(tabId)) {
|
||||||
|
const ports = await this.allocPorts();
|
||||||
|
this.tabs.set(tabId, {
|
||||||
|
relay: null,
|
||||||
|
tunnelMode: TunnelMode.DC,
|
||||||
|
platform: Platform.VK,
|
||||||
|
dcPort: ports.dc,
|
||||||
|
pionPort: ports.pion,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return this.tabs.get(tabId)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
getTab(tabId: string): TabState | undefined {
|
||||||
|
return this.tabs.get(tabId);
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteTab(tabId: string): void {
|
||||||
|
const tab = this.tabs.get(tabId);
|
||||||
|
if (tab) {
|
||||||
|
this.killRelay(tabId, tab);
|
||||||
|
this.tabs.delete(tabId);
|
||||||
|
}
|
||||||
|
this.botTabIds.delete(tabId);
|
||||||
|
this.callStatusCache.delete(tabId);
|
||||||
|
}
|
||||||
|
|
||||||
|
addBotTab(tabId: string): void {
|
||||||
|
this.botTabIds.add(tabId);
|
||||||
|
}
|
||||||
|
|
||||||
|
removeBotTab(tabId: string): void {
|
||||||
|
this.botTabIds.delete(tabId);
|
||||||
|
}
|
||||||
|
|
||||||
|
isBotTab(tabId: string): boolean {
|
||||||
|
return this.botTabIds.has(tabId);
|
||||||
|
}
|
||||||
|
|
||||||
|
setCallStatus(tabId: string, status: CallStatus): void {
|
||||||
|
this.callStatusCache.set(tabId, status);
|
||||||
|
}
|
||||||
|
|
||||||
|
getCallStatus(tabId: string): CallStatus {
|
||||||
|
return this.callStatusCache.get(tabId) || CallStatus.Inactive;
|
||||||
|
}
|
||||||
|
|
||||||
|
findBotPeerId(platform: Platform): number | null {
|
||||||
|
for (const [tabId, tab] of this.tabs) {
|
||||||
|
if (this.botTabIds.has(tabId) && tab.platform === platform && tab.peerId != null) {
|
||||||
|
return tab.peerId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getTabList(): TabListEntry[] {
|
||||||
|
const result: TabListEntry[] = [];
|
||||||
|
this.tabs.forEach((tab, tabId) => {
|
||||||
|
result.push({
|
||||||
|
id: tabId,
|
||||||
|
platform: tab.platform,
|
||||||
|
mode: tab.tunnelMode,
|
||||||
|
isBot: tab.isBot === true,
|
||||||
|
callStatus: this.getCallStatus(tabId),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendLog(tabId: string, msg: string): void {
|
||||||
|
if (this._mainWindow && !this._mainWindow.isDestroyed()) {
|
||||||
|
this._mainWindow.webContents.send(IPC.RELAY_LOG, { tabId, msg });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private attachProcessOutput(proc: ChildProcess, tabId: string): void {
|
||||||
|
const onData = (data: Buffer) => {
|
||||||
|
data
|
||||||
|
.toString()
|
||||||
|
.trim()
|
||||||
|
.split('\n')
|
||||||
|
.forEach((msg) => {
|
||||||
|
if (!msg) return;
|
||||||
|
console.log(`[relay:${tabId}]`, msg);
|
||||||
|
this.sendLog(tabId, msg);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
proc.stdout?.on('data', onData);
|
||||||
|
proc.stderr?.on('data', onData);
|
||||||
|
}
|
||||||
|
|
||||||
|
startRelay(tabId: string, tab: TabState): void {
|
||||||
|
this.killRelay(tabId, tab);
|
||||||
|
const port = tab.tunnelMode === TunnelMode.PionVideo ? tab.pionPort : tab.dcPort;
|
||||||
|
let relayMode: RelayMode = RelayMode.DCCreator;
|
||||||
|
if (tab.tunnelMode === TunnelMode.PionVideo) {
|
||||||
|
relayMode = tab.platform === Platform.Telemost
|
||||||
|
? RelayMode.TelemostVideoCreator
|
||||||
|
: RelayMode.VKVideoCreator;
|
||||||
|
}
|
||||||
|
const proc = spawn(this.relayPath, ['--mode', relayMode, '--ws-port', String(port)], {
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
});
|
||||||
|
tab.relay = proc;
|
||||||
|
this.attachProcessOutput(proc, tabId);
|
||||||
|
proc.on('close', (code) => {
|
||||||
|
this.sendLog(tabId, `Relay exited with code ${code}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async startHeadless(tabId: string, platform: Platform): Promise<void> {
|
||||||
|
const tab = await this.getOrCreateTab(tabId);
|
||||||
|
const isTelemost = platform === Platform.Telemost;
|
||||||
|
tab.tunnelMode = isTelemost ? TunnelMode.HeadlessTelemost : TunnelMode.HeadlessVK;
|
||||||
|
tab.platform = platform;
|
||||||
|
const cookieStr = isTelemost
|
||||||
|
? await this.getYandexCookieString()
|
||||||
|
: await this.getVKCookieString();
|
||||||
|
if (!cookieStr) {
|
||||||
|
const name = isTelemost ? 'Yandex' : 'VK';
|
||||||
|
this.sendLog(tabId, `No ${name} cookies found. Please log into ${name} first.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.killRelay(tabId, tab);
|
||||||
|
const binaryPath = isTelemost ? this.headlessTelemostPath : this.headlessVKPath;
|
||||||
|
const proc = spawn(binaryPath, ['--cookie-string', cookieStr, '--resources', 'default'], {
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
});
|
||||||
|
tab.relay = proc;
|
||||||
|
this.attachProcessOutput(proc, tabId);
|
||||||
|
proc.on('close', (code) => {
|
||||||
|
this.sendLog(tabId, `Headless exited with code ${code}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
killRelay(tabId: string, tab: TabState): void {
|
||||||
|
if (tab.relay) {
|
||||||
|
console.log(`[${tabId}] killing process pid=${tab.relay.pid}`);
|
||||||
|
tab.relay.kill();
|
||||||
|
tab.relay = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
killAllRelays(): void {
|
||||||
|
this.tabs.forEach((tab, tabId) => this.killRelay(tabId, tab));
|
||||||
|
}
|
||||||
|
|
||||||
|
async loadHook(tabId: string, url: string, tab: TabState): Promise<string> {
|
||||||
|
const isTelemost = url.includes('telemost.yandex');
|
||||||
|
const newPlatform = isTelemost ? Platform.Telemost : Platform.VK;
|
||||||
|
|
||||||
|
if (newPlatform !== tab.platform && tab.tunnelMode === TunnelMode.PionVideo) {
|
||||||
|
tab.platform = newPlatform;
|
||||||
|
this.killRelay(tabId, tab);
|
||||||
|
setTimeout(() => this.startRelay(tabId, tab), RELAY_RESTART_DELAY_MS);
|
||||||
|
} else {
|
||||||
|
tab.platform = newPlatform;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tab.tunnelMode === TunnelMode.PionVideo) {
|
||||||
|
const hookFile = isTelemost ? 'video-telemost.js' : 'video-vk.js';
|
||||||
|
const hook = await fs.readFile(path.join(this.hooksDir, hookFile), 'utf8');
|
||||||
|
return LOG_CAPTURE_SNIPPET + `window.PION_PORT=${tab.pionPort};window.IS_CREATOR=true;` + hook;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hookFile = isTelemost ? 'dc-creator-telemost.js' : 'dc-creator-vk.js';
|
||||||
|
const hook = await fs.readFile(path.join(this.hooksDir, hookFile), 'utf8');
|
||||||
|
return LOG_CAPTURE_SNIPPET + `window.WS_PORT=${tab.dcPort};` + hook;
|
||||||
|
}
|
||||||
|
|
||||||
|
setTunnelMode(tabId: string, mode: TunnelMode): void {
|
||||||
|
const tab = this.tabs.get(tabId);
|
||||||
|
if (!tab) return;
|
||||||
|
tab.tunnelMode = mode;
|
||||||
|
this.killRelay(tabId, tab);
|
||||||
|
setTimeout(() => this.startRelay(tabId, tab), RELAY_RESTART_DELAY_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getVKCookieString(): Promise<string> {
|
||||||
|
const ses = session.fromPartition(SESSION_PARTITION);
|
||||||
|
const all = await ses.cookies.get({});
|
||||||
|
const vkCookies = all.filter((cookie) => {
|
||||||
|
return cookie.domain != null && VK_COOKIE_DOMAINS.some((d) => cookie.domain!.includes(d));
|
||||||
|
});
|
||||||
|
return vkCookies.map((cookie) => `${cookie.name}=${cookie.value}`).join('; ');
|
||||||
|
}
|
||||||
|
|
||||||
|
async getYandexCookieString(): Promise<string> {
|
||||||
|
const ses = session.fromPartition(SESSION_PARTITION);
|
||||||
|
const all = await ses.cookies.get({});
|
||||||
|
const yaCookies = all.filter((cookie) => {
|
||||||
|
return cookie.domain != null && YANDEX_COOKIE_DOMAINS.some((d) => cookie.domain!.includes(d));
|
||||||
|
});
|
||||||
|
return yaCookies.map((cookie) => `${cookie.name}=${cookie.value}`).join('; ');
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import { app, BrowserWindow, session, Session } from 'electron';
|
||||||
|
import * as path from 'path';
|
||||||
|
import { TabManager } from './tab-manager';
|
||||||
|
import { VkAutoclick } from '../autoclick/vk';
|
||||||
|
import { TelemostAutoclick } from '../autoclick/telemost';
|
||||||
|
import { SESSION_PARTITION, USER_AGENT, WINDOW_WIDTH, WINDOW_HEIGHT } from '../constants';
|
||||||
|
import { Platform, CallStatus } from '../types';
|
||||||
|
|
||||||
|
function stripCSP(ses: Session): void {
|
||||||
|
ses.webRequest.onHeadersReceived((details, callback) => {
|
||||||
|
const headers = { ...details.responseHeaders };
|
||||||
|
delete headers['content-security-policy'];
|
||||||
|
delete headers['Content-Security-Policy'];
|
||||||
|
delete headers['content-security-policy-report-only'];
|
||||||
|
delete headers['Content-Security-Policy-Report-Only'];
|
||||||
|
callback({ responseHeaders: headers });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseCallStatus(msg: string): { tabId: string; status: CallStatus } | null {
|
||||||
|
const prefix = '[CALL_STATUS] ';
|
||||||
|
const idx = msg.indexOf(prefix);
|
||||||
|
if (idx === -1) return null;
|
||||||
|
const parts = msg.substring(idx + prefix.length);
|
||||||
|
const colonIdx = parts.indexOf(':');
|
||||||
|
if (colonIdx === -1) return null;
|
||||||
|
const status = parts.substring(colonIdx + 1);
|
||||||
|
return {
|
||||||
|
tabId: parts.substring(0, colonIdx),
|
||||||
|
status: status === CallStatus.Active ? CallStatus.Active : CallStatus.Inactive,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractCallLink(msg: string, prefix: string): string | null {
|
||||||
|
const idx = msg.indexOf(prefix);
|
||||||
|
if (idx === -1) return null;
|
||||||
|
return msg.split(prefix)[1].trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createWindow(tabManager: TabManager): BrowserWindow {
|
||||||
|
const ses = session.fromPartition(SESSION_PARTITION);
|
||||||
|
stripCSP(ses);
|
||||||
|
ses.setPermissionRequestHandler((_wc, _perm, cb) => cb(true));
|
||||||
|
ses.setPermissionCheckHandler(() => true);
|
||||||
|
ses.setUserAgent(USER_AGENT);
|
||||||
|
|
||||||
|
app.on('session-created', stripCSP);
|
||||||
|
|
||||||
|
const win = new BrowserWindow({
|
||||||
|
width: WINDOW_WIDTH,
|
||||||
|
height: WINDOW_HEIGHT,
|
||||||
|
icon: path.join(__dirname, '..', '..', 'resources', 'icon.png'),
|
||||||
|
webPreferences: {
|
||||||
|
preload: path.join(__dirname, '..', 'preload', 'index.js'),
|
||||||
|
nodeIntegration: true,
|
||||||
|
contextIsolation: false,
|
||||||
|
webviewTag: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
win.loadFile('index.html');
|
||||||
|
win.on('closed', () => {
|
||||||
|
tabManager.mainWindow = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
const autoclickers = new Map<number, { telemost: TelemostAutoclick; vk: VkAutoclick }>();
|
||||||
|
|
||||||
|
win.webContents.on('did-attach-webview', (_e, wvContents) => {
|
||||||
|
wvContents.on('before-input-event', (_e, input) => {
|
||||||
|
if (input.key === 'F12') wvContents.openDevTools();
|
||||||
|
});
|
||||||
|
|
||||||
|
wvContents.on('did-navigate', (_e, url) => {
|
||||||
|
const wcId = wvContents.id;
|
||||||
|
if (!autoclickers.has(wcId)) {
|
||||||
|
autoclickers.set(wcId, {
|
||||||
|
telemost: new TelemostAutoclick(),
|
||||||
|
vk: new VkAutoclick(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const ac = autoclickers.get(wcId)!;
|
||||||
|
if (url.includes('telemost.yandex')) {
|
||||||
|
ac.vk.stop();
|
||||||
|
ac.telemost.attach(wvContents);
|
||||||
|
} else if (url.includes('vk.com')) {
|
||||||
|
ac.telemost.stop();
|
||||||
|
ac.vk.attach(wvContents);
|
||||||
|
} else {
|
||||||
|
ac.telemost.stop();
|
||||||
|
ac.vk.stop();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
wvContents.on('console-message', (_e, _level, msg) => {
|
||||||
|
if (msg.includes('state: disconnected') || msg.includes('state: failed')) {
|
||||||
|
const ac = autoclickers.get(wvContents.id);
|
||||||
|
if (ac) ac.vk.kickDisconnected();
|
||||||
|
}
|
||||||
|
|
||||||
|
handleBotCallLink(tabManager, msg, Platform.VK, '[BOT] VKCalls: call link:');
|
||||||
|
handleBotCallLink(tabManager, msg, Platform.Telemost, '[BOT] Telemost: call link:');
|
||||||
|
|
||||||
|
const callStatus = parseCallStatus(msg);
|
||||||
|
if (callStatus) {
|
||||||
|
console.log('[MAIN] Cached status for', callStatus.tabId, ':', callStatus.status);
|
||||||
|
tabManager.setCallStatus(callStatus.tabId, callStatus.status);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
wvContents.on('destroyed', () => {
|
||||||
|
const ac = autoclickers.get(wvContents.id);
|
||||||
|
if (ac) {
|
||||||
|
ac.telemost.stop();
|
||||||
|
ac.vk.stop();
|
||||||
|
autoclickers.delete(wvContents.id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return win;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleBotCallLink(
|
||||||
|
tabManager: TabManager,
|
||||||
|
msg: string,
|
||||||
|
platform: Platform,
|
||||||
|
prefix: string,
|
||||||
|
): void {
|
||||||
|
const link = extractCallLink(msg, prefix);
|
||||||
|
if (!link) return;
|
||||||
|
console.log(`[MAIN] ${platform} call link captured:`, link);
|
||||||
|
const peerId = tabManager.findBotPeerId(platform);
|
||||||
|
if (peerId != null && tabManager.botManager) {
|
||||||
|
console.log(`[MAIN] Sending ${platform} link to peer:`, peerId);
|
||||||
|
tabManager.botManager.sendMessage(peerId, `Call created!\n ${link}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { ipcRenderer } from 'electron';
|
||||||
|
import { IPC } from '../constants';
|
||||||
|
|
||||||
|
(window as any).bridge = {
|
||||||
|
onRelayLog(cb: (tabId: string, msg: string) => void) {
|
||||||
|
ipcRenderer.on(IPC.RELAY_LOG, (_e, data) => cb(data.tabId, data.msg));
|
||||||
|
},
|
||||||
|
getHookCode(tabId: string, url: string) {
|
||||||
|
return ipcRenderer.invoke(IPC.GET_HOOK_CODE, tabId, url);
|
||||||
|
},
|
||||||
|
setTunnelMode(tabId: string, mode: string) {
|
||||||
|
return ipcRenderer.invoke(IPC.SET_TUNNEL_MODE, tabId, mode);
|
||||||
|
},
|
||||||
|
startRelay(tabId: string) {
|
||||||
|
return ipcRenderer.invoke(IPC.START_RELAY, tabId);
|
||||||
|
},
|
||||||
|
closeTab(tabId: string) {
|
||||||
|
return ipcRenderer.invoke(IPC.CLOSE_TAB, tabId);
|
||||||
|
},
|
||||||
|
startBot(settings: any) {
|
||||||
|
return ipcRenderer.invoke(IPC.START_BOT, settings);
|
||||||
|
},
|
||||||
|
stopBot() {
|
||||||
|
return ipcRenderer.invoke(IPC.STOP_BOT);
|
||||||
|
},
|
||||||
|
onCreateBotTab(cb: (data: any) => void) {
|
||||||
|
ipcRenderer.on(IPC.CREATE_BOT_TAB, (_e, data) => cb(data));
|
||||||
|
},
|
||||||
|
getCallCreatorCode(scriptFile: string) {
|
||||||
|
return ipcRenderer.invoke(IPC.GET_CALL_CREATOR_CODE, scriptFile);
|
||||||
|
},
|
||||||
|
onBotError(cb: (msg: string) => void) {
|
||||||
|
ipcRenderer.on(IPC.BOT_ERROR, (_e, msg) => cb(msg));
|
||||||
|
},
|
||||||
|
getCookies(domain: string) {
|
||||||
|
return ipcRenderer.invoke(IPC.GET_COOKIES, domain);
|
||||||
|
},
|
||||||
|
startHeadless(tabId: string, platform: string) {
|
||||||
|
return ipcRenderer.invoke(IPC.START_HEADLESS, tabId, platform);
|
||||||
|
},
|
||||||
|
onCloseBotTab(cb: (data: any) => void) {
|
||||||
|
ipcRenderer.on(IPC.CLOSE_BOT_TAB, (_e, data) => cb(data));
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
import { Platform, Bridge, LogPanel, Webview } from '../types';
|
||||||
|
import { SESSION_PARTITION, HOOK_POLL_INTERVAL_MS, CALL_CREATOR_INJECT_DELAY_MS } from '../constants';
|
||||||
|
import { RendererTabManager } from './tab-manager';
|
||||||
|
|
||||||
|
declare const window: Window & { bridge: Bridge };
|
||||||
|
|
||||||
|
export function renderTabs(tm: RendererTabManager): void {
|
||||||
|
const bar = document.getElementById('tabBar')!;
|
||||||
|
let html = '';
|
||||||
|
Object.keys(tm.tabs).forEach((id) => {
|
||||||
|
const tab = tm.tabs[id];
|
||||||
|
const label = tm.getTabLabel(tab);
|
||||||
|
const cls = id === tm.activeTabId ? 'tab active' : 'tab';
|
||||||
|
html +=
|
||||||
|
`<div class="${cls}" data-tab-id="${id}">` +
|
||||||
|
`<span class="tab-label">${escapeHtml(label)}</span>` +
|
||||||
|
`<img class="edit" src="resources/icons8-pencil-50.png" data-action="rename">` +
|
||||||
|
` <span class="close" data-action="close">✕</span></div>`;
|
||||||
|
});
|
||||||
|
html += '<div class="tab-add" data-action="add-tab" title="New tab">+</div>';
|
||||||
|
bar.innerHTML = html;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderContent(tm: RendererTabManager): void {
|
||||||
|
const content = document.getElementById('content')!;
|
||||||
|
const welcome = document.getElementById('welcome')!;
|
||||||
|
const toolbar = document.getElementById('toolbar')!;
|
||||||
|
const logsPanel = document.getElementById('logsPanel')!;
|
||||||
|
const headlessInfo = document.getElementById('headlessInfo')!;
|
||||||
|
|
||||||
|
const webviews = content.querySelectorAll('webview');
|
||||||
|
webviews.forEach((wv) => wv.classList.add('hidden'));
|
||||||
|
|
||||||
|
if (!tm.activeTabId || !tm.tabs[tm.activeTabId]) {
|
||||||
|
welcome.style.display = 'flex';
|
||||||
|
toolbar.style.display = 'none';
|
||||||
|
logsPanel.style.display = 'none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
welcome.style.display = 'none';
|
||||||
|
logsPanel.style.display = 'flex';
|
||||||
|
|
||||||
|
const activeTab = tm.tabs[tm.activeTabId];
|
||||||
|
if (activeTab.headless) {
|
||||||
|
toolbar.style.display = 'none';
|
||||||
|
headlessInfo.style.display = 'block';
|
||||||
|
const title = activeTab.platform === Platform.Telemost ? 'Headless Telemost' : 'Headless VK';
|
||||||
|
document.getElementById('headlessTitle')!.textContent = title;
|
||||||
|
document.getElementById('headlessStatus')!.textContent = activeTab.headlessStatus || 'Starting...';
|
||||||
|
const callInfo = activeTab.callInfo;
|
||||||
|
const isTelemost = activeTab.platform === Platform.Telemost;
|
||||||
|
const callInfoVK = document.getElementById('headlessCallInfo')!;
|
||||||
|
const callInfoTM = document.getElementById('headlessCallInfoTM')!;
|
||||||
|
if (callInfo && isTelemost) {
|
||||||
|
callInfoVK.style.display = 'none';
|
||||||
|
callInfoTM.style.display = 'block';
|
||||||
|
document.getElementById('headlessTMJoinLink')!.textContent = callInfo.joinLink || '';
|
||||||
|
document.getElementById('headlessTMProtocol')!.textContent = callInfo.protocol || '';
|
||||||
|
} else if (callInfo) {
|
||||||
|
callInfoTM.style.display = 'none';
|
||||||
|
callInfoVK.style.display = 'block';
|
||||||
|
document.getElementById('headlessJoinLink')!.textContent = callInfo.joinLink || '';
|
||||||
|
document.getElementById('headlessShortLink')!.textContent = callInfo.shortLink || '';
|
||||||
|
document.getElementById('headlessTurn')!.textContent = callInfo.turn || '';
|
||||||
|
document.getElementById('headlessProtocol')!.textContent = callInfo.protocol || '';
|
||||||
|
} else {
|
||||||
|
callInfoVK.style.display = 'none';
|
||||||
|
callInfoTM.style.display = 'none';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
toolbar.style.display = 'flex';
|
||||||
|
headlessInfo.style.display = 'none';
|
||||||
|
(document.getElementById('modeSelect') as HTMLSelectElement).value = activeTab.mode;
|
||||||
|
if (activeTab.wv) activeTab.wv.classList.remove('hidden');
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('relayLog')!.textContent = activeTab.relayLogs || '';
|
||||||
|
document.getElementById('hookLog')!.textContent = activeTab.hookLogs || '';
|
||||||
|
scrollLogs();
|
||||||
|
|
||||||
|
renderBotButton(tm);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderBotButton(tm: RendererTabManager): void {
|
||||||
|
const btn = document.getElementById('tabBot')!;
|
||||||
|
btn.textContent = tm.botRunning ? 'Bot: On' : 'Bot: Off';
|
||||||
|
btn.classList.toggle('running', tm.botRunning);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function scrollLogs(): void {
|
||||||
|
const relayEl = document.getElementById('relayLog');
|
||||||
|
const hookEl = document.getElementById('hookLog');
|
||||||
|
if (relayEl) relayEl.scrollTop = relayEl.scrollHeight;
|
||||||
|
if (hookEl) hookEl.scrollTop = hookEl.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadURL(tm: RendererTabManager, url: string): void {
|
||||||
|
if (!tm.activeTabId) return;
|
||||||
|
const activeTab = tm.tabs[tm.activeTabId];
|
||||||
|
if (activeTab.wv) activeTab.wv.remove();
|
||||||
|
|
||||||
|
const webview = document.createElement('webview') as unknown as Webview;
|
||||||
|
webview.setAttribute('src', url);
|
||||||
|
webview.setAttribute('partition', SESSION_PARTITION);
|
||||||
|
webview.setAttribute('nodeintegration', '');
|
||||||
|
webview.setAttribute('nodeintegrationinsubframes', '');
|
||||||
|
webview.classList.add('webview-full');
|
||||||
|
webview.dataset.tabId = tm.activeTabId;
|
||||||
|
document.getElementById('content')!.appendChild(webview);
|
||||||
|
|
||||||
|
webview.addEventListener('dom-ready', () => {
|
||||||
|
webview.setAudioMuted(true);
|
||||||
|
const currentTabId = webview.dataset.tabId!;
|
||||||
|
|
||||||
|
window.bridge.getHookCode(currentTabId, webview.getURL()).then((code: string) => {
|
||||||
|
webview.executeJavaScript(code).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
window.bridge.getCallCreatorCode('call-checker.js').then((checkerCode: string) => {
|
||||||
|
const inject = `window.__CALL_CHECKER_TAB_ID = "${currentTabId}"; ${checkerCode}`;
|
||||||
|
webview.executeJavaScript(inject).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
const tabState = tm.tabs[currentTabId];
|
||||||
|
if (tabState?.isBot) {
|
||||||
|
setTimeout(() => {
|
||||||
|
const scriptFile = tabState.platform === Platform.Telemost ? 'tm-call-creator.js' : 'vk-call-creator.js';
|
||||||
|
window.bridge.getCallCreatorCode(scriptFile).then((code: string) => {
|
||||||
|
webview.executeJavaScript(code).catch(() => {});
|
||||||
|
});
|
||||||
|
}, CALL_CREATOR_INJECT_DELAY_MS);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
webview.addEventListener('did-navigate', () => {
|
||||||
|
activeTab.url = webview.getURL() || activeTab.url;
|
||||||
|
renderTabs(tm);
|
||||||
|
const currentTabId = webview.dataset.tabId!;
|
||||||
|
webview.executeJavaScript('window.__hookInstalled = false').catch(() => {});
|
||||||
|
window.bridge.getHookCode(currentTabId, webview.getURL()).then((code: string) => {
|
||||||
|
webview.executeJavaScript(code).catch(() => {});
|
||||||
|
});
|
||||||
|
window.bridge.getCallCreatorCode('call-checker.js').then((checkerCode: string) => {
|
||||||
|
const inject = `window.__CALL_CHECKER_TAB_ID = "${currentTabId}"; ${checkerCode}`;
|
||||||
|
webview.executeJavaScript(inject).catch(() => {});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
activeTab.wv = webview;
|
||||||
|
activeTab.url = url;
|
||||||
|
renderTabs(tm);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startHookLogPoller(tm: RendererTabManager): void {
|
||||||
|
setInterval(() => {
|
||||||
|
if (!tm.activeTabId || !tm.tabs[tm.activeTabId]?.wv) return;
|
||||||
|
const webview = tm.tabs[tm.activeTabId].wv!;
|
||||||
|
webview
|
||||||
|
.executeJavaScript(
|
||||||
|
'(window.__hookLogs && window.__hookLogs.length) ? window.__hookLogs.splice(0) : []',
|
||||||
|
)
|
||||||
|
.then((logs: string[]) => {
|
||||||
|
if (!logs.length) return;
|
||||||
|
const el = document.getElementById('hookLog')!;
|
||||||
|
logs.forEach((msg) => {
|
||||||
|
if (el.textContent!.length > 0) el.textContent += '\n';
|
||||||
|
el.textContent += msg.replace('[HOOK] ', '');
|
||||||
|
});
|
||||||
|
el.scrollTop = el.scrollHeight;
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}, HOOK_POLL_INTERVAL_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(str: string): string {
|
||||||
|
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function showError(msg: string): void {
|
||||||
|
document.getElementById('errorText')!.textContent = msg;
|
||||||
|
document.getElementById('errorPopup')!.classList.add('visible');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function closeError(): void {
|
||||||
|
document.getElementById('errorPopup')!.classList.remove('visible');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearLog(panel: LogPanel): void {
|
||||||
|
const id = panel === LogPanel.Relay ? 'relayLog' : 'hookLog';
|
||||||
|
document.getElementById(id)!.textContent = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveLogs(): void {
|
||||||
|
const relay = document.getElementById('relayLog')!.textContent || '';
|
||||||
|
const hook = document.getElementById('hookLog')!.textContent || '';
|
||||||
|
const text = '=== RELAY ===\n' + relay + '\n\n=== HOOK ===\n' + hook;
|
||||||
|
const blob = new Blob([text], { type: 'text/plain' });
|
||||||
|
const anchor = document.createElement('a');
|
||||||
|
anchor.href = URL.createObjectURL(blob);
|
||||||
|
anchor.download = 'tunnel-logs-' + new Date().toISOString().replace(/[:.]/g, '-') + '.txt';
|
||||||
|
anchor.click();
|
||||||
|
URL.revokeObjectURL(anchor.href);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function exportCookies(domain: string, filename: string, errorMsg: string): void {
|
||||||
|
window.bridge.getCookies(domain).then((cookies) => {
|
||||||
|
if (!cookies.length) {
|
||||||
|
showError(errorMsg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const simple = cookies.map((cookie) => ({ name: cookie.name, value: cookie.value }));
|
||||||
|
const blob = new Blob([JSON.stringify(simple, null, 2)], { type: 'application/json' });
|
||||||
|
const anchor = document.createElement('a');
|
||||||
|
anchor.href = URL.createObjectURL(blob);
|
||||||
|
anchor.download = filename;
|
||||||
|
anchor.click();
|
||||||
|
URL.revokeObjectURL(anchor.href);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function copyToClipboard(text: string): void {
|
||||||
|
navigator.clipboard.writeText(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renameTab(tm: RendererTabManager, tabId: string, tabEl: HTMLElement): void {
|
||||||
|
const span = tabEl.querySelector('.tab-label') as HTMLElement;
|
||||||
|
if (!span) return;
|
||||||
|
const input = document.createElement('input');
|
||||||
|
input.type = 'text';
|
||||||
|
input.value = tm.tabs[tabId]?.name || '';
|
||||||
|
input.placeholder = tm.getTabLabel(tm.tabs[tabId]);
|
||||||
|
input.className = 'tab-rename-input';
|
||||||
|
span.replaceWith(input);
|
||||||
|
input.focus();
|
||||||
|
input.select();
|
||||||
|
const done = () => {
|
||||||
|
if (tm.tabs[tabId]) {
|
||||||
|
tm.tabs[tabId].name = input.value.trim();
|
||||||
|
}
|
||||||
|
renderTabs(tm);
|
||||||
|
};
|
||||||
|
input.addEventListener('blur', done);
|
||||||
|
input.addEventListener('keydown', (ev) => {
|
||||||
|
if (ev.key === 'Enter') input.blur();
|
||||||
|
if (ev.key === 'Escape') {
|
||||||
|
input.value = '';
|
||||||
|
input.blur();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import { RendererTabManager } from './tab-manager';
|
||||||
|
import {
|
||||||
|
renderTabs,
|
||||||
|
renderContent,
|
||||||
|
renderBotButton,
|
||||||
|
loadURL,
|
||||||
|
startHookLogPoller,
|
||||||
|
showError,
|
||||||
|
closeError,
|
||||||
|
clearLog,
|
||||||
|
saveLogs,
|
||||||
|
exportCookies,
|
||||||
|
copyToClipboard,
|
||||||
|
renameTab,
|
||||||
|
} from './dom';
|
||||||
|
import { VK_IM_URL, TELEMOST_URL } from '../constants';
|
||||||
|
import { Platform, Bridge, BotTabData, LogPanel, TunnelMode } from '../types';
|
||||||
|
|
||||||
|
declare const window: Window & { bridge: Bridge };
|
||||||
|
|
||||||
|
const tm = new RendererTabManager(() => {
|
||||||
|
renderTabs(tm);
|
||||||
|
renderContent(tm);
|
||||||
|
});
|
||||||
|
|
||||||
|
function bindTabBarEvents(): void {
|
||||||
|
document.getElementById('tabBar')!.addEventListener('click', (event) => {
|
||||||
|
const target = event.target as HTMLElement;
|
||||||
|
const action = target.dataset.action;
|
||||||
|
const tabEl = target.closest('[data-tab-id]') as HTMLElement | null;
|
||||||
|
const tabId = tabEl?.dataset.tabId;
|
||||||
|
|
||||||
|
if (action === 'add-tab') {
|
||||||
|
tm.createTab();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (action === 'close' && tabId) {
|
||||||
|
event.stopPropagation();
|
||||||
|
tm.closeTab(tabId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (action === 'rename' && tabId) {
|
||||||
|
event.stopPropagation();
|
||||||
|
renameTab(tm, tabId, tabEl!);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (tabId) {
|
||||||
|
tm.selectTab(tabId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindToolbarEvents(): void {
|
||||||
|
document.getElementById('btnVk')!.addEventListener('click', () => loadURL(tm, VK_IM_URL));
|
||||||
|
document.getElementById('btnTelemost')!.addEventListener('click', () => loadURL(tm, TELEMOST_URL));
|
||||||
|
document.getElementById('btnHeadlessVK')!.addEventListener('click', () => tm.switchToHeadless(Platform.VK));
|
||||||
|
document.getElementById('btnHeadlessTM')!.addEventListener('click', () => tm.switchToHeadless(Platform.Telemost));
|
||||||
|
document.getElementById('modeSelect')!.addEventListener('change', (event) => {
|
||||||
|
tm.setTunnelMode((event.target as HTMLSelectElement).value);
|
||||||
|
});
|
||||||
|
document.getElementById('btnSaveLogs')!.addEventListener('click', saveLogs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindActionBarEvents(): void {
|
||||||
|
document.getElementById('btnVkCookies')!.addEventListener('click', () => {
|
||||||
|
exportCookies('.vk.com', 'vk-cookies.json', 'No VK cookies found.\nPlease log into VK first.');
|
||||||
|
});
|
||||||
|
document.getElementById('btnYandexCookies')!.addEventListener('click', () => {
|
||||||
|
exportCookies(
|
||||||
|
'yandex',
|
||||||
|
'cookies-yandex.json',
|
||||||
|
'No Yandex cookies found.\nPlease log into Yandex (telemost.yandex.ru) first.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
document.getElementById('btnSettings')!.addEventListener('click', openSettings);
|
||||||
|
document.getElementById('tabBot')!.addEventListener('click', () => {
|
||||||
|
if (!tm.botSettings.token || !tm.botSettings.groupId) {
|
||||||
|
openSettings();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tm.toggleBot();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindSettingsEvents(): void {
|
||||||
|
document.getElementById('btnSettingsCancel')!.addEventListener('click', closeSettings);
|
||||||
|
document.getElementById('btnSettingsSave')!.addEventListener('click', () => {
|
||||||
|
tm.botSettings.token = (document.getElementById('vkToken') as HTMLInputElement).value.trim();
|
||||||
|
tm.botSettings.groupId = (document.getElementById('vkGroupId') as HTMLInputElement).value.trim();
|
||||||
|
tm.botSettings.userId = (document.getElementById('vkUserId') as HTMLInputElement).value.trim();
|
||||||
|
tm.saveBotSettings();
|
||||||
|
closeSettings();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindErrorPopup(): void {
|
||||||
|
document.getElementById('errorPopup')!.addEventListener('click', closeError);
|
||||||
|
document.querySelector('#errorPopup .popup')!.addEventListener('click', (event) => event.stopPropagation());
|
||||||
|
document.getElementById('btnErrorClose')!.addEventListener('click', closeError);
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindLogEvents(): void {
|
||||||
|
document.getElementById('btnClearRelay')!.addEventListener('click', () => clearLog(LogPanel.Relay));
|
||||||
|
document.getElementById('btnClearHook')!.addEventListener('click', () => clearLog(LogPanel.Hook));
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindHeadlessEvents(): void {
|
||||||
|
document.getElementById('headlessJoinLink')!.addEventListener('click', (event) => {
|
||||||
|
copyToClipboard((event.target as HTMLElement).textContent || '');
|
||||||
|
});
|
||||||
|
document.getElementById('headlessShortLink')!.addEventListener('click', (event) => {
|
||||||
|
copyToClipboard((event.target as HTMLElement).textContent || '');
|
||||||
|
});
|
||||||
|
document.getElementById('headlessInfo')!.addEventListener('click', (event) => {
|
||||||
|
const target = event.target as HTMLElement;
|
||||||
|
const copyTarget = target.dataset.copy;
|
||||||
|
if (copyTarget) {
|
||||||
|
const sourceEl = document.getElementById(copyTarget);
|
||||||
|
if (sourceEl) copyToClipboard(sourceEl.textContent || '');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function openSettings(): void {
|
||||||
|
document.getElementById('settingsPopup')!.classList.add('visible');
|
||||||
|
(document.getElementById('vkToken') as HTMLInputElement).value = tm.botSettings.token;
|
||||||
|
(document.getElementById('vkGroupId') as HTMLInputElement).value = tm.botSettings.groupId;
|
||||||
|
(document.getElementById('vkUserId') as HTMLInputElement).value = tm.botSettings.userId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeSettings(): void {
|
||||||
|
document.getElementById('settingsPopup')!.classList.remove('visible');
|
||||||
|
}
|
||||||
|
|
||||||
|
function init(): void {
|
||||||
|
bindTabBarEvents();
|
||||||
|
bindToolbarEvents();
|
||||||
|
bindActionBarEvents();
|
||||||
|
bindSettingsEvents();
|
||||||
|
bindErrorPopup();
|
||||||
|
bindLogEvents();
|
||||||
|
bindHeadlessEvents();
|
||||||
|
|
||||||
|
window.bridge.onRelayLog((tabId: string, msg: string) => {
|
||||||
|
tm.appendRelayLog(tabId, msg);
|
||||||
|
});
|
||||||
|
|
||||||
|
window.bridge.onBotError((msg: string) => {
|
||||||
|
showError(msg);
|
||||||
|
tm.botRunning = false;
|
||||||
|
localStorage.setItem('botEnabled', 'false');
|
||||||
|
renderBotButton(tm);
|
||||||
|
});
|
||||||
|
|
||||||
|
window.bridge.onCreateBotTab((data: BotTabData) => {
|
||||||
|
tm.createBotTab(data);
|
||||||
|
(document.getElementById('modeSelect') as HTMLSelectElement).value = data.mode;
|
||||||
|
window.bridge.setTunnelMode(data.tabId, data.mode);
|
||||||
|
const url = data.platform === Platform.Telemost ? TELEMOST_URL : VK_IM_URL;
|
||||||
|
loadURL(tm, url);
|
||||||
|
});
|
||||||
|
|
||||||
|
window.bridge.onCloseBotTab((data: { tabId: string }) => {
|
||||||
|
tm.closeTab(data.tabId);
|
||||||
|
});
|
||||||
|
|
||||||
|
startHookLogPoller(tm);
|
||||||
|
tm.autoStartBot();
|
||||||
|
renderBotButton(tm);
|
||||||
|
}
|
||||||
|
|
||||||
|
init();
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
import { RendererTab, BotTabData, BotSettings, TunnelMode, Platform, Bridge } from '../types';
|
||||||
|
import { HeadlessLogMarker } from '../constants';
|
||||||
|
|
||||||
|
declare const window: Window & { bridge: Bridge };
|
||||||
|
|
||||||
|
export class RendererTabManager {
|
||||||
|
tabs: Record<string, RendererTab> = {};
|
||||||
|
activeTabId: string | null = null;
|
||||||
|
private nextId = 1;
|
||||||
|
botRunning = false;
|
||||||
|
botSettings: BotSettings;
|
||||||
|
private onRender: () => void;
|
||||||
|
|
||||||
|
constructor(onRender: () => void) {
|
||||||
|
this.onRender = onRender;
|
||||||
|
const saved = localStorage.getItem('botSettings');
|
||||||
|
this.botSettings = saved
|
||||||
|
? JSON.parse(saved)
|
||||||
|
: { token: '', groupId: '', userId: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
createTab(): string {
|
||||||
|
const tabId = 'tab-' + this.nextId++;
|
||||||
|
this.tabs[tabId] = {
|
||||||
|
wv: null,
|
||||||
|
url: '',
|
||||||
|
mode: TunnelMode.DC,
|
||||||
|
relayLogs: '',
|
||||||
|
hookLogs: '',
|
||||||
|
name: '',
|
||||||
|
isBot: false,
|
||||||
|
};
|
||||||
|
window.bridge.startRelay(tabId);
|
||||||
|
this.selectTab(tabId);
|
||||||
|
return tabId;
|
||||||
|
}
|
||||||
|
|
||||||
|
switchToHeadless(platform: Platform): void {
|
||||||
|
if (!this.activeTabId) return;
|
||||||
|
const tab = this.tabs[this.activeTabId];
|
||||||
|
if (tab.wv) tab.wv.remove();
|
||||||
|
const isTelemost = platform === Platform.Telemost;
|
||||||
|
tab.wv = null;
|
||||||
|
tab.url = '';
|
||||||
|
tab.mode = isTelemost ? TunnelMode.HeadlessTelemost : TunnelMode.HeadlessVK;
|
||||||
|
tab.name = isTelemost ? 'Headless TM' : 'Headless VK';
|
||||||
|
tab.headless = true;
|
||||||
|
tab.platform = platform;
|
||||||
|
tab.callInfo = undefined;
|
||||||
|
tab.headlessStatus = 'Starting...';
|
||||||
|
tab.tunnelConnected = false;
|
||||||
|
tab.relayLogs = '';
|
||||||
|
tab.hookLogs = '';
|
||||||
|
window.bridge.startHeadless(this.activeTabId, platform);
|
||||||
|
this.onRender();
|
||||||
|
}
|
||||||
|
|
||||||
|
createBotTab(data: BotTabData): void {
|
||||||
|
if (!this.tabs[data.tabId]) {
|
||||||
|
const botName = data.platform === Platform.Telemost ? 'Bot-Telemost' : 'Bot-VK';
|
||||||
|
this.tabs[data.tabId] = {
|
||||||
|
wv: null,
|
||||||
|
url: '',
|
||||||
|
mode: data.mode,
|
||||||
|
relayLogs: '',
|
||||||
|
hookLogs: '',
|
||||||
|
name: botName,
|
||||||
|
isBot: true,
|
||||||
|
peerId: data.peerId,
|
||||||
|
platform: data.platform,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
this.selectTab(data.tabId);
|
||||||
|
}
|
||||||
|
|
||||||
|
closeTab(tabId: string): void {
|
||||||
|
const tab = this.tabs[tabId];
|
||||||
|
if (tab?.wv) tab.wv.remove();
|
||||||
|
window.bridge.closeTab(tabId);
|
||||||
|
delete this.tabs[tabId];
|
||||||
|
if (this.activeTabId === tabId) {
|
||||||
|
const ids = Object.keys(this.tabs);
|
||||||
|
this.activeTabId = ids.length > 0 ? ids[ids.length - 1] : null;
|
||||||
|
}
|
||||||
|
this.onRender();
|
||||||
|
}
|
||||||
|
|
||||||
|
selectTab(tabId: string): void {
|
||||||
|
this.saveCurrentTabLogs();
|
||||||
|
this.activeTabId = tabId;
|
||||||
|
this.onRender();
|
||||||
|
}
|
||||||
|
|
||||||
|
saveCurrentTabLogs(): void {
|
||||||
|
if (this.activeTabId && this.tabs[this.activeTabId]) {
|
||||||
|
const relayEl = document.getElementById('relayLog');
|
||||||
|
const hookEl = document.getElementById('hookLog');
|
||||||
|
if (relayEl) this.tabs[this.activeTabId].relayLogs = relayEl.textContent || '';
|
||||||
|
if (hookEl) this.tabs[this.activeTabId].hookLogs = hookEl.textContent || '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getActiveTab(): RendererTab | null {
|
||||||
|
if (!this.activeTabId) return null;
|
||||||
|
return this.tabs[this.activeTabId] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getTabLabel(tab: RendererTab): string {
|
||||||
|
if (tab.name) return tab.name;
|
||||||
|
if (tab.url) {
|
||||||
|
if (tab.url.includes('vk.com')) return 'VK';
|
||||||
|
if (tab.url.includes('telemost')) return 'Telemost';
|
||||||
|
}
|
||||||
|
return 'New';
|
||||||
|
}
|
||||||
|
|
||||||
|
appendRelayLog(tabId: string, msg: string): void {
|
||||||
|
const tab = this.tabs[tabId];
|
||||||
|
if (!tab) return;
|
||||||
|
tab.relayLogs += (tab.relayLogs ? '\n' : '') + msg;
|
||||||
|
let rendered = false;
|
||||||
|
if (tab.headless) rendered = this.parseHeadlessLog(tabId, msg);
|
||||||
|
if (tabId === this.activeTabId && !rendered) {
|
||||||
|
const el = document.getElementById('relayLog');
|
||||||
|
if (el) {
|
||||||
|
if (el.textContent!.length > 0) el.textContent += '\n';
|
||||||
|
el.textContent += msg;
|
||||||
|
el.scrollTop = el.scrollHeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseHeadlessLog(tabId: string, msg: string): boolean {
|
||||||
|
const tab = this.tabs[tabId];
|
||||||
|
if (!tab) return false;
|
||||||
|
const trimmed = msg.trim();
|
||||||
|
let changed = false;
|
||||||
|
|
||||||
|
if (trimmed === HeadlessLogMarker.CALL_CREATED) {
|
||||||
|
tab.callInfo = {};
|
||||||
|
tab.headlessStatus = 'Call created';
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (trimmed.includes(HeadlessLogMarker.JOIN_LINK)) {
|
||||||
|
if (!tab.callInfo) tab.callInfo = {};
|
||||||
|
tab.callInfo.joinLink = trimmed.split(HeadlessLogMarker.JOIN_LINK)[1].trim();
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (trimmed.includes(HeadlessLogMarker.SHORT_LINK)) {
|
||||||
|
if (!tab.callInfo) tab.callInfo = {};
|
||||||
|
tab.callInfo.shortLink = trimmed.split(HeadlessLogMarker.SHORT_LINK)[1].trim();
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (trimmed.includes(HeadlessLogMarker.TURN)) {
|
||||||
|
if (!tab.callInfo) tab.callInfo = {};
|
||||||
|
tab.callInfo.turn = trimmed.split(HeadlessLogMarker.TURN)[1].trim();
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (trimmed.includes(HeadlessLogMarker.PROTOCOL)) {
|
||||||
|
if (!tab.callInfo) tab.callInfo = {};
|
||||||
|
tab.callInfo.protocol = trimmed.split(HeadlessLogMarker.PROTOCOL)[1].trim();
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (trimmed.includes('[FATAL]')) {
|
||||||
|
const fatalMessage = trimmed.split('[FATAL]')[1]?.trim() || 'fatal error';
|
||||||
|
tab.headlessStatus = 'Disconnected: ' + fatalMessage;
|
||||||
|
tab.tunnelConnected = false;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (changed && tabId === this.activeTabId) this.onRender();
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
setTunnelMode(mode: string): void {
|
||||||
|
if (!this.activeTabId) return;
|
||||||
|
const tab = this.tabs[this.activeTabId];
|
||||||
|
if (!tab) return;
|
||||||
|
tab.mode = mode as TunnelMode;
|
||||||
|
window.bridge.setTunnelMode(this.activeTabId, mode).then(() => {
|
||||||
|
if (tab.wv) {
|
||||||
|
tab.wv.executeJavaScript('window.__hookInstalled = false').catch(() => {});
|
||||||
|
tab.wv.reload();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
saveBotSettings(): void {
|
||||||
|
localStorage.setItem('botSettings', JSON.stringify(this.botSettings));
|
||||||
|
}
|
||||||
|
|
||||||
|
toggleBot(): void {
|
||||||
|
if (!this.botSettings.token || !this.botSettings.groupId) return;
|
||||||
|
this.botRunning = !this.botRunning;
|
||||||
|
localStorage.setItem('botEnabled', this.botRunning ? 'true' : 'false');
|
||||||
|
if (this.botRunning) {
|
||||||
|
window.bridge.startBot(this.botSettings);
|
||||||
|
} else {
|
||||||
|
window.bridge.stopBot();
|
||||||
|
}
|
||||||
|
this.onRender();
|
||||||
|
}
|
||||||
|
|
||||||
|
autoStartBot(): void {
|
||||||
|
if (
|
||||||
|
localStorage.getItem('botEnabled') === 'true' &&
|
||||||
|
this.botSettings.token &&
|
||||||
|
this.botSettings.groupId
|
||||||
|
) {
|
||||||
|
this.botRunning = true;
|
||||||
|
window.bridge.startBot(this.botSettings);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import type { ChildProcess } from 'child_process';
|
||||||
|
|
||||||
|
export enum TunnelMode {
|
||||||
|
DC = 'dc',
|
||||||
|
PionVideo = 'pion-video',
|
||||||
|
HeadlessVK = 'headless-vk',
|
||||||
|
HeadlessTelemost = 'headless-telemost',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum Platform {
|
||||||
|
VK = 'vk',
|
||||||
|
Telemost = 'telemost',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum RelayMode {
|
||||||
|
DCCreator = 'dc-creator',
|
||||||
|
TelemostVideoCreator = 'telemost-video-creator',
|
||||||
|
VKVideoCreator = 'vk-video-creator',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum CallStatus {
|
||||||
|
Active = 'active',
|
||||||
|
Inactive = 'inactive',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum BotCommand {
|
||||||
|
VK = 'vk',
|
||||||
|
TM = 'tm',
|
||||||
|
List = 'list',
|
||||||
|
Menu = 'menu',
|
||||||
|
Close = 'close',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum LogPanel {
|
||||||
|
Relay = 'relay',
|
||||||
|
Hook = 'hook',
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PortPair {
|
||||||
|
dc: number;
|
||||||
|
pion: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TabState {
|
||||||
|
relay: ChildProcess | null;
|
||||||
|
tunnelMode: TunnelMode;
|
||||||
|
platform: Platform;
|
||||||
|
dcPort: number;
|
||||||
|
pionPort: number;
|
||||||
|
peerId?: number;
|
||||||
|
isBot?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BotSettings {
|
||||||
|
token: string;
|
||||||
|
groupId: string;
|
||||||
|
userId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TabConfig {
|
||||||
|
mode: TunnelMode;
|
||||||
|
peerId: number;
|
||||||
|
platform: Platform;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TabListEntry {
|
||||||
|
id: string;
|
||||||
|
platform: Platform;
|
||||||
|
mode: TunnelMode;
|
||||||
|
isBot: boolean;
|
||||||
|
callStatus: CallStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CallInfo {
|
||||||
|
joinLink?: string;
|
||||||
|
shortLink?: string;
|
||||||
|
turn?: string;
|
||||||
|
protocol?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Webview extends Electron.WebviewTag {
|
||||||
|
getURL(): string;
|
||||||
|
setAudioMuted(muted: boolean): void;
|
||||||
|
executeJavaScript(code: string): Promise<any>;
|
||||||
|
reload(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RendererTab {
|
||||||
|
wv: Webview | null;
|
||||||
|
url: string;
|
||||||
|
mode: TunnelMode;
|
||||||
|
relayLogs: string;
|
||||||
|
hookLogs: string;
|
||||||
|
name: string;
|
||||||
|
isBot: boolean;
|
||||||
|
peerId?: number;
|
||||||
|
platform?: Platform;
|
||||||
|
headless?: boolean;
|
||||||
|
headlessStatus?: string;
|
||||||
|
callInfo?: CallInfo;
|
||||||
|
tunnelConnected?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BotTabData {
|
||||||
|
tabId: string;
|
||||||
|
mode: TunnelMode;
|
||||||
|
peerId: number;
|
||||||
|
platform: Platform;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RelayLogData {
|
||||||
|
tabId: string;
|
||||||
|
msg: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Bridge {
|
||||||
|
onRelayLog(cb: (tabId: string, msg: string) => void): void;
|
||||||
|
getHookCode(tabId: string, url: string): Promise<string>;
|
||||||
|
setTunnelMode(tabId: string, mode: string): Promise<void>;
|
||||||
|
startRelay(tabId: string): Promise<void>;
|
||||||
|
closeTab(tabId: string): Promise<void>;
|
||||||
|
startBot(settings: BotSettings): Promise<void>;
|
||||||
|
stopBot(): Promise<void>;
|
||||||
|
onCreateBotTab(cb: (data: BotTabData) => void): void;
|
||||||
|
getCallCreatorCode(scriptFile: string): Promise<string>;
|
||||||
|
onBotError(cb: (msg: string) => void): void;
|
||||||
|
getCookies(domain: string): Promise<Electron.Cookie[]>;
|
||||||
|
startHeadless(tabId: string, platform: string): Promise<void>;
|
||||||
|
onCloseBotTab(cb: (data: { tabId: string }) => void): void;
|
||||||
|
}
|
||||||
@@ -0,0 +1,467 @@
|
|||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, sans-serif;
|
||||||
|
background: #1a1a1a;
|
||||||
|
color: #e0e0e0;
|
||||||
|
height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-bar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
background: #222;
|
||||||
|
border-bottom: 1px solid #333;
|
||||||
|
height: 36px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-bar-tabs {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
height: 100%;
|
||||||
|
flex: 1;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-bar-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
height: 100%;
|
||||||
|
border-left: 1px solid #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 0 12px;
|
||||||
|
height: 100%;
|
||||||
|
font-size: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
border-right: 1px solid #333;
|
||||||
|
white-space: nowrap;
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab.active {
|
||||||
|
background: #1a1a1a;
|
||||||
|
color: #e0e0e0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab .close {
|
||||||
|
font-size: 14px;
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: pointer;
|
||||||
|
margin-left: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab .close:hover {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab .edit {
|
||||||
|
width: 12px;
|
||||||
|
height: 12px;
|
||||||
|
opacity: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
filter: invert(1) brightness(2);
|
||||||
|
margin-left: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab:hover .edit {
|
||||||
|
opacity: 0.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab .edit:hover {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-add {
|
||||||
|
padding: 0 12px;
|
||||||
|
height: 100%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
font-size: 16px;
|
||||||
|
cursor: pointer;
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-add:hover {
|
||||||
|
color: #e0e0e0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-action-btn {
|
||||||
|
padding: 0 12px;
|
||||||
|
height: 100%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
font-size: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-action-btn:hover {
|
||||||
|
color: #e0e0e0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-action-btn.settings {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-action-btn.bot {
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-action-btn.running {
|
||||||
|
color: #dc3545;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-rename-input {
|
||||||
|
width: 80px;
|
||||||
|
padding: 0 4px;
|
||||||
|
border: 1px solid #555;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
background: #111;
|
||||||
|
color: #e0e0e0;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 6px 12px;
|
||||||
|
background: #252525;
|
||||||
|
border-bottom: 1px solid #333;
|
||||||
|
height: 36px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar button {
|
||||||
|
padding: 3px 12px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-vk {
|
||||||
|
background: #0077ff;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-telemost {
|
||||||
|
background: #fc3f1d;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-headless {
|
||||||
|
background: #0077ff;
|
||||||
|
color: white;
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-headless-tm {
|
||||||
|
background: #fc3f1d;
|
||||||
|
color: white;
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-spacer {
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-label {
|
||||||
|
font-size: 11px;
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-select {
|
||||||
|
padding: 2px 6px;
|
||||||
|
border: 1px solid #555;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 11px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: 500;
|
||||||
|
background: #333;
|
||||||
|
color: #e0e0e0;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-icon {
|
||||||
|
cursor: pointer;
|
||||||
|
margin-left: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-icon img {
|
||||||
|
height: 16px;
|
||||||
|
vertical-align: middle;
|
||||||
|
filter: invert(1) brightness(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
flex: 1;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content webview {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
border: none;
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content webview.hidden {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.webview-full {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.welcome {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 100%;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.welcome h1 {
|
||||||
|
font-size: 22px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.welcome p {
|
||||||
|
color: #888;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.headless-info {
|
||||||
|
display: none;
|
||||||
|
padding: 24px;
|
||||||
|
color: #e0e0e0;
|
||||||
|
font-family: monospace;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.headless-title {
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: bold;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.headless-status {
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
|
||||||
|
.headless-call-info {
|
||||||
|
margin-top: 16px;
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.headless-row {
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.headless-label {
|
||||||
|
color: #888;
|
||||||
|
}
|
||||||
|
|
||||||
|
.headless-link {
|
||||||
|
color: #4fc3f7;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.headless-copy {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
margin-left: 6px;
|
||||||
|
cursor: pointer;
|
||||||
|
vertical-align: middle;
|
||||||
|
filter: invert(0.53);
|
||||||
|
}
|
||||||
|
|
||||||
|
.headless-copy:hover {
|
||||||
|
filter: invert(0.88);
|
||||||
|
}
|
||||||
|
|
||||||
|
.headless-tunnel {
|
||||||
|
margin-top: 16px;
|
||||||
|
display: none;
|
||||||
|
color: #4caf50;
|
||||||
|
font-weight: bold;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logs {
|
||||||
|
display: flex;
|
||||||
|
gap: 0;
|
||||||
|
border-top: 1px solid #333;
|
||||||
|
height: 120px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-panel {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-panel:first-child {
|
||||||
|
border-right: 1px solid #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-title {
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #888;
|
||||||
|
padding: 3px 8px;
|
||||||
|
background: #1e1e1e;
|
||||||
|
border-bottom: 1px solid #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-clear-btn {
|
||||||
|
cursor: pointer;
|
||||||
|
float: right;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-content {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 3px 8px;
|
||||||
|
font-family: monospace;
|
||||||
|
font-size: 10px;
|
||||||
|
background: #111;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-content.relay {
|
||||||
|
color: #4fc3f7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-content.hook {
|
||||||
|
color: #66bb6a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup-overlay {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.7);
|
||||||
|
z-index: 1000;
|
||||||
|
display: none;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup-overlay.visible {
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup {
|
||||||
|
background: #2a2a2a;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 24px;
|
||||||
|
width: 400px;
|
||||||
|
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup h2 {
|
||||||
|
margin: 0 0 20px;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #e0e0e0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #888;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid #444;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 14px;
|
||||||
|
background: #1a1a1a;
|
||||||
|
color: #e0e0e0;
|
||||||
|
outline: none;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup input:focus {
|
||||||
|
border-color: #0077ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup-buttons {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.popup button {
|
||||||
|
padding: 8px 16px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 13px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-save {
|
||||||
|
background: #0077ff;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-cancel {
|
||||||
|
background: #444;
|
||||||
|
color: #e0e0e0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-title {
|
||||||
|
color: #dc3545;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-text {
|
||||||
|
background: #111;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 11px;
|
||||||
|
color: #e0e0e0;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-all;
|
||||||
|
max-height: 200px;
|
||||||
|
overflow-y: auto;
|
||||||
|
user-select: text;
|
||||||
|
cursor: text;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
class TelemostAutoclick {
|
|
||||||
constructor() {
|
|
||||||
this._interval = null;
|
|
||||||
this._wvContents = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
attach(wvContents) {
|
|
||||||
this.stop();
|
|
||||||
this._wvContents = wvContents;
|
|
||||||
this._interval = setInterval(() => this._scan(), 2000);
|
|
||||||
wvContents.on('destroyed', () => this.stop());
|
|
||||||
}
|
|
||||||
|
|
||||||
stop() {
|
|
||||||
if (this._interval) {
|
|
||||||
clearInterval(this._interval);
|
|
||||||
this._interval = null;
|
|
||||||
}
|
|
||||||
this._wvContents = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
_scan() {
|
|
||||||
try {
|
|
||||||
this._wvContents.mainFrame.framesInSubtree.forEach((frame) => {
|
|
||||||
frame.executeJavaScript(`
|
|
||||||
(function() {
|
|
||||||
var buttons = document.querySelectorAll('.Orb-Button, button, [role="button"], [role="link"]');
|
|
||||||
var admitBtn = null;
|
|
||||||
for (var i = 0; i < buttons.length; i++) {
|
|
||||||
var txt = buttons[i].textContent.replace(/\\s+/g, ' ').trim();
|
|
||||||
if (txt.indexOf('Впустить') !== -1) {
|
|
||||||
admitBtn = buttons[i];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!admitBtn) return 'idle';
|
|
||||||
|
|
||||||
// Find guest's participant name
|
|
||||||
var names = document.querySelectorAll('[class*="participantName"]');
|
|
||||||
for (var j = 0; j < names.length; j++) {
|
|
||||||
if (names[j].closest('[class*="selfView"]')) continue;
|
|
||||||
var moreBtn = names[j].querySelector('[data-testid="show-moderation-popup"]');
|
|
||||||
if (moreBtn) {
|
|
||||||
moreBtn.click();
|
|
||||||
return 'kick-open';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
admitBtn.click();
|
|
||||||
return 'admitted';
|
|
||||||
})()
|
|
||||||
`).then((r) => {
|
|
||||||
if (r === 'kick-open') {
|
|
||||||
setTimeout(() => this._clickRemove(frame), 500);
|
|
||||||
} else if (r === 'admitted') {
|
|
||||||
console.log('[auto-accept] guest admitted');
|
|
||||||
}
|
|
||||||
}).catch(function() {});
|
|
||||||
});
|
|
||||||
} catch(e) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
_clickRemove(frame) {
|
|
||||||
frame.executeJavaScript(`
|
|
||||||
(function() {
|
|
||||||
var el = document.querySelector('[title="Удалить со встречи"]');
|
|
||||||
if (el) { el.click(); return true; }
|
|
||||||
return false;
|
|
||||||
})()
|
|
||||||
`).then((r) => {
|
|
||||||
if (r) setTimeout(() => this._confirmRemove(frame), 500);
|
|
||||||
}).catch(function() {});
|
|
||||||
}
|
|
||||||
|
|
||||||
_confirmRemove(frame) {
|
|
||||||
frame.executeJavaScript(`
|
|
||||||
(function() {
|
|
||||||
var modal = document.querySelector('[data-testid="orb-modal2"]');
|
|
||||||
if (!modal) return false;
|
|
||||||
var btns = modal.querySelectorAll('button');
|
|
||||||
for (var i = 0; i < btns.length; i++) {
|
|
||||||
var txt = btns[i].textContent.replace(/\\s+/g, ' ').trim();
|
|
||||||
if (txt === 'Удалить') {
|
|
||||||
btns[i].click();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
})()
|
|
||||||
`).then((r) => {
|
|
||||||
if (r) console.log('[auto-accept] kicked previous participant');
|
|
||||||
}).catch(function() {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = TelemostAutoclick;
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
(function() {
|
|
||||||
if (window.__tmCallCreatorStarted) return;
|
|
||||||
window.__tmCallCreatorStarted = true;
|
|
||||||
|
|
||||||
const start = () => {
|
|
||||||
console.log("[BOT] Telemost: DOM ready...");
|
|
||||||
|
|
||||||
const waitAndClick = (fn) => {
|
|
||||||
if (fn()) return;
|
|
||||||
|
|
||||||
const observer = new MutationObserver(() => {
|
|
||||||
if (fn()) observer.disconnect();
|
|
||||||
});
|
|
||||||
|
|
||||||
observer.observe(document.body, { childList: true, subtree: true });
|
|
||||||
};
|
|
||||||
|
|
||||||
waitAndClick(() => {
|
|
||||||
const btn = document.querySelector('[data-testid="create-call-button"]');
|
|
||||||
|
|
||||||
if (btn) {
|
|
||||||
btn.click();
|
|
||||||
console.log("[BOT] Telemost: creating call...");
|
|
||||||
|
|
||||||
const check = setInterval(() => {
|
|
||||||
const url = location.href;
|
|
||||||
|
|
||||||
if (url.includes('/j/')) {
|
|
||||||
console.log("[BOT] Telemost: call link:", url);
|
|
||||||
window.__CALL_LINK__ = url;
|
|
||||||
clearInterval(check);
|
|
||||||
}
|
|
||||||
}, 300);
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
if (document.readyState === "loading") {
|
|
||||||
document.addEventListener("DOMContentLoaded", start);
|
|
||||||
} else {
|
|
||||||
start();
|
|
||||||
}
|
|
||||||
|
|
||||||
})();
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ESNext",
|
||||||
|
"module": "commonjs",
|
||||||
|
"lib": ["ESNext", "DOM"],
|
||||||
|
"outDir": "dist",
|
||||||
|
"rootDir": "src",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"declaration": false,
|
||||||
|
"sourceMap": true
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts"],
|
||||||
|
"exclude": ["node_modules", "dist", "scripts"]
|
||||||
|
}
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
class VkAutoclick {
|
|
||||||
constructor() {
|
|
||||||
this._interval = null;
|
|
||||||
this._wvContents = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
attach(wvContents) {
|
|
||||||
this.stop();
|
|
||||||
this._wvContents = wvContents;
|
|
||||||
this._interval = setInterval(() => this._scan(), 2000);
|
|
||||||
wvContents.on('destroyed', () => this.stop());
|
|
||||||
}
|
|
||||||
|
|
||||||
stop() {
|
|
||||||
if (this._interval) {
|
|
||||||
clearInterval(this._interval);
|
|
||||||
this._interval = null;
|
|
||||||
}
|
|
||||||
this._wvContents = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
_scan() {
|
|
||||||
try {
|
|
||||||
this._wvContents.mainFrame.framesInSubtree.forEach((frame) => {
|
|
||||||
frame.executeJavaScript(`
|
|
||||||
(function() {
|
|
||||||
var admitBtn = document.querySelector('[data-testid="calls_waiting_hall_promote"]');
|
|
||||||
if (!admitBtn) return 'idle';
|
|
||||||
|
|
||||||
// Kick current participant first if present (skip first = owner)
|
|
||||||
var menuBtns = document.querySelectorAll('[data-testid="calls_participant_list_item_menu_button"]');
|
|
||||||
if (menuBtns.length > 1) {
|
|
||||||
menuBtns[menuBtns.length - 1].click();
|
|
||||||
return 'kick-open';
|
|
||||||
}
|
|
||||||
|
|
||||||
admitBtn.click();
|
|
||||||
return 'admitted';
|
|
||||||
})()
|
|
||||||
`).then((r) => {
|
|
||||||
if (r === 'kick-open') {
|
|
||||||
setTimeout(() => this._clickKick(frame), 500);
|
|
||||||
} else if (r === 'admitted') {
|
|
||||||
console.log('[auto-accept] VK guest admitted');
|
|
||||||
}
|
|
||||||
}).catch(function() {});
|
|
||||||
});
|
|
||||||
} catch(e) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
_clickKick(frame) {
|
|
||||||
frame.executeJavaScript(`
|
|
||||||
(function() {
|
|
||||||
var btn = document.querySelector('[data-testid="calls_participant_actions_kick"]');
|
|
||||||
if (btn) { btn.click(); return true; }
|
|
||||||
return false;
|
|
||||||
})()
|
|
||||||
`).then((r) => {
|
|
||||||
if (r) setTimeout(() => this._confirmKick(frame), 500);
|
|
||||||
}).catch(function() {});
|
|
||||||
}
|
|
||||||
|
|
||||||
_confirmKick(frame) {
|
|
||||||
frame.executeJavaScript(`
|
|
||||||
(function() {
|
|
||||||
var btn = document.querySelector('[data-testid="calls_call_kick_submit"]');
|
|
||||||
if (btn) { btn.click(); return true; }
|
|
||||||
return false;
|
|
||||||
})()
|
|
||||||
`).then((r) => {
|
|
||||||
if (r) console.log('[auto-accept] VK kicked previous participant');
|
|
||||||
}).catch(function() {});
|
|
||||||
}
|
|
||||||
|
|
||||||
kickDisconnected() {
|
|
||||||
if (!this._wvContents) return;
|
|
||||||
try {
|
|
||||||
this._wvContents.mainFrame.framesInSubtree.forEach((frame) => {
|
|
||||||
frame.executeJavaScript(`
|
|
||||||
(function() {
|
|
||||||
var menuBtns = document.querySelectorAll('[data-testid="calls_participant_list_item_menu_button"]');
|
|
||||||
var menuBtn = menuBtns.length > 1 ? menuBtns[menuBtns.length - 1] : null;
|
|
||||||
if (menuBtn) { menuBtn.click(); return true; }
|
|
||||||
return false;
|
|
||||||
})()
|
|
||||||
`).then((r) => {
|
|
||||||
if (r) setTimeout(() => this._clickKick(frame), 500);
|
|
||||||
}).catch(function() {});
|
|
||||||
});
|
|
||||||
} catch(e) {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = VkAutoclick;
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
(function() {
|
|
||||||
if (window.__callCreatorStarted) return;
|
|
||||||
window.__callCreatorStarted = true;
|
|
||||||
|
|
||||||
const start = () => {
|
|
||||||
console.log("[BOT] VKCalls: DOM ready...");
|
|
||||||
|
|
||||||
const waitAndClick = (fn) => {
|
|
||||||
if (fn()) return;
|
|
||||||
|
|
||||||
const observer = new MutationObserver(() => {
|
|
||||||
if (fn()) observer.disconnect();
|
|
||||||
});
|
|
||||||
|
|
||||||
observer.observe(document.body, { childList: true, subtree: true });
|
|
||||||
};
|
|
||||||
|
|
||||||
waitAndClick(() => {
|
|
||||||
const trigger = document.getElementById('call-menu-trigger');
|
|
||||||
|
|
||||||
if (trigger) {
|
|
||||||
trigger.click();
|
|
||||||
console.log("[BOT] VKCalls: opened call menu");
|
|
||||||
|
|
||||||
waitAndClick(() => {
|
|
||||||
const el = [...document.querySelectorAll('span')]
|
|
||||||
.find(e => e.textContent.includes('Создать звонок по'));
|
|
||||||
|
|
||||||
const btn = el?.closest('button, div');
|
|
||||||
|
|
||||||
if (btn) {
|
|
||||||
btn.click();
|
|
||||||
console.log("[BOT] VKCalls: created call");
|
|
||||||
|
|
||||||
const origFetch = window.fetch;
|
|
||||||
window.fetch = async (...args) => {
|
|
||||||
const res = await origFetch(...args);
|
|
||||||
|
|
||||||
if (window.__CALL_LINK_CAPTURED__) return res;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const clone = res.clone();
|
|
||||||
const text = await clone.text();
|
|
||||||
|
|
||||||
if (text.includes("call_in_progress")) {
|
|
||||||
const json = JSON.parse(text);
|
|
||||||
const items = json?.response?.[1]?.items;
|
|
||||||
|
|
||||||
if (items) {
|
|
||||||
for (const item of items) {
|
|
||||||
const join = item?.call_in_progress?.join_link;
|
|
||||||
if (join) {
|
|
||||||
const link = "https://vk.com/call/join/" + join;
|
|
||||||
|
|
||||||
console.log("[BOT] VKCalls: call link:", link);
|
|
||||||
window.__CALL_LINK__ = link;
|
|
||||||
|
|
||||||
window.__CALL_LINK_CAPTURED__ = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {}
|
|
||||||
|
|
||||||
return res;
|
|
||||||
};
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
if (document.readyState === "loading") {
|
|
||||||
document.addEventListener("DOMContentLoaded", start);
|
|
||||||
} else {
|
|
||||||
start();
|
|
||||||
}
|
|
||||||
|
|
||||||
})();
|
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
FROM eclipse-temurin:17-jdk-jammy
|
||||||
|
|
||||||
|
ARG GO_VERSION=1.26.1
|
||||||
|
ARG ANDROID_CMDLINE_TOOLS=13114758
|
||||||
|
ARG ANDROID_NDK_VERSION=29.0.14206865
|
||||||
|
ARG ANDROID_PLATFORM=android-36
|
||||||
|
ARG ANDROID_BUILD_TOOLS=36.0.0
|
||||||
|
|
||||||
|
ENV DEBIAN_FRONTEND=noninteractive \
|
||||||
|
ANDROID_SDK_ROOT=/opt/android-sdk \
|
||||||
|
ANDROID_HOME=/opt/android-sdk \
|
||||||
|
ANDROID_NDK_HOME=/opt/android-sdk/ndk/${ANDROID_NDK_VERSION} \
|
||||||
|
GRADLE_USER_HOME=/opt/gradle \
|
||||||
|
PATH=/usr/local/go/bin:/root/go/bin:/opt/android-sdk/cmdline-tools/latest/bin:/opt/android-sdk/platform-tools:${PATH} \
|
||||||
|
WINEPREFIX=/root/.wine
|
||||||
|
|
||||||
|
RUN dpkg --add-architecture i386 \
|
||||||
|
&& apt update \
|
||||||
|
&& apt install -y --no-install-recommends --no-install-suggests \
|
||||||
|
bash build-essential ca-certificates curl git \
|
||||||
|
libc6-dev pkg-config python3 rsync \
|
||||||
|
gcc-multilib g++-multilib \
|
||||||
|
unzip wget zip gnupg \
|
||||||
|
wine64 wine32 wine \
|
||||||
|
&& apt clean \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
RUN wget -q https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz -O /tmp/go.tgz \
|
||||||
|
&& tar -C /usr/local -xzf /tmp/go.tgz \
|
||||||
|
&& rm /tmp/go.tgz
|
||||||
|
|
||||||
|
RUN mkdir -p ${ANDROID_SDK_ROOT}/cmdline-tools /workspace /opt/gradle \
|
||||||
|
&& mkdir -p /root/Library/Android \
|
||||||
|
&& ln -s ${ANDROID_SDK_ROOT} /root/Library/Android/sdk \
|
||||||
|
&& wget -q https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_CMDLINE_TOOLS}_latest.zip \
|
||||||
|
-O /tmp/cmdline-tools.zip \
|
||||||
|
&& unzip -q /tmp/cmdline-tools.zip -d ${ANDROID_SDK_ROOT}/cmdline-tools \
|
||||||
|
&& mv ${ANDROID_SDK_ROOT}/cmdline-tools/cmdline-tools ${ANDROID_SDK_ROOT}/cmdline-tools/latest \
|
||||||
|
&& rm /tmp/cmdline-tools.zip \
|
||||||
|
&& yes | sdkmanager --licenses >/dev/null \
|
||||||
|
&& sdkmanager \
|
||||||
|
"platform-tools" \
|
||||||
|
"platforms;${ANDROID_PLATFORM}" \
|
||||||
|
"build-tools;${ANDROID_BUILD_TOOLS}" \
|
||||||
|
"ndk;${ANDROID_NDK_VERSION}" \
|
||||||
|
&& rm -rf ${ANDROID_SDK_ROOT}/ndk/${ANDROID_NDK_VERSION}/simpleperf \
|
||||||
|
&& rm -rf ${ANDROID_SDK_ROOT}/ndk/${ANDROID_NDK_VERSION}/shader-tools \
|
||||||
|
&& rm -rf ${ANDROID_SDK_ROOT}/ndk/${ANDROID_NDK_VERSION}/sources/third_party \
|
||||||
|
&& rm -rf ${ANDROID_SDK_ROOT}/.downloadIntermediates \
|
||||||
|
&& rm -rf ${ANDROID_SDK_ROOT}/.temp
|
||||||
|
|
||||||
|
RUN go install golang.org/x/mobile/cmd/gomobile@latest \
|
||||||
|
&& go install golang.org/x/mobile/cmd/gobind@latest \
|
||||||
|
&& go install github.com/konoui/lipo@latest \
|
||||||
|
&& go clean -cache -modcache -testcache \
|
||||||
|
&& mkdir -p /etc/apt/keyrings \
|
||||||
|
&& curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key \
|
||||||
|
| gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg \
|
||||||
|
&& echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_22.x nodistro main" \
|
||||||
|
> /etc/apt/sources.list.d/nodesource.list \
|
||||||
|
&& apt update \
|
||||||
|
&& apt install -y --no-install-recommends --no-install-suggests nodejs \
|
||||||
|
&& apt clean \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
WORKDIR /workspace
|
||||||
Executable
+35
@@ -0,0 +1,35 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT=/workspace
|
||||||
|
REPO="${ROOT}/whitelist-bypass"
|
||||||
|
|
||||||
|
export HOME=/root
|
||||||
|
export ANDROID_HOME=/root/Library/Android/sdk
|
||||||
|
export ANDROID_SDK_ROOT=${ANDROID_HOME}
|
||||||
|
export ANDROID_NDK_HOME=${ANDROID_HOME}/ndk/29.0.14206865
|
||||||
|
export GRADLE_USER_HOME=/opt/gradle
|
||||||
|
export PATH=/usr/local/go/bin:/root/go/bin:${ANDROID_HOME}/cmdline-tools/latest/bin:${ANDROID_HOME}/platform-tools:${PATH}
|
||||||
|
|
||||||
|
cd "${REPO}/relay"
|
||||||
|
gomobile init -v
|
||||||
|
|
||||||
|
cd "${REPO}"
|
||||||
|
echo ""
|
||||||
|
echo "=== build-go.sh ==="
|
||||||
|
./build-go.sh
|
||||||
|
|
||||||
|
cd "${REPO}"
|
||||||
|
echo ""
|
||||||
|
echo "=== build-app.sh ==="
|
||||||
|
./build-app.sh
|
||||||
|
|
||||||
|
cd "${REPO}"
|
||||||
|
echo ""
|
||||||
|
echo "=== build-creator.sh ==="
|
||||||
|
./build-creator.sh
|
||||||
|
|
||||||
|
cd "${REPO}"
|
||||||
|
echo ""
|
||||||
|
echo "=== ALL BUILDS DONE ==="
|
||||||
|
ls -lh "${REPO}/prebuilts" || true
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
services:
|
||||||
|
build-all:
|
||||||
|
platform: linux/amd64
|
||||||
|
build:
|
||||||
|
context: ..
|
||||||
|
dockerfile: docker-build/Dockerfile
|
||||||
|
working_dir: /workspace
|
||||||
|
volumes:
|
||||||
|
- ../:/workspace/whitelist-bypass
|
||||||
|
- ./build-all.sh:/opt/build_all/build-all.sh
|
||||||
|
- android-sdk-cache:/opt/android-sdk
|
||||||
|
- android-gradle-cache:/opt/gradle
|
||||||
|
environment:
|
||||||
|
BUILD_NUMBER: "${BUILD_NUMBER:-0}"
|
||||||
|
command: "/opt/build_all/build-all.sh"
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
android-sdk-cache:
|
||||||
|
android-gradle-cache:
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
jsdom/
|
jsdom/
|
||||||
headless-creator
|
headless-creator
|
||||||
|
headless-*
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
)
|
|
||||||
|
|
||||||
// maskAddr masks the sensitive portion of an address for logging.
|
|
||||||
// IPv4: keeps first two octets, e.g. "192.168.x.x"
|
|
||||||
// IPv6: fully masked
|
|
||||||
// hostname: first char + "***"
|
|
||||||
// host:port: masks host, keeps port
|
|
||||||
func maskAddr(addr string) string {
|
|
||||||
host, port, err := net.SplitHostPort(addr)
|
|
||||||
if err != nil {
|
|
||||||
host = addr
|
|
||||||
port = ""
|
|
||||||
}
|
|
||||||
masked := maskHost(host)
|
|
||||||
if port != "" {
|
|
||||||
return net.JoinHostPort(masked, port)
|
|
||||||
}
|
|
||||||
return masked
|
|
||||||
}
|
|
||||||
|
|
||||||
func maskHost(host string) string {
|
|
||||||
if host == "" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
ip := net.ParseIP(host)
|
|
||||||
if ip != nil {
|
|
||||||
if ip4 := ip.To4(); ip4 != nil {
|
|
||||||
return fmt.Sprintf("%d.%d.x.x", ip4[0], ip4[1])
|
|
||||||
}
|
|
||||||
return "x::x"
|
|
||||||
}
|
|
||||||
if len(host) <= 1 {
|
|
||||||
return "*"
|
|
||||||
}
|
|
||||||
return string(host[0]) + "***"
|
|
||||||
}
|
|
||||||
+1
-1
@@ -3,7 +3,7 @@ interval="${1:-5}"
|
|||||||
printf "%-8s %-20s %10s %6s %6s\n" "TIME" "PROCESS" "RSS(MB)" "THR" "FD"
|
printf "%-8s %-20s %10s %6s %6s\n" "TIME" "PROCESS" "RSS(MB)" "THR" "FD"
|
||||||
echo "-------------------------------------------------------"
|
echo "-------------------------------------------------------"
|
||||||
while true; do
|
while true; do
|
||||||
pids=$(pgrep -f "headless-creator" 2>/dev/null)
|
pids=$(pgrep -f "headless-" 2>/dev/null)
|
||||||
if [ -z "$pids" ]; then
|
if [ -z "$pids" ]; then
|
||||||
printf "%-8s %s\n" "$(date +%H:%M:%S)" "no processes found"
|
printf "%-8s %s\n" "$(date +%H:%M:%S)" "no processes found"
|
||||||
else
|
else
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import "github.com/pion/webrtc/v4"
|
|
||||||
|
|
||||||
// Tunnel frame protocol constants shared between DC and video relay paths.
|
|
||||||
// Frame format: connID(4) + msgType(1) + payload
|
|
||||||
const (
|
|
||||||
msgConnect byte = 0x01
|
|
||||||
msgConnectOK byte = 0x02
|
|
||||||
msgConnectErr byte = 0x03
|
|
||||||
msgData byte = 0x04
|
|
||||||
msgClose byte = 0x05
|
|
||||||
msgUDP byte = 0x06
|
|
||||||
msgUDPReply byte = 0x07
|
|
||||||
|
|
||||||
socksVer = 0x05
|
|
||||||
socksCmdTCP = 0x01
|
|
||||||
socksCmdUDP = 0x03
|
|
||||||
socksAtypIPv4 = 0x01
|
|
||||||
socksAtypDomain = 0x03
|
|
||||||
socksAtypIPv6 = 0x04
|
|
||||||
|
|
||||||
socksHandshakeBuf = 258
|
|
||||||
udpBufSize = 4096
|
|
||||||
rtpBufSize = 65536
|
|
||||||
vp8RelayBufSize = 900
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
socksNoAuth = []byte{socksVer, 0x00}
|
|
||||||
socksOK = []byte{socksVer, 0x00, 0x00, socksAtypIPv4, 0, 0, 0, 0, 0, 0}
|
|
||||||
socksConnFail = []byte{socksVer, 0x05, 0x00, socksAtypIPv4, 0, 0, 0, 0, 0, 0}
|
|
||||||
socksCmdErr = []byte{socksVer, 0x07, 0x00, socksAtypIPv4, 0, 0, 0, 0, 0, 0}
|
|
||||||
socksAddrErr = []byte{socksVer, 0x08, 0x00, socksAtypIPv4, 0, 0, 0, 0, 0, 0}
|
|
||||||
socksGenFail = []byte{socksVer, 0x01, 0x00, socksAtypIPv4, 0, 0, 0, 0, 0, 0}
|
|
||||||
)
|
|
||||||
|
|
||||||
// Relay is the common interface for DCRelay and VideoRelay.
|
|
||||||
type Relay interface {
|
|
||||||
Init(iceServers []webrtc.ICEServer) error
|
|
||||||
CreateOffer() (webrtc.SessionDescription, error)
|
|
||||||
CreateAnswer() (webrtc.SessionDescription, error)
|
|
||||||
SetRemoteDescription(sdpType webrtc.SDPType, sdp string) error
|
|
||||||
AddICECandidate(candidate webrtc.ICECandidateInit) error
|
|
||||||
OnICECandidate(fn func(*webrtc.ICECandidate))
|
|
||||||
OnConnectionStateChange(fn func(webrtc.PeerConnectionState))
|
|
||||||
Close()
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"regexp"
|
||||||
|
|
||||||
|
"whitelist-bypass/relay/common"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TMConfig struct {
|
||||||
|
AppVersion string
|
||||||
|
SDKVersion string
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchConfig() (TMConfig, error) {
|
||||||
|
var cfg TMConfig
|
||||||
|
|
||||||
|
page, err := common.HttpGet("https://telemost.yandex.ru/")
|
||||||
|
if err != nil {
|
||||||
|
return cfg, fmt.Errorf("failed to fetch telemost.yandex.ru: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
stateRe := regexp.MustCompile(`<script[^>]*id="preloaded-state"[^>]*>([\s\S]*?)</script>`)
|
||||||
|
stateMatch := stateRe.FindSubmatch(page)
|
||||||
|
if stateMatch == nil {
|
||||||
|
return cfg, fmt.Errorf("preloaded-state not found in page")
|
||||||
|
}
|
||||||
|
var state struct {
|
||||||
|
Config struct {
|
||||||
|
AppVersion string `json:"appVersion"`
|
||||||
|
} `json:"config"`
|
||||||
|
AppVersion string `json:"appVersion"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(stateMatch[1], &state); err != nil {
|
||||||
|
return cfg, fmt.Errorf("failed to parse preloaded-state: %w", err)
|
||||||
|
}
|
||||||
|
cfg.AppVersion = state.Config.AppVersion
|
||||||
|
if cfg.AppVersion == "" {
|
||||||
|
cfg.AppVersion = state.AppVersion
|
||||||
|
}
|
||||||
|
if cfg.AppVersion == "" {
|
||||||
|
return cfg, fmt.Errorf("appVersion not found in preloaded-state")
|
||||||
|
}
|
||||||
|
log.Printf("[config] appVersion=%s", cfg.AppVersion)
|
||||||
|
|
||||||
|
bundleRe := regexp.MustCompile(`https://telemost\.yastatic\.net/s3/telemost/_/main\.\w+\.[a-f0-9]+\.js`)
|
||||||
|
bundleURL := bundleRe.FindString(string(page))
|
||||||
|
if bundleURL == "" {
|
||||||
|
return cfg, fmt.Errorf("main bundle URL not found in page")
|
||||||
|
}
|
||||||
|
log.Printf("[config] Found bundle: %s", bundleURL)
|
||||||
|
|
||||||
|
bundle, err := common.HttpGet(bundleURL)
|
||||||
|
if err != nil {
|
||||||
|
return cfg, fmt.Errorf("failed to fetch bundle: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
sdkVerRe := regexp.MustCompile(`goloom-sdk\.(\d+\.\d+\.\d+)\.js`)
|
||||||
|
if m := sdkVerRe.FindSubmatch(bundle); m != nil {
|
||||||
|
cfg.SDKVersion = string(m[1])
|
||||||
|
} else {
|
||||||
|
return cfg, fmt.Errorf("goloom SDK version not found in bundle")
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("[config] app=%s sdk=%s", cfg.AppVersion, cfg.SDKVersion)
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
module headless-creator
|
||||||
|
|
||||||
|
go 1.26.1
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/gorilla/websocket v1.5.3
|
||||||
|
github.com/pion/rtp v1.10.1
|
||||||
|
github.com/pion/webrtc/v4 v4.2.11
|
||||||
|
whitelist-bypass/relay v0.0.0
|
||||||
|
)
|
||||||
|
|
||||||
|
replace whitelist-bypass/relay => ../../relay
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/pion/datachannel v1.6.0 // indirect
|
||||||
|
github.com/pion/dtls/v3 v3.1.2 // indirect
|
||||||
|
github.com/pion/ice/v4 v4.2.2 // indirect
|
||||||
|
github.com/pion/interceptor v0.1.44 // indirect
|
||||||
|
github.com/pion/logging v0.2.4 // indirect
|
||||||
|
github.com/pion/mdns/v2 v2.1.0 // indirect
|
||||||
|
github.com/pion/randutil v0.1.0 // indirect
|
||||||
|
github.com/pion/rtcp v1.2.16 // indirect
|
||||||
|
github.com/pion/sctp v1.9.4 // indirect
|
||||||
|
github.com/pion/sdp/v3 v3.0.18 // indirect
|
||||||
|
github.com/pion/srtp/v3 v3.0.10 // indirect
|
||||||
|
github.com/pion/stun/v3 v3.1.1 // indirect
|
||||||
|
github.com/pion/transport/v4 v4.0.1 // indirect
|
||||||
|
github.com/pion/turn/v4 v4.1.4 // indirect
|
||||||
|
github.com/wlynxg/anet v0.0.5 // indirect
|
||||||
|
golang.org/x/crypto v0.49.0 // indirect
|
||||||
|
golang.org/x/net v0.52.0 // indirect
|
||||||
|
golang.org/x/sys v0.42.0 // indirect
|
||||||
|
golang.org/x/time v0.11.0 // indirect
|
||||||
|
)
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
@@ -28,19 +30,27 @@ github.com/pion/srtp/v3 v3.0.10 h1:tFirkpBb3XccP5VEXLi50GqXhv5SKPxqrdlhDCJlZrQ=
|
|||||||
github.com/pion/srtp/v3 v3.0.10/go.mod h1:3mOTIB0cq9qlbn59V4ozvv9ClW/BSEbRp4cY0VtaR7M=
|
github.com/pion/srtp/v3 v3.0.10/go.mod h1:3mOTIB0cq9qlbn59V4ozvv9ClW/BSEbRp4cY0VtaR7M=
|
||||||
github.com/pion/stun/v3 v3.1.1 h1:CkQxveJ4xGQjulGSROXbXq94TAWu8gIX2dT+ePhUkqw=
|
github.com/pion/stun/v3 v3.1.1 h1:CkQxveJ4xGQjulGSROXbXq94TAWu8gIX2dT+ePhUkqw=
|
||||||
github.com/pion/stun/v3 v3.1.1/go.mod h1:qC1DfmcCTQjl9PBaMa5wSn3x9IPmKxSdcCsxBcDBndM=
|
github.com/pion/stun/v3 v3.1.1/go.mod h1:qC1DfmcCTQjl9PBaMa5wSn3x9IPmKxSdcCsxBcDBndM=
|
||||||
|
github.com/pion/transport/v3 v3.1.1 h1:Tr684+fnnKlhPceU+ICdrw6KKkTms+5qHMgw6bIkYOM=
|
||||||
|
github.com/pion/transport/v3 v3.1.1/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=
|
||||||
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
|
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
|
||||||
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
|
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
|
||||||
github.com/pion/turn/v4 v4.1.4 h1:EU11yMXKIsK43FhcUnjLlrhE4nboHZq+TXBIi3QpcxQ=
|
github.com/pion/turn/v4 v4.1.4 h1:EU11yMXKIsK43FhcUnjLlrhE4nboHZq+TXBIi3QpcxQ=
|
||||||
github.com/pion/turn/v4 v4.1.4/go.mod h1:ES1DXVFKnOhuDkqn9hn5VJlSWmZPaRJLyBXoOeO/BmQ=
|
github.com/pion/turn/v4 v4.1.4/go.mod h1:ES1DXVFKnOhuDkqn9hn5VJlSWmZPaRJLyBXoOeO/BmQ=
|
||||||
github.com/pion/webrtc/v4 v4.2.11 h1:QUX1QZKlNIn4O7U5JxLPGP0sV5RTncZkzu9SPR3jVNU=
|
github.com/pion/webrtc/v4 v4.2.11 h1:QUX1QZKlNIn4O7U5JxLPGP0sV5RTncZkzu9SPR3jVNU=
|
||||||
github.com/pion/webrtc/v4 v4.2.11/go.mod h1:s/rAiyy77GyRFrZMx+Ls6aua26dIBPudH8/ZHYbIRWY=
|
github.com/pion/webrtc/v4 v4.2.11/go.mod h1:s/rAiyy77GyRFrZMx+Ls6aua26dIBPudH8/ZHYbIRWY=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
|
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
|
||||||
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
|
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
|
||||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||||
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
|
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||||
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
|
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4=
|
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
|
||||||
golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -0,0 +1,700 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"runtime/debug"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
"github.com/pion/webrtc/v4"
|
||||||
|
"whitelist-bypass/relay/common"
|
||||||
|
"whitelist-bypass/relay/tunnel"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
tmAPIBase = "https://cloud-api.yandex.ru/telemost_front/v2/telemost"
|
||||||
|
tmOrigin = "https://telemost.yandex.ru"
|
||||||
|
tmPingPeriod = 5 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
var capabilitiesOffer = map[string][]string{
|
||||||
|
"offerAnswerMode": {"SEPARATE"},
|
||||||
|
"initialSubscriberOffer": {"ON_HELLO"},
|
||||||
|
"slotsMode": {"FROM_CONTROLLER"},
|
||||||
|
"simulcastMode": {"DISABLED", "STATIC"},
|
||||||
|
"selfVadStatus": {"FROM_SERVER", "FROM_CLIENT"},
|
||||||
|
"dataChannelSharing": {"TO_RTP"},
|
||||||
|
"videoEncoderConfig": {"NO_CONFIG", "ONLY_INIT_CONFIG", "RUNTIME_CONFIG"},
|
||||||
|
"dataChannelVideoCodec": {"VP8", "UNIQUE_CODEC_FROM_TRACK_DESCRIPTION"},
|
||||||
|
"bandwidthLimitationReason": {"BANDWIDTH_REASON_DISABLED", "BANDWIDTH_REASON_ENABLED"},
|
||||||
|
"sdkDefaultDeviceManagement": {"SDK_DEFAULT_DEVICE_MANAGEMENT_DISABLED", "SDK_DEFAULT_DEVICE_MANAGEMENT_ENABLED"},
|
||||||
|
"joinOrderLayout": {"JOIN_ORDER_LAYOUT_DISABLED", "JOIN_ORDER_LAYOUT_ENABLED"},
|
||||||
|
"pinLayout": {"PIN_LAYOUT_DISABLED"},
|
||||||
|
"sendSelfViewVideoSlot": {"SEND_SELF_VIEW_VIDEO_SLOT_DISABLED", "SEND_SELF_VIEW_VIDEO_SLOT_ENABLED"},
|
||||||
|
"serverLayoutTransition": {"SERVER_LAYOUT_TRANSITION_DISABLED"},
|
||||||
|
"sdkPublisherOptimizeBitrate": {"SDK_PUBLISHER_OPTIMIZE_BITRATE_DISABLED", "SDK_PUBLISHER_OPTIMIZE_BITRATE_FULL", "SDK_PUBLISHER_OPTIMIZE_BITRATE_ONLY_SELF"},
|
||||||
|
"sdkNetworkLostDetection": {"SDK_NETWORK_LOST_DETECTION_DISABLED"},
|
||||||
|
"sdkNetworkPathMonitor": {"SDK_NETWORK_PATH_MONITOR_DISABLED"},
|
||||||
|
"publisherVp9": {"PUBLISH_VP9_DISABLED", "PUBLISH_VP9_ENABLED"},
|
||||||
|
"svcMode": {"SVC_MODE_DISABLED", "SVC_MODE_L3T3", "SVC_MODE_L3T3_KEY"},
|
||||||
|
"subscriberOfferAsyncAck": {"SUBSCRIBER_OFFER_ASYNC_ACK_DISABLED", "SUBSCRIBER_OFFER_ASYNC_ACK_ENABLED"},
|
||||||
|
"androidBluetoothRoutingFix": {"ANDROID_BLUETOOTH_ROUTING_FIX_DISABLED"},
|
||||||
|
"fixedIceCandidatesPoolSize": {"FIXED_ICE_CANDIDATES_POOL_SIZE_DISABLED"},
|
||||||
|
"sdkAndroidTelecomIntegration": {"SDK_ANDROID_TELECOM_INTEGRATION_DISABLED"},
|
||||||
|
"setActiveCodecsMode": {"SET_ACTIVE_CODECS_MODE_DISABLED", "SET_ACTIVE_CODECS_MODE_VIDEO_ONLY"},
|
||||||
|
"subscriberDtlsPassiveMode": {"SUBSCRIBER_DTLS_PASSIVE_MODE_DISABLED", "SUBSCRIBER_DTLS_PASSIVE_MODE_ENABLED"},
|
||||||
|
}
|
||||||
|
|
||||||
|
type ConnInfo struct {
|
||||||
|
ConferenceURI string
|
||||||
|
RoomID string
|
||||||
|
PeerID string
|
||||||
|
Credentials string
|
||||||
|
MediaServerURL string
|
||||||
|
ServiceName string
|
||||||
|
ICEServers []webrtc.ICEServer
|
||||||
|
}
|
||||||
|
|
||||||
|
type Bridge struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
ws *websocket.Conn
|
||||||
|
relay *SFURelay
|
||||||
|
connInfo *ConnInfo
|
||||||
|
config TMConfig
|
||||||
|
cookieStr string
|
||||||
|
pubSeq int
|
||||||
|
subSeq int
|
||||||
|
peers map[string]string
|
||||||
|
readBuf int
|
||||||
|
maxDCBuf uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func tmRequest(method, path string, body interface{}, cookieStr string, cfg TMConfig) ([]byte, int, error) {
|
||||||
|
var bodyReader io.Reader
|
||||||
|
if body != nil {
|
||||||
|
data, _ := json.Marshal(body)
|
||||||
|
bodyReader = strings.NewReader(string(data))
|
||||||
|
}
|
||||||
|
req, err := http.NewRequest(method, tmAPIBase+path, bodyReader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", common.UserAgent)
|
||||||
|
req.Header.Set("Origin", tmOrigin)
|
||||||
|
req.Header.Set("Referer", tmOrigin+"/")
|
||||||
|
req.Header.Set("Cookie", cookieStr)
|
||||||
|
req.Header.Set("Client-Instance-Id", uuid.New().String())
|
||||||
|
req.Header.Set("X-Telemost-Client-Version", cfg.AppVersion)
|
||||||
|
if body != nil {
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
return data, resp.StatusCode, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseICEServersJSON(raw json.RawMessage) []webrtc.ICEServer {
|
||||||
|
var rawIce []struct {
|
||||||
|
URLs []string `json:"urls"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Credential string `json:"credential"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(raw, &rawIce)
|
||||||
|
var out []webrtc.ICEServer
|
||||||
|
for _, s := range rawIce {
|
||||||
|
ice := webrtc.ICEServer{URLs: s.URLs}
|
||||||
|
if s.Username != "" {
|
||||||
|
ice.Username = s.Username
|
||||||
|
ice.Credential = s.Credential
|
||||||
|
}
|
||||||
|
out = append(out, ice)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func getConnection(cookieStr, confURL string, cfg TMConfig) (*ConnInfo, error) {
|
||||||
|
r, status, err := tmRequest("GET",
|
||||||
|
"/conferences/"+confURL+"/connection?next_gen_media_platform_allowed=true&display_name=Headless&waiting_room_supported=true",
|
||||||
|
nil, cookieStr, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("get connection: %w", err)
|
||||||
|
}
|
||||||
|
if status != 200 {
|
||||||
|
return nil, fmt.Errorf("get connection: status %d: %s", status, string(r))
|
||||||
|
}
|
||||||
|
var conn struct {
|
||||||
|
PeerID string `json:"peer_id"`
|
||||||
|
RoomID string `json:"room_id"`
|
||||||
|
Credentials string `json:"credentials"`
|
||||||
|
ClientConfig struct {
|
||||||
|
MediaServerURL string `json:"media_server_url"`
|
||||||
|
ServiceName string `json:"service_name"`
|
||||||
|
ICEServers json.RawMessage `json:"ice_servers"`
|
||||||
|
} `json:"client_configuration"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(r, &conn)
|
||||||
|
if conn.ClientConfig.MediaServerURL == "" {
|
||||||
|
return nil, fmt.Errorf("empty media_server_url: %s", string(r))
|
||||||
|
}
|
||||||
|
return &ConnInfo{
|
||||||
|
RoomID: conn.RoomID,
|
||||||
|
PeerID: conn.PeerID,
|
||||||
|
Credentials: conn.Credentials,
|
||||||
|
MediaServerURL: conn.ClientConfig.MediaServerURL,
|
||||||
|
ServiceName: conn.ClientConfig.ServiceName,
|
||||||
|
ICEServers: parseICEServersJSON(conn.ClientConfig.ICEServers),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func createAndJoinCall(cookieStr string, cfg TMConfig) (*ConnInfo, error) {
|
||||||
|
log.Println("[auth] Creating conference...")
|
||||||
|
r, status, err := tmRequest("POST", "/conferences?next_gen_media_platform_allowed=true",
|
||||||
|
struct{}{}, cookieStr, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("create conference: %w", err)
|
||||||
|
}
|
||||||
|
if status != 200 && status != 201 {
|
||||||
|
return nil, fmt.Errorf("create conference: status %d: %s", status, string(r))
|
||||||
|
}
|
||||||
|
var conf struct {
|
||||||
|
URI string `json:"uri"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(r, &conf)
|
||||||
|
if conf.URI == "" {
|
||||||
|
return nil, fmt.Errorf("empty conference URI: %s", string(r))
|
||||||
|
}
|
||||||
|
log.Printf("[auth] Conference: %s", conf.URI)
|
||||||
|
|
||||||
|
log.Println("[auth] Getting connection...")
|
||||||
|
info, err := getConnection(cookieStr, url.QueryEscape(conf.URI), cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
info.ConferenceURI = conf.URI
|
||||||
|
log.Printf("[auth] peer_id=%s room_id=%s", info.PeerID, info.RoomID)
|
||||||
|
log.Printf("[auth] media_server=%s", info.MediaServerURL)
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) wsSend(msg interface{}) {
|
||||||
|
b.mu.Lock()
|
||||||
|
defer b.mu.Unlock()
|
||||||
|
if b.ws == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, _ := json.Marshal(msg)
|
||||||
|
b.ws.WriteMessage(websocket.TextMessage, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) ack(uid string) {
|
||||||
|
b.wsSend(map[string]interface{}{
|
||||||
|
"uid": uid,
|
||||||
|
"ack": map[string]interface{}{
|
||||||
|
"status": map[string]interface{}{"code": "OK", "description": ""},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) sendHello() {
|
||||||
|
b.wsSend(map[string]interface{}{
|
||||||
|
"uid": uuid.New().String(),
|
||||||
|
"hello": map[string]interface{}{
|
||||||
|
"participantMeta": map[string]interface{}{"name": "Headless", "role": "SPEAKER", "description": "", "sendAudio": false, "sendVideo": true},
|
||||||
|
"participantAttributes": map[string]interface{}{"name": "Headless", "role": "SPEAKER", "description": ""},
|
||||||
|
"sendAudio": false, "sendVideo": true, "sendSharing": false,
|
||||||
|
"participantId": b.connInfo.PeerID, "roomId": b.connInfo.RoomID,
|
||||||
|
"serviceName": b.connInfo.ServiceName, "credentials": b.connInfo.Credentials,
|
||||||
|
"capabilitiesOffer": capabilitiesOffer,
|
||||||
|
"sdkInfo": map[string]interface{}{"implementation": "browser", "version": b.config.SDKVersion, "userAgent": common.UserAgent, "hwConcurrency": 8},
|
||||||
|
"sdkInitializationId": uuid.New().String(),
|
||||||
|
"disablePublisher": false, "disableSubscriber": false, "disableSubscriberAudio": false,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
log.Println("[tm-ws] -> hello")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) sendPubOffer() {
|
||||||
|
offer, err := b.relay.CreatePubOffer()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[tm-ws] pub offer failed: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
audioMid, videoMid := parseMids(offer.SDP)
|
||||||
|
log.Printf("[tm-ws] -> publisherSdpOffer pcSeq=%d", b.pubSeq)
|
||||||
|
|
||||||
|
var tracks []map[string]interface{}
|
||||||
|
if audioMid != "" {
|
||||||
|
tracks = append(tracks, map[string]interface{}{"mid": audioMid, "transceiverMid": audioMid, "kind": "AUDIO", "priority": 0, "label": "", "codecs": map[string]interface{}{}, "groupId": 1, "description": ""})
|
||||||
|
}
|
||||||
|
if videoMid != "" {
|
||||||
|
tracks = append(tracks, map[string]interface{}{"mid": videoMid, "transceiverMid": videoMid, "kind": "VIDEO", "priority": 0, "label": "", "codecs": map[string]interface{}{}, "groupId": 2, "description": ""})
|
||||||
|
}
|
||||||
|
b.wsSend(map[string]interface{}{
|
||||||
|
"uid": uuid.New().String(),
|
||||||
|
"publisherSdpOffer": map[string]interface{}{"pcSeq": b.pubSeq, "sdp": offer.SDP, "tracks": tracks},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) sendICE(cand *webrtc.ICECandidate, target string, pcSeq int) {
|
||||||
|
c := cand.ToJSON()
|
||||||
|
mid := ""
|
||||||
|
if c.SDPMid != nil {
|
||||||
|
mid = *c.SDPMid
|
||||||
|
}
|
||||||
|
var idx uint16
|
||||||
|
if c.SDPMLineIndex != nil {
|
||||||
|
idx = *c.SDPMLineIndex
|
||||||
|
}
|
||||||
|
b.wsSend(map[string]interface{}{
|
||||||
|
"uid": uuid.New().String(),
|
||||||
|
"webrtcIceCandidate": map[string]interface{}{
|
||||||
|
"candidate": c.Candidate, "sdpMid": mid,
|
||||||
|
"usernameFragment": extractUfrag(c.Candidate),
|
||||||
|
"sdpMlineIndex": idx, "target": target, "pcSeq": pcSeq,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) requestVideoSlots() {
|
||||||
|
log.Println("[tm-ws] -> setSlots")
|
||||||
|
b.wsSend(map[string]interface{}{
|
||||||
|
"uid": uuid.New().String(),
|
||||||
|
"setSlots": map[string]interface{}{
|
||||||
|
"slots": []map[string]interface{}{{"width": 320, "height": 240}},
|
||||||
|
"audioSlotsCount": 1, "key": 1,
|
||||||
|
"nLastConfig": map[string]interface{}{"nCount": 1, "showInSubgrid": false},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) handleMessage(raw []byte) {
|
||||||
|
var msg map[string]interface{}
|
||||||
|
if err := json.Unmarshal(raw, &msg); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
uid, _ := msg["uid"].(string)
|
||||||
|
|
||||||
|
if sh, ok := msg["serverHello"]; ok {
|
||||||
|
log.Println("[tm-ws] <- serverHello")
|
||||||
|
if shMap, ok := sh.(map[string]interface{}); ok {
|
||||||
|
b.parseICEServers(shMap)
|
||||||
|
}
|
||||||
|
b.ack(uid)
|
||||||
|
b.initRelay()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if pa, ok := msg["publisherSdpAnswer"]; ok {
|
||||||
|
paMap, _ := pa.(map[string]interface{})
|
||||||
|
sdp, _ := paMap["sdp"].(string)
|
||||||
|
log.Printf("[tm-ws] <- publisherSdpAnswer %d bytes", len(sdp))
|
||||||
|
if err := b.relay.SetPubAnswer(sdp); err != nil {
|
||||||
|
log.Printf("[tm-ws] error: %v", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if so, ok := msg["subscriberSdpOffer"]; ok {
|
||||||
|
soMap, _ := so.(map[string]interface{})
|
||||||
|
sdp, _ := soMap["sdp"].(string)
|
||||||
|
pcSeq, _ := soMap["pcSeq"].(float64)
|
||||||
|
b.subSeq = int(pcSeq)
|
||||||
|
log.Printf("[tm-ws] <- subscriberSdpOffer pcSeq=%d", b.subSeq)
|
||||||
|
b.ack(uid)
|
||||||
|
answer, err := b.relay.SetSubOffer(sdp)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[tm-ws] error: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("[tm-ws] -> subscriberSdpAnswer pcSeq=%d", b.subSeq)
|
||||||
|
b.wsSend(map[string]interface{}{
|
||||||
|
"uid": uuid.New().String(),
|
||||||
|
"subscriberSdpAnswer": map[string]interface{}{"sdp": answer.SDP, "pcSeq": b.subSeq},
|
||||||
|
})
|
||||||
|
b.sendPubOffer()
|
||||||
|
b.requestVideoSlots()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if ic, ok := msg["webrtcIceCandidate"]; ok {
|
||||||
|
icMap, _ := ic.(map[string]interface{})
|
||||||
|
candidate, _ := icMap["candidate"].(string)
|
||||||
|
sdpMid, _ := icMap["sdpMid"].(string)
|
||||||
|
target, _ := icMap["target"].(string)
|
||||||
|
sdpIdx, _ := icMap["sdpMlineIndex"].(float64)
|
||||||
|
idx := uint16(sdpIdx)
|
||||||
|
cand := webrtc.ICECandidateInit{Candidate: candidate, SDPMid: &sdpMid, SDPMLineIndex: &idx}
|
||||||
|
if target == "PUBLISHER" {
|
||||||
|
b.relay.AddPubICECandidate(cand)
|
||||||
|
} else {
|
||||||
|
b.relay.AddSubICECandidate(cand)
|
||||||
|
}
|
||||||
|
b.ack(uid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if ackData, ok := msg["ack"]; ok {
|
||||||
|
if ackMap, ok := ackData.(map[string]interface{}); ok {
|
||||||
|
if status, ok := ackMap["status"].(map[string]interface{}); ok {
|
||||||
|
if code, _ := status["code"].(string); code != "OK" {
|
||||||
|
desc, _ := status["description"].(string)
|
||||||
|
log.Printf("[tm-ws] <- ack error: %s %s", code, desc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if ud, ok := msg["upsertDescription"]; ok {
|
||||||
|
udMap, _ := ud.(map[string]interface{})
|
||||||
|
descs, _ := udMap["description"].([]interface{})
|
||||||
|
for _, d := range descs {
|
||||||
|
dm, _ := d.(map[string]interface{})
|
||||||
|
pid, _ := dm["id"].(string)
|
||||||
|
if pid == "" || pid == b.connInfo.PeerID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
name := ""
|
||||||
|
if meta, ok := dm["meta"].(map[string]interface{}); ok {
|
||||||
|
name, _ = meta["name"].(string)
|
||||||
|
}
|
||||||
|
b.mu.Lock()
|
||||||
|
b.peers[pid] = name
|
||||||
|
b.mu.Unlock()
|
||||||
|
log.Printf("[tm-ws] Participant joined: %s (%s) total=%d", name, pid, len(b.peers))
|
||||||
|
}
|
||||||
|
b.ack(uid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if rd, ok := msg["removeDescription"]; ok {
|
||||||
|
rdMap, _ := rd.(map[string]interface{})
|
||||||
|
ids, _ := rdMap["descriptionId"].([]interface{})
|
||||||
|
for _, id := range ids {
|
||||||
|
pid, _ := id.(string)
|
||||||
|
b.mu.Lock()
|
||||||
|
name := b.peers[pid]
|
||||||
|
delete(b.peers, pid)
|
||||||
|
remaining := len(b.peers)
|
||||||
|
b.mu.Unlock()
|
||||||
|
log.Printf("[tm-ws] Participant left: %s (%s) total=%d", name, pid, remaining)
|
||||||
|
if remaining == 0 {
|
||||||
|
go b.pollAndAdmit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.ack(uid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := msg["notification"]; ok {
|
||||||
|
b.ack(uid)
|
||||||
|
go b.pollAndAdmit()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := msg["participantsChanged"]; ok {
|
||||||
|
b.ack(uid)
|
||||||
|
go b.pollAndAdmit()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if uid != "" {
|
||||||
|
b.ack(uid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) parseICEServers(sh map[string]interface{}) {
|
||||||
|
rtcCfg, ok := sh["rtcConfiguration"].(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
servers, ok := rtcCfg["iceServers"].([]interface{})
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var iceServers []webrtc.ICEServer
|
||||||
|
for _, s := range servers {
|
||||||
|
sm, _ := s.(map[string]interface{})
|
||||||
|
var urls []string
|
||||||
|
if u, ok := sm["urls"].([]interface{}); ok {
|
||||||
|
for _, v := range u {
|
||||||
|
if vs, ok := v.(string); ok {
|
||||||
|
urls = append(urls, vs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ice := webrtc.ICEServer{URLs: urls}
|
||||||
|
if u, ok := sm["username"].(string); ok && u != "" {
|
||||||
|
ice.Username = u
|
||||||
|
ice.Credential, _ = sm["credential"].(string)
|
||||||
|
}
|
||||||
|
iceServers = append(iceServers, ice)
|
||||||
|
}
|
||||||
|
b.connInfo.ICEServers = iceServers
|
||||||
|
log.Printf("[tm-ws] %d ICE servers", len(iceServers))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) kickPeer(peerID string) {
|
||||||
|
confURL := url.QueryEscape(b.connInfo.ConferenceURI)
|
||||||
|
log.Printf("[tm-ws] Kicking %s", peerID)
|
||||||
|
tmRequest("POST", "/conferences/"+confURL+"/commands/kick?peer_id="+url.QueryEscape(peerID)+"&with_ban=false",
|
||||||
|
nil, b.cookieStr, b.config)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) pollAndAdmit() {
|
||||||
|
confURL := url.QueryEscape(b.connInfo.ConferenceURI)
|
||||||
|
r, status, err := tmRequest("GET", "/conferences/"+confURL+"/waiting-rooms/peers", nil, b.cookieStr, b.config)
|
||||||
|
if err != nil || status != 200 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var resp struct {
|
||||||
|
Peers []struct {
|
||||||
|
PeerID string `json:"peer_id"`
|
||||||
|
State struct {
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
} `json:"state"`
|
||||||
|
} `json:"peers"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(r, &resp)
|
||||||
|
if len(resp.Peers) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
b.mu.Lock()
|
||||||
|
toKick := make(map[string]string)
|
||||||
|
for pid, name := range b.peers {
|
||||||
|
toKick[pid] = name
|
||||||
|
}
|
||||||
|
b.mu.Unlock()
|
||||||
|
|
||||||
|
if len(toKick) > 0 {
|
||||||
|
for pid, name := range toKick {
|
||||||
|
log.Printf("[tm-ws] Kicking %s (%s) for new peer", name, pid)
|
||||||
|
b.kickPeer(pid)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, p := range resp.Peers {
|
||||||
|
log.Printf("[tm-ws] Admitting %s (%s)", p.State.DisplayName, p.PeerID)
|
||||||
|
tmRequest("PUT", "/conferences/"+confURL+"/commands/admit?peer_id="+url.QueryEscape(p.PeerID),
|
||||||
|
nil, b.cookieStr, b.config)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) initRelay() {
|
||||||
|
if b.relay != nil {
|
||||||
|
b.relay.Close()
|
||||||
|
}
|
||||||
|
b.pubSeq = 1
|
||||||
|
b.subSeq = 0
|
||||||
|
|
||||||
|
relay := NewSFURelay()
|
||||||
|
relay.readBufSize = b.readBuf
|
||||||
|
relay.maxDCBuf = b.maxDCBuf
|
||||||
|
relay.OnConnected = func(tun *tunnel.VP8DataTunnel) {
|
||||||
|
tunnel.NewRelayBridge(tun, "creator", b.readBuf, log.Printf)
|
||||||
|
fmt.Println("\n TUNNEL CONNECTED\n")
|
||||||
|
}
|
||||||
|
relay.OnPubICE = func(cand *webrtc.ICECandidate) {
|
||||||
|
if cand == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.sendICE(cand, "PUBLISHER", b.pubSeq)
|
||||||
|
}
|
||||||
|
relay.OnSubICE = func(cand *webrtc.ICECandidate) {
|
||||||
|
if cand == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.sendICE(cand, "SUBSCRIBER", b.subSeq)
|
||||||
|
}
|
||||||
|
if err := relay.Init(b.connInfo.ICEServers); err != nil {
|
||||||
|
log.Fatalf("[relay] init failed: %v", err)
|
||||||
|
}
|
||||||
|
b.relay = relay
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bridge) run() {
|
||||||
|
fmt.Println("")
|
||||||
|
fmt.Println(" CALL CREATED")
|
||||||
|
fmt.Println(" join_link:", b.connInfo.ConferenceURI)
|
||||||
|
fmt.Printf(" protocol: sdk %s app %s\n\n", b.config.SDKVersion, b.config.AppVersion)
|
||||||
|
|
||||||
|
wsHeader := http.Header{}
|
||||||
|
wsHeader.Set("User-Agent", common.UserAgent)
|
||||||
|
wsHeader.Set("Origin", tmOrigin)
|
||||||
|
|
||||||
|
for {
|
||||||
|
log.Println("[tm-ws] Connecting...")
|
||||||
|
ws, _, err := websocket.DefaultDialer.Dial(b.connInfo.MediaServerURL, wsHeader)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[tm-ws] Connect failed: %s, retrying in 5s...", common.MaskError(err))
|
||||||
|
time.Sleep(5 * time.Second)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
b.mu.Lock()
|
||||||
|
b.ws = ws
|
||||||
|
b.mu.Unlock()
|
||||||
|
log.Println("[tm-ws] Connected")
|
||||||
|
|
||||||
|
b.sendHello()
|
||||||
|
|
||||||
|
stopPing := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(tmPingPeriod)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-stopPing:
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
b.wsSend(map[string]interface{}{"uid": uuid.New().String(), "ping": map[string]interface{}{}})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
for {
|
||||||
|
_, raw, err := ws.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[tm-ws] Closed: %s", common.MaskError(err))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
b.handleMessage(raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
close(stopPing)
|
||||||
|
b.mu.Lock()
|
||||||
|
b.ws = nil
|
||||||
|
b.mu.Unlock()
|
||||||
|
|
||||||
|
log.Println("[tm-ws] Rejoining in 3s...")
|
||||||
|
time.Sleep(3 * time.Second)
|
||||||
|
|
||||||
|
newConn, err := getConnection(b.cookieStr, url.QueryEscape(b.connInfo.ConferenceURI), b.config)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[rejoin] Failed: %v, retrying in 5s...", err)
|
||||||
|
time.Sleep(5 * time.Second)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
b.connInfo.PeerID = newConn.PeerID
|
||||||
|
b.connInfo.Credentials = newConn.Credentials
|
||||||
|
b.connInfo.MediaServerURL = newConn.MediaServerURL
|
||||||
|
b.connInfo.ICEServers = newConn.ICEServers
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseMids(sdp string) (audioMid, videoMid string) {
|
||||||
|
var media string
|
||||||
|
for _, line := range strings.Split(sdp, "\r\n") {
|
||||||
|
if strings.HasPrefix(line, "m=audio") {
|
||||||
|
media = "audio"
|
||||||
|
} else if strings.HasPrefix(line, "m=video") {
|
||||||
|
media = "video"
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(line, "a=mid:") {
|
||||||
|
mid := strings.TrimPrefix(line, "a=mid:")
|
||||||
|
if media == "audio" && audioMid == "" {
|
||||||
|
audioMid = mid
|
||||||
|
} else if media == "video" && videoMid == "" {
|
||||||
|
videoMid = mid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractUfrag(candidate string) string {
|
||||||
|
parts := strings.Split(candidate, " ")
|
||||||
|
for i, p := range parts {
|
||||||
|
if p == "ufrag" && i+1 < len(parts) {
|
||||||
|
return parts[i+1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
cookiesPath := flag.String("cookies", "", "path to cookies-yandex.json")
|
||||||
|
cookieString := flag.String("cookie-string", "", "raw cookie string")
|
||||||
|
resources := flag.String("resources", "default", "resource mode: default, moderate, unlimited")
|
||||||
|
writeFile := flag.String("write-file", "", "path to file where active call link is appended")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
var readBuf int
|
||||||
|
var maxDCBuf uint64
|
||||||
|
var memLimit int64
|
||||||
|
switch *resources {
|
||||||
|
case "moderate":
|
||||||
|
readBuf = 16384
|
||||||
|
maxDCBuf = 1 << 20
|
||||||
|
memLimit = 64 << 20
|
||||||
|
case "default":
|
||||||
|
readBuf = 32768
|
||||||
|
maxDCBuf = 4 << 20
|
||||||
|
memLimit = 128 << 20
|
||||||
|
case "unlimited":
|
||||||
|
readBuf = common.RTPBufSize
|
||||||
|
maxDCBuf = 8 << 20
|
||||||
|
memLimit = 256 << 20
|
||||||
|
default:
|
||||||
|
log.Fatalf("[config] unknown resources mode: %s", *resources)
|
||||||
|
}
|
||||||
|
if memLimit > 0 {
|
||||||
|
debug.SetMemoryLimit(memLimit)
|
||||||
|
}
|
||||||
|
log.Printf("[config] resources=%s read-buf=%d max-dc-buf=%d mem-limit=%d", *resources, readBuf, maxDCBuf, memLimit)
|
||||||
|
|
||||||
|
var cookieStr string
|
||||||
|
if *cookieString != "" {
|
||||||
|
cookieStr = *cookieString
|
||||||
|
} else if *cookiesPath != "" {
|
||||||
|
cookieStr = common.LoadCookies(*cookiesPath)
|
||||||
|
} else {
|
||||||
|
log.Fatal("Either --cookies or --cookie-string is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("[config] Fetching live config from Telemost bundle...")
|
||||||
|
cfg, err := fetchConfig()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("[config] %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
connInfo, err := createAndJoinCall(cookieStr, cfg)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to create call: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if *writeFile != "" {
|
||||||
|
f, err := os.OpenFile(*writeFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to open write-file: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(f, connInfo.ConferenceURI)
|
||||||
|
f.Close()
|
||||||
|
log.Printf("[config] Wrote call link to %s", *writeFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
bridge := &Bridge{
|
||||||
|
connInfo: connInfo,
|
||||||
|
config: cfg,
|
||||||
|
cookieStr: cookieStr,
|
||||||
|
peers: make(map[string]string),
|
||||||
|
readBuf: readBuf,
|
||||||
|
maxDCBuf: maxDCBuf,
|
||||||
|
}
|
||||||
|
bridge.run()
|
||||||
|
}
|
||||||
@@ -0,0 +1,514 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"math"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pion/rtp"
|
||||||
|
"github.com/pion/rtp/codecs"
|
||||||
|
"github.com/pion/webrtc/v4"
|
||||||
|
"whitelist-bypass/relay/common"
|
||||||
|
"whitelist-bypass/relay/tunnel"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SFURelay struct {
|
||||||
|
pubPC *webrtc.PeerConnection
|
||||||
|
subPC *webrtc.PeerConnection
|
||||||
|
pubRemoteSet bool
|
||||||
|
subRemoteSet bool
|
||||||
|
pubPending []webrtc.ICECandidateInit
|
||||||
|
subPending []webrtc.ICECandidateInit
|
||||||
|
mu sync.Mutex
|
||||||
|
|
||||||
|
sampleTrack *webrtc.TrackLocalStaticSample
|
||||||
|
tun *tunnel.VP8DataTunnel
|
||||||
|
dc *webrtc.DataChannel
|
||||||
|
inDC *webrtc.DataChannel
|
||||||
|
OnConnected func(*tunnel.VP8DataTunnel)
|
||||||
|
OnPubICE func(*webrtc.ICECandidate)
|
||||||
|
OnSubICE func(*webrtc.ICECandidate)
|
||||||
|
|
||||||
|
readBufSize int
|
||||||
|
maxDCBuf uint64
|
||||||
|
|
||||||
|
// DC relay
|
||||||
|
conns sync.Map
|
||||||
|
dcMu sync.Mutex
|
||||||
|
sendMsgId uint32
|
||||||
|
recvBufs sync.Map
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSFURelay() *SFURelay {
|
||||||
|
return &SFURelay{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) Init(iceServers []webrtc.ICEServer) error {
|
||||||
|
config := webrtc.Configuration{ICEServers: iceServers}
|
||||||
|
|
||||||
|
pubPC, err := webrtc.NewPeerConnection(config)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
r.pubPC = pubPC
|
||||||
|
|
||||||
|
sampleTrack, _ := webrtc.NewTrackLocalStaticSample(
|
||||||
|
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8},
|
||||||
|
"video", "tunnel-video",
|
||||||
|
)
|
||||||
|
r.sampleTrack = sampleTrack
|
||||||
|
|
||||||
|
audioTrack, _ := webrtc.NewTrackLocalStaticRTP(
|
||||||
|
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus},
|
||||||
|
"audio", "tunnel-audio",
|
||||||
|
)
|
||||||
|
pubPC.AddTransceiverFromTrack(audioTrack, webrtc.RTPTransceiverInit{Direction: webrtc.RTPTransceiverDirectionSendonly})
|
||||||
|
pubPC.AddTransceiverFromTrack(sampleTrack, webrtc.RTPTransceiverInit{Direction: webrtc.RTPTransceiverDirectionSendonly})
|
||||||
|
r.createSharingDC()
|
||||||
|
|
||||||
|
pubPC.OnICECandidate(func(cand *webrtc.ICECandidate) {
|
||||||
|
if cand == nil || r.OnPubICE == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.OnPubICE(cand)
|
||||||
|
})
|
||||||
|
|
||||||
|
pubPC.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
|
||||||
|
log.Printf("[pub] connection state: %s", state.String())
|
||||||
|
})
|
||||||
|
|
||||||
|
subPC, err := webrtc.NewPeerConnection(config)
|
||||||
|
if err != nil {
|
||||||
|
pubPC.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
r.subPC = subPC
|
||||||
|
|
||||||
|
subPC.OnICECandidate(func(cand *webrtc.ICECandidate) {
|
||||||
|
if cand == nil || r.OnSubICE == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.OnSubICE(cand)
|
||||||
|
})
|
||||||
|
|
||||||
|
subPC.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
|
||||||
|
log.Printf("[sub] connection state: %s", state.String())
|
||||||
|
})
|
||||||
|
|
||||||
|
subPC.OnDataChannel(func(inDC *webrtc.DataChannel) {
|
||||||
|
log.Printf("[sub] Incoming DC: label=%s id=%d state=%s", inDC.Label(), inDC.ID(), inDC.ReadyState().String())
|
||||||
|
if inDC.Label() == "sharing" {
|
||||||
|
log.Println("[sub] Joiner sharing DC found")
|
||||||
|
r.inDC = inDC
|
||||||
|
inDC.OnMessage(func(msg webrtc.DataChannelMessage) {
|
||||||
|
if msg.IsString {
|
||||||
|
s := string(msg.Data)
|
||||||
|
if s == "tunnel:ping" {
|
||||||
|
if r.dc != nil && r.dc.ReadyState() == webrtc.DataChannelStateOpen {
|
||||||
|
r.dc.SendText("tunnel:pong")
|
||||||
|
log.Println("[relay] === MODE: DC ===")
|
||||||
|
fmt.Println("\n TUNNEL CONNECTED\n")
|
||||||
|
} else {
|
||||||
|
log.Println("[sub] tunnel:ping received but pub DC not ready")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !msg.IsString && len(msg.Data) >= 6 {
|
||||||
|
r.handleChunk(msg.Data)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
inDC.OnOpen(func() {
|
||||||
|
log.Println("[sub] Joiner sharing DC open")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
subPC.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
|
||||||
|
log.Printf("[sub] remote track: %s", track.Codec().MimeType)
|
||||||
|
go r.readTrack(track)
|
||||||
|
})
|
||||||
|
|
||||||
|
log.Printf("[relay] pub+sub PCs created (%d ICE servers)", len(iceServers))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) CreatePubOffer() (webrtc.SessionDescription, error) {
|
||||||
|
offer, err := r.pubPC.CreateOffer(nil)
|
||||||
|
if err != nil {
|
||||||
|
return offer, err
|
||||||
|
}
|
||||||
|
r.pubPC.SetLocalDescription(offer)
|
||||||
|
return offer, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) SetPubAnswer(sdp string) error {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
err := r.pubPC.SetRemoteDescription(webrtc.SessionDescription{
|
||||||
|
Type: webrtc.SDPTypeAnswer, SDP: sdp,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
r.pubRemoteSet = true
|
||||||
|
for _, cand := range r.pubPending {
|
||||||
|
r.pubPC.AddICECandidate(cand)
|
||||||
|
}
|
||||||
|
r.pubPending = nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) SetSubOffer(sdp string) (webrtc.SessionDescription, error) {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
err := r.subPC.SetRemoteDescription(webrtc.SessionDescription{
|
||||||
|
Type: webrtc.SDPTypeOffer, SDP: sdp,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return webrtc.SessionDescription{}, err
|
||||||
|
}
|
||||||
|
r.subRemoteSet = true
|
||||||
|
for _, cand := range r.subPending {
|
||||||
|
r.subPC.AddICECandidate(cand)
|
||||||
|
}
|
||||||
|
r.subPending = nil
|
||||||
|
|
||||||
|
answer, err := r.subPC.CreateAnswer(nil)
|
||||||
|
if err != nil {
|
||||||
|
return answer, err
|
||||||
|
}
|
||||||
|
r.subPC.SetLocalDescription(answer)
|
||||||
|
return answer, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) AddPubICECandidate(cand webrtc.ICECandidateInit) {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
if !r.pubRemoteSet {
|
||||||
|
r.pubPending = append(r.pubPending, cand)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.pubPC.AddICECandidate(cand)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) AddSubICECandidate(cand webrtc.ICECandidateInit) {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
if !r.subRemoteSet {
|
||||||
|
r.subPending = append(r.subPending, cand)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.subPC.AddICECandidate(cand)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) createSharingDC() {
|
||||||
|
log.Println("[pub] Creating sharing DataChannel")
|
||||||
|
ordered := true
|
||||||
|
dc, err := r.pubPC.CreateDataChannel("sharing", &webrtc.DataChannelInit{Ordered: &ordered})
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[pub] Failed to create sharing DC: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.dc = dc
|
||||||
|
dc.OnOpen(func() {
|
||||||
|
log.Println("[pub] Sharing DC open")
|
||||||
|
})
|
||||||
|
dc.OnClose(func() {
|
||||||
|
log.Println("[pub] Sharing DC closed")
|
||||||
|
})
|
||||||
|
dc.OnMessage(func(msg webrtc.DataChannelMessage) {
|
||||||
|
if msg.IsString {
|
||||||
|
s := string(msg.Data)
|
||||||
|
if s == "tunnel:ping" {
|
||||||
|
dc.SendText("tunnel:pong")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if s == "tunnel:pong" {
|
||||||
|
log.Println("[pub] Received tunnel:pong on outbound DC")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) CreatePubRenegotiate() (webrtc.SessionDescription, error) {
|
||||||
|
offer, err := r.pubPC.CreateOffer(&webrtc.OfferOptions{ICERestart: false})
|
||||||
|
if err != nil {
|
||||||
|
return offer, err
|
||||||
|
}
|
||||||
|
err = r.pubPC.SetLocalDescription(offer)
|
||||||
|
if err != nil {
|
||||||
|
return offer, err
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
r.pubRemoteSet = false
|
||||||
|
r.pubPending = nil
|
||||||
|
r.mu.Unlock()
|
||||||
|
return offer, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const chunkSize = 994
|
||||||
|
|
||||||
|
type chunkBuf struct {
|
||||||
|
chunks [][]byte
|
||||||
|
count int
|
||||||
|
size int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) handleChunk(data []byte) {
|
||||||
|
id := uint16(data[0])<<8 | uint16(data[1])
|
||||||
|
idx := int(uint16(data[2])<<8 | uint16(data[3]))
|
||||||
|
total := int(uint16(data[4])<<8 | uint16(data[5]))
|
||||||
|
payload := data[6:]
|
||||||
|
|
||||||
|
if total == 1 {
|
||||||
|
cp := make([]byte, len(payload))
|
||||||
|
copy(cp, payload)
|
||||||
|
r.handleDCMessage(cp)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
key := id
|
||||||
|
val, _ := r.recvBufs.LoadOrStore(key, &chunkBuf{chunks: make([][]byte, total)})
|
||||||
|
buf := val.(*chunkBuf)
|
||||||
|
if idx < len(buf.chunks) && buf.chunks[idx] == nil {
|
||||||
|
cp := make([]byte, len(payload))
|
||||||
|
copy(cp, payload)
|
||||||
|
buf.chunks[idx] = cp
|
||||||
|
buf.count++
|
||||||
|
buf.size += len(cp)
|
||||||
|
}
|
||||||
|
if buf.count == total {
|
||||||
|
r.recvBufs.Delete(key)
|
||||||
|
out := make([]byte, 0, buf.size)
|
||||||
|
for _, c := range buf.chunks {
|
||||||
|
out = append(out, c...)
|
||||||
|
}
|
||||||
|
r.handleDCMessage(out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) sendChunked(data []byte) {
|
||||||
|
r.dcMu.Lock()
|
||||||
|
dc := r.dc
|
||||||
|
r.dcMu.Unlock()
|
||||||
|
if dc == nil || dc.ReadyState() != webrtc.DataChannelStateOpen {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.maxDCBuf > 0 {
|
||||||
|
for dc.BufferedAmount() > r.maxDCBuf {
|
||||||
|
time.Sleep(5 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
total := int(math.Ceil(float64(len(data)) / float64(chunkSize)))
|
||||||
|
if total == 0 {
|
||||||
|
total = 1
|
||||||
|
}
|
||||||
|
id := uint16(atomic.AddUint32(&r.sendMsgId, 1)) & 0xFFFF
|
||||||
|
for i := 0; i < total; i++ {
|
||||||
|
start := i * chunkSize
|
||||||
|
end := start + chunkSize
|
||||||
|
if end > len(data) {
|
||||||
|
end = len(data)
|
||||||
|
}
|
||||||
|
p := data[start:end]
|
||||||
|
f := make([]byte, 6+len(p))
|
||||||
|
f[0] = byte(id >> 8)
|
||||||
|
f[1] = byte(id & 0xFF)
|
||||||
|
f[2] = byte(i >> 8)
|
||||||
|
f[3] = byte(i & 0xFF)
|
||||||
|
f[4] = byte(total >> 8)
|
||||||
|
f[5] = byte(total & 0xFF)
|
||||||
|
copy(f[6:], p)
|
||||||
|
dc.Send(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) handleDCMessage(data []byte) {
|
||||||
|
if len(data) < 5 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
connID := binary.BigEndian.Uint32(data[0:4])
|
||||||
|
mt := data[4]
|
||||||
|
payload := data[5:]
|
||||||
|
|
||||||
|
switch mt {
|
||||||
|
case tunnel.MsgConnect:
|
||||||
|
go r.connectTCP(connID, string(payload))
|
||||||
|
case tunnel.MsgUDP:
|
||||||
|
go r.handleUDP(connID, payload)
|
||||||
|
case tunnel.MsgData:
|
||||||
|
val, ok := r.conns.Load(connID)
|
||||||
|
if ok {
|
||||||
|
val.(net.Conn).Write(payload)
|
||||||
|
}
|
||||||
|
case tunnel.MsgClose:
|
||||||
|
val, ok := r.conns.LoadAndDelete(connID)
|
||||||
|
if ok {
|
||||||
|
val.(net.Conn).Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) sendDCFrame(connID uint32, mt byte, payload []byte) {
|
||||||
|
buf := make([]byte, 5+len(payload))
|
||||||
|
binary.BigEndian.PutUint32(buf[0:4], connID)
|
||||||
|
buf[4] = mt
|
||||||
|
copy(buf[5:], payload)
|
||||||
|
r.sendChunked(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) connectTCP(connID uint32, addr string) {
|
||||||
|
log.Printf("[dc] CONNECT %d -> %s", connID, common.MaskAddr(addr))
|
||||||
|
conn, err := net.DialTimeout("tcp", addr, 10*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("[dc] CONNECT %d failed: %s", connID, common.MaskError(err))
|
||||||
|
r.sendDCFrame(connID, tunnel.MsgConnectErr, []byte(common.MaskError(err)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.conns.Store(connID, conn)
|
||||||
|
r.sendDCFrame(connID, tunnel.MsgConnectOK, nil)
|
||||||
|
log.Printf("[dc] CONNECTED %d -> %s", connID, common.MaskAddr(addr))
|
||||||
|
|
||||||
|
buf := make([]byte, chunkSize-5)
|
||||||
|
for {
|
||||||
|
n, err := conn.Read(buf)
|
||||||
|
if n > 0 {
|
||||||
|
r.sendDCFrame(connID, tunnel.MsgData, buf[:n])
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if err != io.EOF {
|
||||||
|
log.Printf("[dc] conn %d read error: %s", connID, common.MaskError(err))
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r.sendDCFrame(connID, tunnel.MsgClose, nil)
|
||||||
|
r.conns.Delete(connID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) handleUDP(connID uint32, payload []byte) {
|
||||||
|
if len(payload) < 2 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
addrLen := int(payload[0])
|
||||||
|
if addrLen == 0 || len(payload) < 1+addrLen {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
addr := string(payload[1 : 1+addrLen])
|
||||||
|
data := payload[1+addrLen:]
|
||||||
|
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn, err := net.DialUDP("udp", nil, udpAddr)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||||
|
conn.Write(data)
|
||||||
|
resp := make([]byte, common.UDPBufSize)
|
||||||
|
n, err := conn.Read(resp)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.sendDCFrame(connID, tunnel.MsgUDPReply, resp[:n])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) closeAllConns() {
|
||||||
|
r.conns.Range(func(key, val any) bool {
|
||||||
|
if c, ok := val.(net.Conn); ok {
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
r.conns.Delete(key)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) Close() {
|
||||||
|
r.closeAllConns()
|
||||||
|
if r.tun != nil {
|
||||||
|
r.tun.Stop()
|
||||||
|
r.tun = nil
|
||||||
|
}
|
||||||
|
if r.pubPC != nil {
|
||||||
|
r.pubPC.Close()
|
||||||
|
r.pubPC = nil
|
||||||
|
}
|
||||||
|
if r.subPC != nil {
|
||||||
|
r.subPC.Close()
|
||||||
|
r.subPC = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SFURelay) readTrack(track *webrtc.TrackRemote) {
|
||||||
|
if track.Codec().MimeType != webrtc.MimeTypeVP8 {
|
||||||
|
buf := make([]byte, common.UDPBufSize)
|
||||||
|
for {
|
||||||
|
if _, _, err := track.Read(buf); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var vp8Pkt codecs.VP8Packet
|
||||||
|
var frameBuf []byte
|
||||||
|
var dataCount, recvCount int
|
||||||
|
bufSz := r.readBufSize
|
||||||
|
if bufSz <= 0 {
|
||||||
|
bufSz = common.RTPBufSize
|
||||||
|
}
|
||||||
|
buf := make([]byte, bufSz)
|
||||||
|
for {
|
||||||
|
n, _, err := track.Read(buf)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pkt := &rtp.Packet{}
|
||||||
|
if pkt.Unmarshal(buf[:n]) != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
vp8Payload, err := vp8Pkt.Unmarshal(pkt.Payload)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if vp8Pkt.S == 1 {
|
||||||
|
frameBuf = frameBuf[:0]
|
||||||
|
}
|
||||||
|
frameBuf = append(frameBuf, vp8Payload...)
|
||||||
|
if pkt.Marker {
|
||||||
|
recvCount++
|
||||||
|
if recvCount <= 3 || recvCount%25 == 0 {
|
||||||
|
if len(frameBuf) > 0 {
|
||||||
|
log.Printf("[video] recv frame #%d %d bytes, first=0x%02x", recvCount, len(frameBuf), frameBuf[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data := tunnel.ExtractDataFromPayload(frameBuf)
|
||||||
|
if data != nil {
|
||||||
|
if r.tun == nil {
|
||||||
|
log.Println("[relay] === MODE: VIDEO ===")
|
||||||
|
r.tun = tunnel.NewVP8DataTunnel(r.sampleTrack, log.Printf)
|
||||||
|
r.tun.Start(25)
|
||||||
|
if r.OnConnected != nil {
|
||||||
|
r.OnConnected(r.tun)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dataCount++
|
||||||
|
if dataCount <= 5 || dataCount%100 == 0 {
|
||||||
|
log.Printf("[video] TUNNEL DATA #%d: %d bytes", dataCount, len(data))
|
||||||
|
}
|
||||||
|
if r.tun.OnData != nil {
|
||||||
|
r.tun.OnData(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/binary"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func encodeFrame(connID uint32, msgType byte, payload []byte) []byte {
|
|
||||||
buf := make([]byte, 4+5+len(payload))
|
|
||||||
binary.BigEndian.PutUint32(buf[0:4], uint32(5+len(payload)))
|
|
||||||
binary.BigEndian.PutUint32(buf[4:8], connID)
|
|
||||||
buf[8] = msgType
|
|
||||||
copy(buf[9:], payload)
|
|
||||||
return buf
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeFrames(data []byte, cb func(connID uint32, msgType byte, payload []byte)) {
|
|
||||||
for len(data) >= 4 {
|
|
||||||
frameLen := int(binary.BigEndian.Uint32(data[0:4]))
|
|
||||||
if frameLen < 5 || 4+frameLen > len(data) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
connID := binary.BigEndian.Uint32(data[4:8])
|
|
||||||
msgType := data[8]
|
|
||||||
payload := data[9 : 4+frameLen]
|
|
||||||
cb(connID, msgType, payload)
|
|
||||||
data = data[4+frameLen:]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type RelayBridge struct {
|
|
||||||
tunnel *VP8DataTunnel
|
|
||||||
conns sync.Map
|
|
||||||
nextID atomic.Uint32
|
|
||||||
logFn func(string, ...any)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRelayBridge(tunnel *VP8DataTunnel, mode string, logFn func(string, ...any)) *RelayBridge {
|
|
||||||
rb := &RelayBridge{
|
|
||||||
tunnel: tunnel,
|
|
||||||
logFn: logFn,
|
|
||||||
}
|
|
||||||
tunnel.onData = rb.handleTunnelData
|
|
||||||
tunnel.onClose = rb.closeAll
|
|
||||||
return rb
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rb *RelayBridge) closeAll() {
|
|
||||||
rb.logFn("relay: closing all connections")
|
|
||||||
rb.conns.Range(func(key, value any) bool {
|
|
||||||
if c, ok := value.(net.Conn); ok {
|
|
||||||
c.Close()
|
|
||||||
}
|
|
||||||
rb.conns.Delete(key)
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rb *RelayBridge) send(connID uint32, msgType byte, payload []byte) {
|
|
||||||
frame := encodeFrame(connID, msgType, payload)
|
|
||||||
rb.tunnel.SendData(frame)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rb *RelayBridge) handleTunnelData(data []byte) {
|
|
||||||
decodeFrames(data, rb.handleCreatorMessage)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rb *RelayBridge) handleCreatorMessage(connID uint32, msgType byte, payload []byte) {
|
|
||||||
switch msgType {
|
|
||||||
case msgConnect:
|
|
||||||
go rb.connectTCP(connID, string(payload))
|
|
||||||
case msgUDP:
|
|
||||||
go rb.handleUDP(connID, payload)
|
|
||||||
case msgData:
|
|
||||||
val, ok := rb.conns.Load(connID)
|
|
||||||
if ok {
|
|
||||||
val.(net.Conn).Write(payload)
|
|
||||||
}
|
|
||||||
case msgClose:
|
|
||||||
val, ok := rb.conns.LoadAndDelete(connID)
|
|
||||||
if ok {
|
|
||||||
val.(net.Conn).Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rb *RelayBridge) handleUDP(connID uint32, payload []byte) {
|
|
||||||
if len(payload) < 2 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
addrLen := int(payload[0])
|
|
||||||
if addrLen == 0 || len(payload) < 1+addrLen {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
addr := string(payload[1 : 1+addrLen])
|
|
||||||
data := payload[1+addrLen:]
|
|
||||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
conn, err := net.DialUDP("udp", nil, udpAddr)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
conn.SetDeadline(time.Now().Add(5 * time.Second))
|
|
||||||
conn.Write(data)
|
|
||||||
buf := make([]byte, udpBufSize)
|
|
||||||
n, err := conn.Read(buf)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
rb.send(connID, msgUDPReply, buf[:n])
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rb *RelayBridge) connectTCP(connID uint32, addr string) {
|
|
||||||
rb.logFn("relay: CONNECT %d -> %s", connID, maskAddr(addr))
|
|
||||||
conn, err := net.DialTimeout("tcp", addr, 10e9)
|
|
||||||
if err != nil {
|
|
||||||
rb.logFn("relay: CONNECT %d failed: %v", connID, err)
|
|
||||||
rb.send(connID, msgConnectErr, []byte(err.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
rb.conns.Store(connID, conn)
|
|
||||||
rb.send(connID, msgConnectOK, nil)
|
|
||||||
rb.logFn("relay: CONNECTED %d -> %s", connID, maskAddr(addr))
|
|
||||||
|
|
||||||
buf := make([]byte, vp8RelayBufSize)
|
|
||||||
for {
|
|
||||||
n, err := conn.Read(buf)
|
|
||||||
if n > 0 {
|
|
||||||
rb.send(connID, msgData, buf[:n])
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
if err != io.EOF {
|
|
||||||
rb.logFn("relay: conn %d read error: %v", connID, err)
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
rb.send(connID, msgClose, nil)
|
|
||||||
rb.conns.Delete(connID)
|
|
||||||
}
|
|
||||||
File renamed without changes.
@@ -2,7 +2,14 @@ module headless-creator
|
|||||||
|
|
||||||
go 1.26.1
|
go 1.26.1
|
||||||
|
|
||||||
require github.com/gorilla/websocket v1.5.3
|
require (
|
||||||
|
github.com/gorilla/websocket v1.5.3
|
||||||
|
github.com/pion/rtp v1.10.1
|
||||||
|
github.com/pion/webrtc/v4 v4.2.11
|
||||||
|
whitelist-bypass/relay v0.0.0
|
||||||
|
)
|
||||||
|
|
||||||
|
replace whitelist-bypass/relay => ../../relay
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
@@ -14,17 +21,15 @@ require (
|
|||||||
github.com/pion/mdns/v2 v2.1.0 // indirect
|
github.com/pion/mdns/v2 v2.1.0 // indirect
|
||||||
github.com/pion/randutil v0.1.0 // indirect
|
github.com/pion/randutil v0.1.0 // indirect
|
||||||
github.com/pion/rtcp v1.2.16 // indirect
|
github.com/pion/rtcp v1.2.16 // indirect
|
||||||
github.com/pion/rtp v1.10.1 // indirect
|
|
||||||
github.com/pion/sctp v1.9.4 // indirect
|
github.com/pion/sctp v1.9.4 // indirect
|
||||||
github.com/pion/sdp/v3 v3.0.18 // indirect
|
github.com/pion/sdp/v3 v3.0.18 // indirect
|
||||||
github.com/pion/srtp/v3 v3.0.10 // indirect
|
github.com/pion/srtp/v3 v3.0.10 // indirect
|
||||||
github.com/pion/stun/v3 v3.1.1 // indirect
|
github.com/pion/stun/v3 v3.1.1 // indirect
|
||||||
github.com/pion/transport/v4 v4.0.1 // indirect
|
github.com/pion/transport/v4 v4.0.1 // indirect
|
||||||
github.com/pion/turn/v4 v4.1.4 // indirect
|
github.com/pion/turn/v4 v4.1.4 // indirect
|
||||||
github.com/pion/webrtc/v4 v4.2.11 // indirect
|
|
||||||
github.com/wlynxg/anet v0.0.5 // indirect
|
github.com/wlynxg/anet v0.0.5 // indirect
|
||||||
golang.org/x/crypto v0.48.0 // indirect
|
golang.org/x/crypto v0.49.0 // indirect
|
||||||
golang.org/x/net v0.50.0 // indirect
|
golang.org/x/net v0.52.0 // indirect
|
||||||
golang.org/x/sys v0.41.0 // indirect
|
golang.org/x/sys v0.42.0 // indirect
|
||||||
golang.org/x/time v0.10.0 // indirect
|
golang.org/x/time v0.11.0 // indirect
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
|
github.com/pion/datachannel v1.6.0 h1:XecBlj+cvsxhAMZWFfFcPyUaDZtd7IJvrXqlXD/53i0=
|
||||||
|
github.com/pion/datachannel v1.6.0/go.mod h1:ur+wzYF8mWdC+Mkis5Thosk+u/VOL287apDNEbFpsIk=
|
||||||
|
github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc=
|
||||||
|
github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo=
|
||||||
|
github.com/pion/ice/v4 v4.2.2 h1:dQJzzcgTFHDYyV3BoCfjPeX+JEtr58BWPi4PGyo6Vjg=
|
||||||
|
github.com/pion/ice/v4 v4.2.2/go.mod h1:2quLV1S5v1tAx3VvAJaH//KGitRXvo4RKlX6D3tnN+c=
|
||||||
|
github.com/pion/interceptor v0.1.44 h1:sNlZwM8dWXU9JQAkJh8xrarC0Etn8Oolcniukmuy0/I=
|
||||||
|
github.com/pion/interceptor v0.1.44/go.mod h1:4atVlBkcgXuUP+ykQF0qOCGU2j7pQzX2ofvPRFsY5RY=
|
||||||
|
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
|
||||||
|
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
|
||||||
|
github.com/pion/mdns/v2 v2.1.0 h1:3IJ9+Xio6tWYjhN6WwuY142P/1jA0D5ERaIqawg/fOY=
|
||||||
|
github.com/pion/mdns/v2 v2.1.0/go.mod h1:pcez23GdynwcfRU1977qKU0mDxSeucttSHbCSfFOd9A=
|
||||||
|
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
|
||||||
|
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
|
||||||
|
github.com/pion/rtcp v1.2.16 h1:fk1B1dNW4hsI78XUCljZJlC4kZOPk67mNRuQ0fcEkSo=
|
||||||
|
github.com/pion/rtcp v1.2.16/go.mod h1:/as7VKfYbs5NIb4h6muQ35kQF/J0ZVNz2Z3xKoCBYOo=
|
||||||
|
github.com/pion/rtp v1.10.1 h1:xP1prZcCTUuhO2c83XtxyOHJteISg6o8iPsE2acaMtA=
|
||||||
|
github.com/pion/rtp v1.10.1/go.mod h1:rF5nS1GqbR7H/TCpKwylzeq6yDM+MM6k+On5EgeThEM=
|
||||||
|
github.com/pion/sctp v1.9.4 h1:cMxEu0F5tbP4qH07bKf1Zjf4rUih9LIo0qQt424e258=
|
||||||
|
github.com/pion/sctp v1.9.4/go.mod h1:N20Dq6LY+JvJDAh9VVh1JELngb2rQ8dPgds5yBWiPgw=
|
||||||
|
github.com/pion/sdp/v3 v3.0.18 h1:l0bAXazKHpepazVdp+tPYnrsy9dfh7ZbT8DxesH5ZnI=
|
||||||
|
github.com/pion/sdp/v3 v3.0.18/go.mod h1:ZREGo6A9ZygQ9XkqAj5xYCQtQpif0i6Pa81HOiAdqQ8=
|
||||||
|
github.com/pion/srtp/v3 v3.0.10 h1:tFirkpBb3XccP5VEXLi50GqXhv5SKPxqrdlhDCJlZrQ=
|
||||||
|
github.com/pion/srtp/v3 v3.0.10/go.mod h1:3mOTIB0cq9qlbn59V4ozvv9ClW/BSEbRp4cY0VtaR7M=
|
||||||
|
github.com/pion/stun/v3 v3.1.1 h1:CkQxveJ4xGQjulGSROXbXq94TAWu8gIX2dT+ePhUkqw=
|
||||||
|
github.com/pion/stun/v3 v3.1.1/go.mod h1:qC1DfmcCTQjl9PBaMa5wSn3x9IPmKxSdcCsxBcDBndM=
|
||||||
|
github.com/pion/transport/v3 v3.1.1 h1:Tr684+fnnKlhPceU+ICdrw6KKkTms+5qHMgw6bIkYOM=
|
||||||
|
github.com/pion/transport/v3 v3.1.1/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=
|
||||||
|
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
|
||||||
|
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
|
||||||
|
github.com/pion/turn/v4 v4.1.4 h1:EU11yMXKIsK43FhcUnjLlrhE4nboHZq+TXBIi3QpcxQ=
|
||||||
|
github.com/pion/turn/v4 v4.1.4/go.mod h1:ES1DXVFKnOhuDkqn9hn5VJlSWmZPaRJLyBXoOeO/BmQ=
|
||||||
|
github.com/pion/webrtc/v4 v4.2.11 h1:QUX1QZKlNIn4O7U5JxLPGP0sV5RTncZkzu9SPR3jVNU=
|
||||||
|
github.com/pion/webrtc/v4 v4.2.11/go.mod h1:s/rAiyy77GyRFrZMx+Ls6aua26dIBPudH8/ZHYbIRWY=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
|
||||||
|
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
|
||||||
|
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||||
|
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||||
|
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||||
|
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||||
|
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||||
|
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
|
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
|
||||||
|
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -16,17 +16,12 @@ import (
|
|||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
"github.com/pion/webrtc/v4"
|
"github.com/pion/webrtc/v4"
|
||||||
|
"whitelist-bypass/relay/common"
|
||||||
|
"whitelist-bypass/relay/tunnel"
|
||||||
)
|
)
|
||||||
|
|
||||||
const userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
|
||||||
|
|
||||||
const TopologyDirect = "DIRECT"
|
const TopologyDirect = "DIRECT"
|
||||||
|
|
||||||
type Cookie struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Value string `json:"value"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type CallInfo struct {
|
type CallInfo struct {
|
||||||
CallID string
|
CallID string
|
||||||
JoinLink string
|
JoinLink string
|
||||||
@@ -47,20 +42,47 @@ type StunServer struct {
|
|||||||
URLs []string `json:"urls"`
|
URLs []string `json:"urls"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadCookies(path string) string {
|
type VKTokenResponse struct {
|
||||||
data, err := os.ReadFile(path)
|
Data struct {
|
||||||
if err != nil {
|
AccessToken string `json:"access_token"`
|
||||||
log.Fatalf("Cannot read cookies: %v", err)
|
} `json:"data"`
|
||||||
}
|
}
|
||||||
var cookies []Cookie
|
|
||||||
if err := json.Unmarshal(data, &cookies); err != nil {
|
type CallSettingsResponse struct {
|
||||||
log.Fatalf("Cannot parse cookies: %v", err)
|
Response struct {
|
||||||
|
Settings struct {
|
||||||
|
PublicKey string `json:"public_key"`
|
||||||
|
} `json:"settings"`
|
||||||
|
} `json:"response"`
|
||||||
}
|
}
|
||||||
parts := make([]string, len(cookies))
|
|
||||||
for i, c := range cookies {
|
type CallTokenResponse struct {
|
||||||
parts[i] = c.Name + "=" + c.Value
|
Response struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
APIBaseURL string `json:"api_base_url"`
|
||||||
|
} `json:"response"`
|
||||||
}
|
}
|
||||||
return strings.Join(parts, "; ")
|
|
||||||
|
type OKAuthResponse struct {
|
||||||
|
SessionKey string `json:"session_key"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type JoinResponse struct {
|
||||||
|
Endpoint string `json:"endpoint"`
|
||||||
|
TurnServer TurnServer `json:"turn_server"`
|
||||||
|
StunServer StunServer `json:"stun_server"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Bridge struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
vkWs *websocket.Conn
|
||||||
|
vkSeq int
|
||||||
|
iceServers []webrtc.ICEServer
|
||||||
|
topology string
|
||||||
|
peers map[int64]struct{}
|
||||||
|
relay Relay
|
||||||
|
newRelay func() Relay
|
||||||
|
p2p *P2PHandler
|
||||||
}
|
}
|
||||||
|
|
||||||
func httpPost(endpoint string, form url.Values, extraHeaders map[string]string) ([]byte, error) {
|
func httpPost(endpoint string, form url.Values, extraHeaders map[string]string) ([]byte, error) {
|
||||||
@@ -70,7 +92,7 @@ func httpPost(endpoint string, form url.Values, extraHeaders map[string]string)
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
req.Header.Set("User-Agent", userAgent)
|
req.Header.Set("User-Agent", common.UserAgent)
|
||||||
req.Header.Set("Origin", "https://vk.com")
|
req.Header.Set("Origin", "https://vk.com")
|
||||||
req.Header.Set("Referer", "https://vk.com/")
|
req.Header.Set("Referer", "https://vk.com/")
|
||||||
for k, v := range extraHeaders {
|
for k, v := range extraHeaders {
|
||||||
@@ -89,7 +111,7 @@ func httpGet(endpoint string) ([]byte, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req.Header.Set("User-Agent", userAgent)
|
req.Header.Set("User-Agent", common.UserAgent)
|
||||||
resp, err := http.DefaultClient.Do(req)
|
resp, err := http.DefaultClient.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -101,6 +123,89 @@ func httpGet(endpoint string) ([]byte, error) {
|
|||||||
return io.ReadAll(resp.Body)
|
return io.ReadAll(resp.Body)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func authAndJoin(cookieStr, okJoinLink string, cfg VKConfig) (*JoinResponse, error) {
|
||||||
|
auth := func(bearer string) map[string]string {
|
||||||
|
return map[string]string{"Authorization": "Bearer " + bearer}
|
||||||
|
}
|
||||||
|
|
||||||
|
r, err := httpPost("https://login.vk.com/?act=web_token",
|
||||||
|
url.Values{"version": {"1"}, "app_id": {cfg.AppID}},
|
||||||
|
map[string]string{"Cookie": cookieStr})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("web_token: %w", err)
|
||||||
|
}
|
||||||
|
var tok VKTokenResponse
|
||||||
|
json.Unmarshal(r, &tok)
|
||||||
|
if tok.Data.AccessToken == "" {
|
||||||
|
return nil, fmt.Errorf("empty VK token, response: %s", string(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
r, err = httpPost("https://api.vk.com/method/calls.getSettings",
|
||||||
|
url.Values{"v": {cfg.APIVersion}}, auth(tok.Data.AccessToken))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("calls.getSettings: %w", err)
|
||||||
|
}
|
||||||
|
var settings CallSettingsResponse
|
||||||
|
json.Unmarshal(r, &settings)
|
||||||
|
appKey := settings.Response.Settings.PublicKey
|
||||||
|
if appKey == "" {
|
||||||
|
return nil, fmt.Errorf("empty public_key, response: %s", string(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
r, err = httpPost("https://api.vk.com/method/messages.getCallToken",
|
||||||
|
url.Values{"v": {cfg.APIVersion}, "env": {"production"}}, auth(tok.Data.AccessToken))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("messages.getCallToken: %w", err)
|
||||||
|
}
|
||||||
|
var callToken CallTokenResponse
|
||||||
|
json.Unmarshal(r, &callToken)
|
||||||
|
if callToken.Response.Token == "" {
|
||||||
|
return nil, fmt.Errorf("empty call token, response: %s", string(r))
|
||||||
|
}
|
||||||
|
if callToken.Response.APIBaseURL == "" {
|
||||||
|
return nil, fmt.Errorf("empty api_base_url, response: %s", string(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
apiBaseURL := strings.TrimRight(callToken.Response.APIBaseURL, "/")
|
||||||
|
if !strings.HasSuffix(apiBaseURL, "/fb.do") {
|
||||||
|
apiBaseURL += "/fb.do"
|
||||||
|
}
|
||||||
|
sd, _ := json.Marshal(map[string]interface{}{
|
||||||
|
"device_id": "headless-go-1", "client_version": cfg.AppVersion,
|
||||||
|
"client_type": "SDK_JS", "auth_token": callToken.Response.Token, "version": 3,
|
||||||
|
})
|
||||||
|
r, err = httpPost(apiBaseURL, url.Values{
|
||||||
|
"method": {"auth.anonymLogin"}, "application_key": {appKey},
|
||||||
|
"format": {"json"}, "session_data": {string(sd)},
|
||||||
|
}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("auth.anonymLogin: %w", err)
|
||||||
|
}
|
||||||
|
var okAuth OKAuthResponse
|
||||||
|
json.Unmarshal(r, &okAuth)
|
||||||
|
if okAuth.SessionKey == "" {
|
||||||
|
return nil, fmt.Errorf("empty session_key, response: %s", string(r))
|
||||||
|
}
|
||||||
|
|
||||||
|
ms, _ := json.Marshal(map[string]bool{
|
||||||
|
"isAudioEnabled": false, "isVideoEnabled": true, "isScreenSharingEnabled": false,
|
||||||
|
})
|
||||||
|
r, err = httpPost(apiBaseURL, url.Values{
|
||||||
|
"method": {"vchat.joinConversationByLink"}, "session_key": {okAuth.SessionKey},
|
||||||
|
"application_key": {appKey}, "format": {"json"}, "joinLink": {okJoinLink},
|
||||||
|
"isVideo": {"true"}, "isAudio": {"false"}, "mediaSettings": {string(ms)},
|
||||||
|
}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("vchat.joinConversationByLink: %w", err)
|
||||||
|
}
|
||||||
|
var joinResp JoinResponse
|
||||||
|
json.Unmarshal(r, &joinResp)
|
||||||
|
if joinResp.Endpoint == "" {
|
||||||
|
return nil, fmt.Errorf("empty WS endpoint, response: %s", string(r))
|
||||||
|
}
|
||||||
|
return &joinResp, nil
|
||||||
|
}
|
||||||
|
|
||||||
func createAndJoinCall(cookieStr, peerId string, cfg VKConfig) (*CallInfo, error) {
|
func createAndJoinCall(cookieStr, peerId string, cfg VKConfig) (*CallInfo, error) {
|
||||||
if cfg.AppID == "" || cfg.APIVersion == "" {
|
if cfg.AppID == "" || cfg.APIVersion == "" {
|
||||||
return nil, fmt.Errorf("config incomplete: app_id=%q api=%q", cfg.AppID, cfg.APIVersion)
|
return nil, fmt.Errorf("config incomplete: app_id=%q api=%q", cfg.AppID, cfg.APIVersion)
|
||||||
@@ -117,41 +222,13 @@ func createAndJoinCall(cookieStr, peerId string, cfg VKConfig) (*CallInfo, error
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("web_token: %w", err)
|
return nil, fmt.Errorf("web_token: %w", err)
|
||||||
}
|
}
|
||||||
var tok struct {
|
var tok VKTokenResponse
|
||||||
Data struct {
|
|
||||||
AccessToken string `json:"access_token"`
|
|
||||||
} `json:"data"`
|
|
||||||
}
|
|
||||||
json.Unmarshal(r, &tok)
|
json.Unmarshal(r, &tok)
|
||||||
vkToken := tok.Data.AccessToken
|
vkToken := tok.Data.AccessToken
|
||||||
if vkToken == "" {
|
if vkToken == "" {
|
||||||
return nil, fmt.Errorf("empty VK token, response: %s", string(r))
|
return nil, fmt.Errorf("empty VK token, response: %s", string(r))
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Println("[auth] Getting call settings...")
|
|
||||||
r, err = httpPost("https://api.vk.com/method/calls.getSettings",
|
|
||||||
url.Values{"v": {cfg.APIVersion}}, auth(vkToken))
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("calls.getSettings: %w", err)
|
|
||||||
}
|
|
||||||
var settings struct {
|
|
||||||
Response struct {
|
|
||||||
Settings struct {
|
|
||||||
PublicKey string `json:"public_key"`
|
|
||||||
IsDev bool `json:"is_dev"`
|
|
||||||
} `json:"settings"`
|
|
||||||
} `json:"response"`
|
|
||||||
}
|
|
||||||
json.Unmarshal(r, &settings)
|
|
||||||
appKey := settings.Response.Settings.PublicKey
|
|
||||||
if appKey == "" {
|
|
||||||
return nil, fmt.Errorf("empty public_key, response: %s", string(r))
|
|
||||||
}
|
|
||||||
env := "production"
|
|
||||||
if settings.Response.Settings.IsDev {
|
|
||||||
env = "development"
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("[auth] Creating call peer_id=%s...", peerId)
|
log.Printf("[auth] Creating call peer_id=%s...", peerId)
|
||||||
r, err = httpPost("https://api.vk.com/method/calls.start",
|
r, err = httpPost("https://api.vk.com/method/calls.start",
|
||||||
url.Values{"v": {cfg.APIVersion}, "peer_id": {peerId}}, auth(vkToken))
|
url.Values{"v": {cfg.APIVersion}, "peer_id": {peerId}}, auth(vkToken))
|
||||||
@@ -179,91 +256,19 @@ func createAndJoinCall(cookieStr, peerId string, cfg VKConfig) (*CallInfo, error
|
|||||||
log.Printf("[auth] call_id: %s", c.CallID)
|
log.Printf("[auth] call_id: %s", c.CallID)
|
||||||
log.Printf("[auth] join_link: %s", c.JoinLink)
|
log.Printf("[auth] join_link: %s", c.JoinLink)
|
||||||
|
|
||||||
log.Println("[auth] Getting call token...")
|
|
||||||
r, err = httpPost("https://api.vk.com/method/messages.getCallToken",
|
|
||||||
url.Values{"v": {cfg.APIVersion}, "env": {env}}, auth(vkToken))
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("messages.getCallToken: %w", err)
|
|
||||||
}
|
|
||||||
var ct struct {
|
|
||||||
Response struct {
|
|
||||||
Token string `json:"token"`
|
|
||||||
APIBaseURL string `json:"api_base_url"`
|
|
||||||
} `json:"response"`
|
|
||||||
}
|
|
||||||
json.Unmarshal(r, &ct)
|
|
||||||
if ct.Response.Token == "" {
|
|
||||||
return nil, fmt.Errorf("empty call token, response: %s", string(r))
|
|
||||||
}
|
|
||||||
if ct.Response.APIBaseURL == "" {
|
|
||||||
return nil, fmt.Errorf("empty api_base_url, response: %s", string(r))
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[auth] OK.ru auth...")
|
|
||||||
apiBaseURL := strings.TrimRight(ct.Response.APIBaseURL, "/")
|
|
||||||
if !strings.HasSuffix(apiBaseURL, "/fb.do") {
|
|
||||||
apiBaseURL += "/fb.do"
|
|
||||||
}
|
|
||||||
sd, _ := json.Marshal(map[string]interface{}{
|
|
||||||
"device_id": "headless-go-1", "client_version": cfg.AppVersion,
|
|
||||||
"client_type": "SDK_JS", "auth_token": ct.Response.Token, "version": 3,
|
|
||||||
})
|
|
||||||
r, err = httpPost(apiBaseURL, url.Values{
|
|
||||||
"method": {"auth.anonymLogin"}, "application_key": {appKey},
|
|
||||||
"format": {"json"}, "session_data": {string(sd)},
|
|
||||||
}, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("auth.anonymLogin: %w", err)
|
|
||||||
}
|
|
||||||
var okAuth struct {
|
|
||||||
SessionKey string `json:"session_key"`
|
|
||||||
}
|
|
||||||
json.Unmarshal(r, &okAuth)
|
|
||||||
if okAuth.SessionKey == "" {
|
|
||||||
return nil, fmt.Errorf("empty session_key, response: %s", string(r))
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[auth] Joining conversation...")
|
log.Println("[auth] Joining conversation...")
|
||||||
ms, _ := json.Marshal(map[string]bool{
|
joinResp, err := authAndJoin(cookieStr, c.OKJoinLink, cfg)
|
||||||
"isAudioEnabled": false, "isVideoEnabled": true, "isScreenSharingEnabled": false,
|
|
||||||
})
|
|
||||||
r, err = httpPost(apiBaseURL, url.Values{
|
|
||||||
"method": {"vchat.joinConversationByLink"}, "session_key": {okAuth.SessionKey},
|
|
||||||
"application_key": {appKey}, "format": {"json"}, "joinLink": {c.OKJoinLink},
|
|
||||||
"isVideo": {"true"}, "isAudio": {"false"}, "mediaSettings": {string(ms)},
|
|
||||||
}, nil)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("vchat.joinConversationByLink: %w", err)
|
return nil, err
|
||||||
}
|
|
||||||
var jr struct {
|
|
||||||
Endpoint string `json:"endpoint"`
|
|
||||||
TurnServer TurnServer `json:"turn_server"`
|
|
||||||
StunServer StunServer `json:"stun_server"`
|
|
||||||
}
|
|
||||||
json.Unmarshal(r, &jr)
|
|
||||||
if jr.Endpoint == "" {
|
|
||||||
return nil, fmt.Errorf("empty WS endpoint, response: %s", string(r))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &CallInfo{
|
return &CallInfo{
|
||||||
CallID: c.CallID, JoinLink: c.JoinLink, ShortLink: c.ShortCredentials.LinkWithPassword,
|
CallID: c.CallID, JoinLink: c.JoinLink, ShortLink: c.ShortCredentials.LinkWithPassword,
|
||||||
OKJoinLink: c.OKJoinLink, TurnServer: jr.TurnServer, StunServer: jr.StunServer,
|
OKJoinLink: c.OKJoinLink, TurnServer: joinResp.TurnServer, StunServer: joinResp.StunServer,
|
||||||
WSEndpoint: jr.Endpoint,
|
WSEndpoint: joinResp.Endpoint,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type Bridge struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
vkWs *websocket.Conn
|
|
||||||
vkSeq int
|
|
||||||
iceServers []webrtc.ICEServer
|
|
||||||
topology string
|
|
||||||
peers map[int64]struct{}
|
|
||||||
relay Relay
|
|
||||||
newRelay func() Relay
|
|
||||||
p2p *P2PHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bridge) vkSend(command string, extra map[string]interface{}) {
|
func (b *Bridge) vkSend(command string, extra map[string]interface{}) {
|
||||||
b.mu.Lock()
|
b.mu.Lock()
|
||||||
defer b.mu.Unlock()
|
defer b.mu.Unlock()
|
||||||
@@ -359,6 +364,15 @@ func (b *Bridge) handleVKMessage(raw []byte) {
|
|||||||
log.Println("[vk-ws] Participant hung up")
|
log.Println("[vk-ws] Participant hung up")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case "closed-conversation":
|
||||||
|
reason, _ := msg["reason"].(string)
|
||||||
|
log.Printf("[vk-ws] Conversation closed: %s", reason)
|
||||||
|
b.mu.Lock()
|
||||||
|
if b.vkWs != nil {
|
||||||
|
b.vkWs.Close()
|
||||||
|
}
|
||||||
|
b.mu.Unlock()
|
||||||
|
|
||||||
default:
|
default:
|
||||||
snippet, _ := json.Marshal(msg)
|
snippet, _ := json.Marshal(msg)
|
||||||
if len(snippet) > 1000 {
|
if len(snippet) > 1000 {
|
||||||
@@ -399,9 +413,9 @@ func buildICEServers(callInfo *CallInfo) []webrtc.ICEServer {
|
|||||||
|
|
||||||
func (b *Bridge) connectVKWs(wsURL string) error {
|
func (b *Bridge) connectVKWs(wsURL string) error {
|
||||||
vkHeader := http.Header{}
|
vkHeader := http.Header{}
|
||||||
vkHeader.Set("User-Agent", userAgent)
|
vkHeader.Set("User-Agent", common.UserAgent)
|
||||||
vkHeader.Set("Origin", "https://vk.com")
|
vkHeader.Set("Origin", "https://vk.com")
|
||||||
vkDialer := websocket.Dialer{WriteBufferSize: rtpBufSize}
|
vkDialer := websocket.Dialer{WriteBufferSize: common.RTPBufSize}
|
||||||
vkWs, _, err := vkDialer.Dial(wsURL, vkHeader)
|
vkWs, _, err := vkDialer.Dial(wsURL, vkHeader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -431,14 +445,16 @@ func (b *Bridge) readLoop() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if string(msg) == "ping" {
|
if string(msg) == "ping" {
|
||||||
|
b.mu.Lock()
|
||||||
b.vkWs.WriteMessage(websocket.TextMessage, []byte("pong"))
|
b.vkWs.WriteMessage(websocket.TextMessage, []byte("pong"))
|
||||||
|
b.mu.Unlock()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
b.handleVKMessage(msg)
|
b.handleVKMessage(msg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bridge) run(callInfo *CallInfo, cfg VKConfig) {
|
func (b *Bridge) run(callInfo *CallInfo, cookieStr string, cfg VKConfig) {
|
||||||
fmt.Println("")
|
fmt.Println("")
|
||||||
fmt.Println(" CALL CREATED")
|
fmt.Println(" CALL CREATED")
|
||||||
fmt.Println(" join_link:", callInfo.JoinLink)
|
fmt.Println(" join_link:", callInfo.JoinLink)
|
||||||
@@ -449,14 +465,16 @@ func (b *Bridge) run(callInfo *CallInfo, cfg VKConfig) {
|
|||||||
fmt.Printf(" protocol: v%s sdk %s\n\n", cfg.ProtocolVersion, cfg.SDKVersion)
|
fmt.Printf(" protocol: v%s sdk %s\n\n", cfg.ProtocolVersion, cfg.SDKVersion)
|
||||||
|
|
||||||
b.iceServers = buildICEServers(callInfo)
|
b.iceServers = buildICEServers(callInfo)
|
||||||
|
wsEndpoint := callInfo.WSEndpoint
|
||||||
|
|
||||||
wsURL := callInfo.WSEndpoint +
|
makeWSURL := func(ep string) string {
|
||||||
|
return ep +
|
||||||
"&platform=WEB" +
|
"&platform=WEB" +
|
||||||
"&appVersion=" + cfg.AppVersion +
|
"&appVersion=" + cfg.AppVersion +
|
||||||
"&version=" + cfg.ProtocolVersion +
|
"&version=" + cfg.ProtocolVersion +
|
||||||
"&device=browser&capabilities=0&clientType=VK&tgt=join"
|
"&device=browser&capabilities=0&clientType=VK&tgt=join"
|
||||||
|
}
|
||||||
|
|
||||||
// Keepalive goroutine
|
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
time.Sleep(15 * time.Second)
|
time.Sleep(15 * time.Second)
|
||||||
@@ -464,7 +482,9 @@ func (b *Bridge) run(callInfo *CallInfo, cfg VKConfig) {
|
|||||||
ws := b.vkWs
|
ws := b.vkWs
|
||||||
b.mu.Unlock()
|
b.mu.Unlock()
|
||||||
if ws != nil {
|
if ws != nil {
|
||||||
|
b.mu.Lock()
|
||||||
ws.WriteMessage(websocket.PingMessage, nil)
|
ws.WriteMessage(websocket.PingMessage, nil)
|
||||||
|
b.mu.Unlock()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
@@ -473,8 +493,8 @@ func (b *Bridge) run(callInfo *CallInfo, cfg VKConfig) {
|
|||||||
b.initRelay()
|
b.initRelay()
|
||||||
|
|
||||||
log.Println("[vk-ws] Connecting...")
|
log.Println("[vk-ws] Connecting...")
|
||||||
if err := b.connectVKWs(wsURL); err != nil {
|
if err := b.connectVKWs(makeWSURL(wsEndpoint)); err != nil {
|
||||||
log.Printf("[vk-ws] Connect failed: %v, retrying in 5s...", err)
|
log.Printf("[vk-ws] Connect failed: %s, retrying in 5s...", common.MaskError(err))
|
||||||
time.Sleep(5 * time.Second)
|
time.Sleep(5 * time.Second)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -489,14 +509,25 @@ func (b *Bridge) run(callInfo *CallInfo, cfg VKConfig) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
err := b.readLoop()
|
err := b.readLoop()
|
||||||
log.Printf("[vk-ws] Closed: %v", err)
|
log.Printf("[vk-ws] Closed: %s", common.MaskError(err))
|
||||||
|
|
||||||
b.mu.Lock()
|
b.mu.Lock()
|
||||||
b.vkWs = nil
|
b.vkWs = nil
|
||||||
b.mu.Unlock()
|
b.mu.Unlock()
|
||||||
|
|
||||||
log.Println("[vk-ws] Reconnecting in 3s...")
|
log.Println("[vk-ws] Rejoining in 3s...")
|
||||||
time.Sleep(3 * time.Second)
|
time.Sleep(3 * time.Second)
|
||||||
|
|
||||||
|
joinResp, rerr := authAndJoin(cookieStr, callInfo.OKJoinLink, cfg)
|
||||||
|
if rerr != nil {
|
||||||
|
log.Printf("[rejoin] Failed: %v, retrying in 5s...", rerr)
|
||||||
|
time.Sleep(5 * time.Second)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
wsEndpoint = joinResp.Endpoint
|
||||||
|
callInfo.TurnServer = joinResp.TurnServer
|
||||||
|
callInfo.StunServer = joinResp.StunServer
|
||||||
|
b.iceServers = buildICEServers(callInfo)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -505,6 +536,7 @@ func main() {
|
|||||||
cookieString := flag.String("cookie-string", "", "raw cookie string (name=val; name=val)")
|
cookieString := flag.String("cookie-string", "", "raw cookie string (name=val; name=val)")
|
||||||
peerId := flag.String("peer-id", "", "VK peer_id for the call")
|
peerId := flag.String("peer-id", "", "VK peer_id for the call")
|
||||||
resources := flag.String("resources", "default", "resource mode: default, moderate, unlimited")
|
resources := flag.String("resources", "default", "resource mode: default, moderate, unlimited")
|
||||||
|
writeFile := flag.String("write-file", "", "path to file where active call link is appended")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
var readBuf int
|
var readBuf int
|
||||||
@@ -520,7 +552,7 @@ func main() {
|
|||||||
maxDCBuf = 4 * 1024 * 1024
|
maxDCBuf = 4 * 1024 * 1024
|
||||||
memLimit = 128 * 1024 * 1024
|
memLimit = 128 * 1024 * 1024
|
||||||
case "unlimited":
|
case "unlimited":
|
||||||
readBuf = rtpBufSize
|
readBuf = common.RTPBufSize
|
||||||
maxDCBuf = 8 * 1024 * 1024
|
maxDCBuf = 8 * 1024 * 1024
|
||||||
memLimit = 256 * 1024 * 1024
|
memLimit = 256 * 1024 * 1024
|
||||||
default:
|
default:
|
||||||
@@ -535,7 +567,7 @@ func main() {
|
|||||||
if *cookieString != "" {
|
if *cookieString != "" {
|
||||||
cookieStr = *cookieString
|
cookieStr = *cookieString
|
||||||
} else if *cookiesPath != "" {
|
} else if *cookiesPath != "" {
|
||||||
cookieStr = loadCookies(*cookiesPath)
|
cookieStr = common.LoadCookies(*cookiesPath)
|
||||||
} else {
|
} else {
|
||||||
log.Fatal("Either --cookies or --cookie-string is required")
|
log.Fatal("Either --cookies or --cookie-string is required")
|
||||||
}
|
}
|
||||||
@@ -551,15 +583,25 @@ func main() {
|
|||||||
log.Fatalf("Failed to create call: %v", err)
|
log.Fatalf("Failed to create call: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if *writeFile != "" {
|
||||||
|
f, err := os.OpenFile(*writeFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to open write-file: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(f, callInfo.JoinLink)
|
||||||
|
f.Close()
|
||||||
|
log.Printf("[config] Wrote call link to %s", *writeFile)
|
||||||
|
}
|
||||||
|
|
||||||
bridge := &Bridge{}
|
bridge := &Bridge{}
|
||||||
bridge.newRelay = func() Relay {
|
bridge.newRelay = func() Relay {
|
||||||
ur := NewTunnelRelay()
|
ur := NewTunnelRelay()
|
||||||
ur.readBufSize = readBuf
|
ur.readBufSize = readBuf
|
||||||
ur.maxDCBuf = maxDCBuf
|
ur.maxDCBuf = maxDCBuf
|
||||||
ur.OnConnected = func(tunnel *VP8DataTunnel) {
|
ur.OnConnected = func(tun *tunnel.VP8DataTunnel) {
|
||||||
NewRelayBridge(tunnel, "creator", log.Printf)
|
tunnel.NewRelayBridge(tun, "creator", readBuf, log.Printf)
|
||||||
}
|
}
|
||||||
return ur
|
return ur
|
||||||
}
|
}
|
||||||
bridge.run(callInfo, cfg)
|
bridge.run(callInfo, cookieStr, cfg)
|
||||||
}
|
}
|
||||||
File renamed without changes.
@@ -0,0 +1,14 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "github.com/pion/webrtc/v4"
|
||||||
|
|
||||||
|
type Relay interface {
|
||||||
|
Init(iceServers []webrtc.ICEServer) error
|
||||||
|
CreateOffer() (webrtc.SessionDescription, error)
|
||||||
|
CreateAnswer() (webrtc.SessionDescription, error)
|
||||||
|
SetRemoteDescription(sdpType webrtc.SDPType, sdp string) error
|
||||||
|
AddICECandidate(candidate webrtc.ICECandidateInit) error
|
||||||
|
OnICECandidate(fn func(*webrtc.ICECandidate))
|
||||||
|
OnConnectionStateChange(fn func(webrtc.PeerConnectionState))
|
||||||
|
Close()
|
||||||
|
}
|
||||||
@@ -11,6 +11,8 @@ import (
|
|||||||
"github.com/pion/rtp"
|
"github.com/pion/rtp"
|
||||||
"github.com/pion/rtp/codecs"
|
"github.com/pion/rtp/codecs"
|
||||||
"github.com/pion/webrtc/v4"
|
"github.com/pion/webrtc/v4"
|
||||||
|
"whitelist-bypass/relay/common"
|
||||||
|
"whitelist-bypass/relay/tunnel"
|
||||||
)
|
)
|
||||||
|
|
||||||
type dcConn struct {
|
type dcConn struct {
|
||||||
@@ -30,8 +32,8 @@ type TunnelRelay struct {
|
|||||||
conns sync.Map
|
conns sync.Map
|
||||||
|
|
||||||
sampleTrack *webrtc.TrackLocalStaticSample
|
sampleTrack *webrtc.TrackLocalStaticSample
|
||||||
tunnel *VP8DataTunnel
|
tun *tunnel.VP8DataTunnel
|
||||||
OnConnected func(*VP8DataTunnel)
|
OnConnected func(*tunnel.VP8DataTunnel)
|
||||||
|
|
||||||
readBufSize int
|
readBufSize int
|
||||||
maxDCBuf uint64
|
maxDCBuf uint64
|
||||||
@@ -131,10 +133,10 @@ func (u *TunnelRelay) Init(iceServers []webrtc.ICEServer) error {
|
|||||||
u.modeOnce.Do(func() {
|
u.modeOnce.Do(func() {
|
||||||
u.mode = "video"
|
u.mode = "video"
|
||||||
log.Println("[relay] === MODE: VIDEO ===")
|
log.Println("[relay] === MODE: VIDEO ===")
|
||||||
u.tunnel = NewVP8DataTunnel(sampleTrack, log.Printf)
|
u.tun = tunnel.NewVP8DataTunnel(sampleTrack, log.Printf)
|
||||||
u.tunnel.Start(25)
|
u.tun.Start(25)
|
||||||
if u.OnConnected != nil {
|
if u.OnConnected != nil {
|
||||||
u.OnConnected(u.tunnel)
|
u.OnConnected(u.tun)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
go u.readTrack(track)
|
go u.readTrack(track)
|
||||||
@@ -193,9 +195,9 @@ func (u *TunnelRelay) OnConnectionStateChange(fn func(webrtc.PeerConnectionState
|
|||||||
|
|
||||||
func (u *TunnelRelay) Close() {
|
func (u *TunnelRelay) Close() {
|
||||||
u.closeAllConns()
|
u.closeAllConns()
|
||||||
if u.tunnel != nil {
|
if u.tun != nil {
|
||||||
u.tunnel.Stop()
|
u.tun.Stop()
|
||||||
u.tunnel = nil
|
u.tun = nil
|
||||||
}
|
}
|
||||||
u.dcMu.Lock()
|
u.dcMu.Lock()
|
||||||
u.dc = nil
|
u.dc = nil
|
||||||
@@ -222,11 +224,11 @@ func (u *TunnelRelay) handleDCMessage(data []byte) {
|
|||||||
payload := data[5:]
|
payload := data[5:]
|
||||||
|
|
||||||
switch mt {
|
switch mt {
|
||||||
case msgConnect:
|
case tunnel.MsgConnect:
|
||||||
go u.connectTCP(connID, string(payload))
|
go u.connectTCP(connID, string(payload))
|
||||||
case msgUDP:
|
case tunnel.MsgUDP:
|
||||||
go u.handleUDP(connID, payload)
|
go u.handleUDP(connID, payload)
|
||||||
case msgData:
|
case tunnel.MsgData:
|
||||||
val, ok := u.conns.Load(connID)
|
val, ok := u.conns.Load(connID)
|
||||||
if ok {
|
if ok {
|
||||||
dc := val.(*dcConn)
|
dc := val.(*dcConn)
|
||||||
@@ -238,7 +240,7 @@ func (u *TunnelRelay) handleDCMessage(data []byte) {
|
|||||||
log.Printf("[dc] conn %d write queue full, dropping %d bytes", connID, len(payload))
|
log.Printf("[dc] conn %d write queue full, dropping %d bytes", connID, len(payload))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case msgClose:
|
case tunnel.MsgClose:
|
||||||
val, ok := u.conns.LoadAndDelete(connID)
|
val, ok := u.conns.LoadAndDelete(connID)
|
||||||
if ok {
|
if ok {
|
||||||
dc := val.(*dcConn)
|
dc := val.(*dcConn)
|
||||||
@@ -261,17 +263,17 @@ func (u *TunnelRelay) sendDCFrame(connID uint32, mt byte, payload []byte) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (u *TunnelRelay) connectTCP(connID uint32, addr string) {
|
func (u *TunnelRelay) connectTCP(connID uint32, addr string) {
|
||||||
log.Printf("[dc] CONNECT %d -> %s", connID, maskAddr(addr))
|
log.Printf("[dc] CONNECT %d -> %s", connID, common.MaskAddr(addr))
|
||||||
conn, err := net.DialTimeout("tcp", addr, 10*time.Second)
|
conn, err := net.DialTimeout("tcp", addr, 10*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[dc] CONNECT %d failed: %v", connID, err)
|
log.Printf("[dc] CONNECT %d failed: %s", connID, common.MaskError(err))
|
||||||
u.sendDCFrame(connID, msgConnectErr, []byte(err.Error()))
|
u.sendDCFrame(connID, tunnel.MsgConnectErr, []byte(common.MaskError(err)))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
dc := &dcConn{conn: conn, ch: make(chan []byte, 256)}
|
dc := &dcConn{conn: conn, ch: make(chan []byte, 256)}
|
||||||
u.conns.Store(connID, dc)
|
u.conns.Store(connID, dc)
|
||||||
u.sendDCFrame(connID, msgConnectOK, nil)
|
u.sendDCFrame(connID, tunnel.MsgConnectOK, nil)
|
||||||
log.Printf("[dc] CONNECTED %d -> %s", connID, maskAddr(addr))
|
log.Printf("[dc] CONNECTED %d -> %s", connID, common.MaskAddr(addr))
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
for data := range dc.ch {
|
for data := range dc.ch {
|
||||||
@@ -282,7 +284,7 @@ func (u *TunnelRelay) connectTCP(connID uint32, addr string) {
|
|||||||
|
|
||||||
bufSz := u.readBufSize
|
bufSz := u.readBufSize
|
||||||
if bufSz <= 0 {
|
if bufSz <= 0 {
|
||||||
bufSz = rtpBufSize
|
bufSz = common.RTPBufSize
|
||||||
}
|
}
|
||||||
buf := make([]byte, bufSz)
|
buf := make([]byte, bufSz)
|
||||||
sent := 0
|
sent := 0
|
||||||
@@ -299,18 +301,18 @@ func (u *TunnelRelay) connectTCP(connID uint32, addr string) {
|
|||||||
}
|
}
|
||||||
n, err := conn.Read(buf)
|
n, err := conn.Read(buf)
|
||||||
if n > 0 {
|
if n > 0 {
|
||||||
u.sendDCFrame(connID, msgData, buf[:n])
|
u.sendDCFrame(connID, tunnel.MsgData, buf[:n])
|
||||||
sent += n
|
sent += n
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err != io.EOF {
|
if err != io.EOF {
|
||||||
log.Printf("[dc] conn %d read error: %v", connID, err)
|
log.Printf("[dc] conn %d read error: %s", connID, common.MaskError(err))
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Printf("[dc] conn %d closed, sent %d bytes", connID, sent)
|
log.Printf("[dc] conn %d closed, sent %d bytes", connID, sent)
|
||||||
u.sendDCFrame(connID, msgClose, nil)
|
u.sendDCFrame(connID, tunnel.MsgClose, nil)
|
||||||
u.conns.Delete(connID)
|
u.conns.Delete(connID)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -335,12 +337,12 @@ func (u *TunnelRelay) handleUDP(connID uint32, payload []byte) {
|
|||||||
defer conn.Close()
|
defer conn.Close()
|
||||||
conn.SetDeadline(time.Now().Add(5 * time.Second))
|
conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||||
conn.Write(data)
|
conn.Write(data)
|
||||||
resp := make([]byte, udpBufSize)
|
resp := make([]byte, common.UDPBufSize)
|
||||||
n, err := conn.Read(resp)
|
n, err := conn.Read(resp)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
u.sendDCFrame(connID, msgUDPReply, resp[:n])
|
u.sendDCFrame(connID, tunnel.MsgUDPReply, resp[:n])
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *TunnelRelay) closeAllConns() {
|
func (u *TunnelRelay) closeAllConns() {
|
||||||
@@ -354,7 +356,7 @@ func (u *TunnelRelay) closeAllConns() {
|
|||||||
|
|
||||||
func (u *TunnelRelay) readTrack(track *webrtc.TrackRemote) {
|
func (u *TunnelRelay) readTrack(track *webrtc.TrackRemote) {
|
||||||
if track.Codec().MimeType != webrtc.MimeTypeVP8 {
|
if track.Codec().MimeType != webrtc.MimeTypeVP8 {
|
||||||
buf := make([]byte, udpBufSize)
|
buf := make([]byte, common.UDPBufSize)
|
||||||
for {
|
for {
|
||||||
if _, _, err := track.Read(buf); err != nil {
|
if _, _, err := track.Read(buf); err != nil {
|
||||||
return
|
return
|
||||||
@@ -365,7 +367,7 @@ func (u *TunnelRelay) readTrack(track *webrtc.TrackRemote) {
|
|||||||
var vp8Pkt codecs.VP8Packet
|
var vp8Pkt codecs.VP8Packet
|
||||||
var frameBuf []byte
|
var frameBuf []byte
|
||||||
var dataCount, recvCount int
|
var dataCount, recvCount int
|
||||||
buf := make([]byte, rtpBufSize)
|
buf := make([]byte, common.RTPBufSize)
|
||||||
for {
|
for {
|
||||||
n, _, err := track.Read(buf)
|
n, _, err := track.Read(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -390,14 +392,14 @@ func (u *TunnelRelay) readTrack(track *webrtc.TrackRemote) {
|
|||||||
log.Printf("[video] recv frame #%d %d bytes, first=0x%02x", recvCount, len(frameBuf), frameBuf[0])
|
log.Printf("[video] recv frame #%d %d bytes, first=0x%02x", recvCount, len(frameBuf), frameBuf[0])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
data := ExtractDataFromPayload(frameBuf)
|
data := tunnel.ExtractDataFromPayload(frameBuf)
|
||||||
if data != nil {
|
if data != nil {
|
||||||
dataCount++
|
dataCount++
|
||||||
if dataCount <= 5 || dataCount%100 == 0 {
|
if dataCount <= 5 || dataCount%100 == 0 {
|
||||||
log.Printf("[video] TUNNEL DATA #%d: %d bytes", dataCount, len(data))
|
log.Printf("[video] TUNNEL DATA #%d: %d bytes", dataCount, len(data))
|
||||||
}
|
}
|
||||||
if u.tunnel != nil && u.tunnel.onData != nil {
|
if u.tun != nil && u.tun.OnData != nil {
|
||||||
u.tunnel.onData(data)
|
u.tun.OnData(data)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+24
-1
@@ -1,6 +1,7 @@
|
|||||||
(function() {
|
(function() {
|
||||||
if (window.__autoclickInstalled) return;
|
if (window.__autoclickInstalled) return;
|
||||||
window.__autoclickInstalled = true;
|
window.__autoclickInstalled = true;
|
||||||
|
var wasCaptchaDetected = false;
|
||||||
|
|
||||||
var log = function() {
|
var log = function() {
|
||||||
var args = ['[HOOK] [autoclick]'];
|
var args = ['[HOOK] [autoclick]'];
|
||||||
@@ -24,7 +25,7 @@
|
|||||||
if (inp && !inp.value) {
|
if (inp && !inp.value) {
|
||||||
log('Filling name');
|
log('Filling name');
|
||||||
var set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
|
var set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
|
||||||
set.call(inp, 'Hello');
|
set.call(inp, window.autofillName);
|
||||||
inp.dispatchEvent(new Event('input', { bubbles: true }));
|
inp.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
inp.dispatchEvent(new Event('change', { bubbles: true }));
|
inp.dispatchEvent(new Event('change', { bubbles: true }));
|
||||||
return;
|
return;
|
||||||
@@ -40,5 +41,27 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function scanForCaptcha() {
|
||||||
|
var iframes = document.querySelectorAll("iframe");
|
||||||
|
for (var i = 0; i < iframes.length; i++) {
|
||||||
|
if (iframes[i].src.startsWith("https://id.vk.com/not_robot_captcha")) {
|
||||||
|
if(!wasCaptchaDetected) {
|
||||||
|
log('Captcha detected, user action required');
|
||||||
|
AndroidBridge.onCaptchaDetected(false);
|
||||||
|
wasCaptchaDetected = true;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(wasCaptchaDetected) { // assuming captcha iframe wasn't found
|
||||||
|
log('Captcha closed or solved');
|
||||||
|
AndroidBridge.onCaptchaDetected(true);
|
||||||
|
wasCaptchaDetected = false;
|
||||||
|
clearInterval(captcha_iv);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var iv = setInterval(scan, 1500);
|
var iv = setInterval(scan, 1500);
|
||||||
|
var captcha_iv = setInterval(scanForCaptcha, 1500);
|
||||||
})();
|
})();
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
(() => {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
var JOIN_LINK = window.JOIN_LINK || '';
|
||||||
|
var ANON_NAME = window.ANON_NAME || 'Guest';
|
||||||
|
|
||||||
|
function log(msg) { console.log('[AUTH] ' + msg); }
|
||||||
|
function setStatus(msg) {
|
||||||
|
if (typeof AndroidCaptchaBridge !== 'undefined' && AndroidCaptchaBridge.setStatus) {
|
||||||
|
AndroidCaptchaBridge.setStatus(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getText(url) {
|
||||||
|
try {
|
||||||
|
var response = await fetch(url, {
|
||||||
|
headers: { 'User-Agent': navigator.userAgent }
|
||||||
|
});
|
||||||
|
if (response.status !== 200) log('GET ' + url.substring(0, 60) + ' status=' + response.status);
|
||||||
|
return response.text();
|
||||||
|
} catch(error) {
|
||||||
|
log('GET ' + url.substring(0, 60) + ' failed: ' + error);
|
||||||
|
setStatus('Network error: ' + error.message);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postAPI(url, body, headers) {
|
||||||
|
try {
|
||||||
|
var response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: Object.assign({'Content-Type': 'application/x-www-form-urlencoded'}, headers || {}),
|
||||||
|
body: new URLSearchParams(body).toString()
|
||||||
|
});
|
||||||
|
return response.json();
|
||||||
|
} catch(error) {
|
||||||
|
log('fetch error for ' + url.substring(0, 80) + ': ' + error);
|
||||||
|
return { error: { error_code: -1, error_msg: error.toString() } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var config = {};
|
||||||
|
var savedAuth = null;
|
||||||
|
var savedCaptchaSid = null;
|
||||||
|
|
||||||
|
async function fetchConfig() {
|
||||||
|
setStatus('Fetching config...');
|
||||||
|
var page = await getText('https://vk.com');
|
||||||
|
var bundleMatch = page.match(/https:\/\/[a-z0-9.-]+\/dist\/core_spa\/core_spa_vk\.[a-f0-9]+\.js/);
|
||||||
|
if (!bundleMatch) { log('Bundle URL not found'); return false; }
|
||||||
|
var bundleURL = bundleMatch[0];
|
||||||
|
var chunksBase = bundleURL.substring(0, bundleURL.lastIndexOf('core_spa_vk.')) + 'chunks/';
|
||||||
|
log('Bundle: ' + bundleURL.split('/').pop());
|
||||||
|
|
||||||
|
var bundle = await getText(bundleURL);
|
||||||
|
|
||||||
|
var appIdMatch = bundle.match(/[,;]u=(\d{7,8}),_=\d{7,8},p=\d{8,9}/);
|
||||||
|
var apiMatch = bundle.match(/\d+:\(e,t,n\)=>\{"use strict";n\.d\(t,\{m:\(\)=>r\}\);const r="(5\.\d+)"\}/);
|
||||||
|
if (!appIdMatch || !apiMatch) { log('appId or API version not found'); return false; }
|
||||||
|
config.appId = appIdMatch[1];
|
||||||
|
config.apiVersion = apiMatch[1];
|
||||||
|
log('appId=' + config.appId + ' api=' + config.apiVersion);
|
||||||
|
|
||||||
|
var bridgeMatch = bundle.match(/core_spa\/chunks\/webCallsBridge\.([a-f0-9]+)\.js/);
|
||||||
|
if (!bridgeMatch) { log('webCallsBridge not found'); return false; }
|
||||||
|
var bridgeURL = chunksBase + 'webCallsBridge.' + bridgeMatch[1] + '.js';
|
||||||
|
var bridgeText = await getText(bridgeURL);
|
||||||
|
|
||||||
|
var moduleIds = [];
|
||||||
|
var seen = {};
|
||||||
|
var modMatches = bridgeText.match(/i\((\d{4,6})\)/g) || [];
|
||||||
|
modMatches.forEach(function(match) {
|
||||||
|
var id = match.match(/\d+/)[0];
|
||||||
|
if (!seen[id]) { seen[id] = true; moduleIds.push(id); }
|
||||||
|
});
|
||||||
|
|
||||||
|
var chunkMap = {};
|
||||||
|
var chunkRegex = /(\d+)===e\)return"core_spa\/chunks\/"\+e\+"\.([a-f0-9]+)\.js"/g;
|
||||||
|
var chunkMatch;
|
||||||
|
while ((chunkMatch = chunkRegex.exec(bundle)) !== null) {
|
||||||
|
chunkMap[chunkMatch[1]] = chunkMatch[2];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var idx = 0; idx < moduleIds.length; idx++) {
|
||||||
|
var modId = moduleIds[idx];
|
||||||
|
var hash = chunkMap[modId] || chunkMap[modId.substring(1)];
|
||||||
|
if (!hash) continue;
|
||||||
|
var chunkId = chunkMap[modId] ? modId : modId.substring(1);
|
||||||
|
var chunkURL = chunksBase + chunkId + '.' + hash + '.js';
|
||||||
|
var chunkText = await getText(chunkURL);
|
||||||
|
|
||||||
|
var appVersionMatch = chunkText.match(/appVersion.{0,40}return\s+([0-9.]+)/);
|
||||||
|
if (appVersionMatch) {
|
||||||
|
config.appVersion = appVersionMatch[1];
|
||||||
|
var protoMatch = chunkText.match(/protocolVersion.{0,40}return.*?(\d+)/);
|
||||||
|
if (protoMatch) config.protocolVersion = protoMatch[1];
|
||||||
|
log('appVersion=' + config.appVersion + ' protocolVersion=' + config.protocolVersion);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.retryCaptcha = async function(successToken) {
|
||||||
|
setStatus('Captcha solved, retrying...');
|
||||||
|
document.getElementById('captcha').style.display = 'none';
|
||||||
|
var params = {
|
||||||
|
v: config.apiVersion,
|
||||||
|
vk_join_link: JOIN_LINK,
|
||||||
|
name: ANON_NAME,
|
||||||
|
};
|
||||||
|
if (savedCaptchaSid) {
|
||||||
|
params.captcha_sid = savedCaptchaSid;
|
||||||
|
params.captcha_key = '';
|
||||||
|
params.success_token = successToken;
|
||||||
|
}
|
||||||
|
var result = await postAPI('https://api.vk.com/method/calls.getAnonymousToken', params, savedAuth);
|
||||||
|
log('Retry response: ' + JSON.stringify(result));
|
||||||
|
if (result.error && result.error.error_code === 14) {
|
||||||
|
showCaptcha(result.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (result.response) {
|
||||||
|
onAuthComplete(result.response);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function showCaptcha(error) {
|
||||||
|
savedCaptchaSid = error.captcha_sid || '';
|
||||||
|
var captchaURL = error.redirect_uri;
|
||||||
|
log('Captcha required, showing iframe');
|
||||||
|
setStatus('Solve the captcha:');
|
||||||
|
var iframe = document.getElementById('captcha');
|
||||||
|
iframe.style.display = 'block';
|
||||||
|
iframe.src = captchaURL;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onAuthComplete(response) {
|
||||||
|
var callToken = response.token;
|
||||||
|
var apiBaseURL = response.api_base_url;
|
||||||
|
var okJoinLink = response.ok_join_link;
|
||||||
|
setStatus('Authenticating with OK.ru...');
|
||||||
|
|
||||||
|
var baseURL = apiBaseURL.replace(/\/$/, '');
|
||||||
|
if (baseURL.indexOf('/fb.do') === -1) baseURL += '/fb.do';
|
||||||
|
var deviceId = String(Math.floor(Math.random() * 9e18));
|
||||||
|
|
||||||
|
var sessionData = {
|
||||||
|
version: 2,
|
||||||
|
device_id: deviceId,
|
||||||
|
client_version: config.appVersion,
|
||||||
|
client_type: 'SDK_JS',
|
||||||
|
};
|
||||||
|
|
||||||
|
var okLogin = await postAPI(baseURL, {
|
||||||
|
method: 'auth.anonymLogin',
|
||||||
|
session_data: JSON.stringify(sessionData),
|
||||||
|
application_key: config.publicKey,
|
||||||
|
format: 'json',
|
||||||
|
});
|
||||||
|
log('anonymLogin: ' + JSON.stringify(okLogin));
|
||||||
|
if (!okLogin.session_key) {
|
||||||
|
setStatus('anonymLogin failed: ' + JSON.stringify(okLogin));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setStatus('Auth complete, handing off to relay...');
|
||||||
|
var authResult = {
|
||||||
|
sessionKey: okLogin.session_key,
|
||||||
|
applicationKey: config.publicKey,
|
||||||
|
apiBaseURL: baseURL,
|
||||||
|
joinLink: okJoinLink || config.okJoinLink || JOIN_LINK,
|
||||||
|
anonymToken: callToken,
|
||||||
|
appVersion: config.appVersion,
|
||||||
|
protocolVersion: config.protocolVersion,
|
||||||
|
};
|
||||||
|
log('Passing auth to relay');
|
||||||
|
if (typeof AndroidCaptchaBridge !== 'undefined') {
|
||||||
|
AndroidCaptchaBridge.onJoined(JSON.stringify(authResult));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startAuth() {
|
||||||
|
if (!(await fetchConfig())) {
|
||||||
|
setStatus('Config extraction failed');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setStatus('Getting anonymous token...');
|
||||||
|
var anonResult = await postAPI('https://login.vk.com/?act=get_anonym_token', {
|
||||||
|
client_id: config.appId,
|
||||||
|
});
|
||||||
|
var anonToken = anonResult.data && anonResult.data.access_token;
|
||||||
|
if (!anonToken) {
|
||||||
|
setStatus('Failed to get anon token');
|
||||||
|
log('get_anonym_token failed: ' + JSON.stringify(anonResult));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log('anon token OK');
|
||||||
|
savedAuth = { Authorization: 'Bearer ' + anonToken };
|
||||||
|
|
||||||
|
setStatus('Getting call settings...');
|
||||||
|
var settings = await postAPI('https://api.vk.com/method/calls.getSettings', {
|
||||||
|
v: config.apiVersion,
|
||||||
|
}, savedAuth);
|
||||||
|
config.publicKey = settings.response && settings.response.settings && settings.response.settings.public_key;
|
||||||
|
log('publicKey: ' + config.publicKey);
|
||||||
|
|
||||||
|
setStatus('Getting call preview...');
|
||||||
|
var preview = await postAPI('https://api.vk.com/method/calls.getCallPreview', {
|
||||||
|
v: config.apiVersion,
|
||||||
|
vk_join_link: JOIN_LINK,
|
||||||
|
}, savedAuth);
|
||||||
|
var okJoinLink = preview.response && preview.response.ok_join_link;
|
||||||
|
if (okJoinLink) {
|
||||||
|
config.okJoinLink = okJoinLink;
|
||||||
|
log('okJoinLink: ' + okJoinLink);
|
||||||
|
}
|
||||||
|
|
||||||
|
setStatus('Getting call token...');
|
||||||
|
var callResult = await postAPI('https://api.vk.com/method/calls.getAnonymousToken', {
|
||||||
|
v: config.apiVersion,
|
||||||
|
vk_join_link: JOIN_LINK,
|
||||||
|
name: ANON_NAME,
|
||||||
|
}, savedAuth);
|
||||||
|
log('getAnonymousToken: ' + JSON.stringify(callResult));
|
||||||
|
|
||||||
|
if (callResult.error && callResult.error.error_code === 14) {
|
||||||
|
showCaptcha(callResult.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (callResult.response) {
|
||||||
|
onAuthComplete(callResult.response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
startAuth().catch(function(error) {
|
||||||
|
log('startAuth error: ' + error);
|
||||||
|
setStatus('Error: ' + error.message);
|
||||||
|
});
|
||||||
|
})();
|
||||||
@@ -412,13 +412,13 @@
|
|||||||
log('Incoming subscriberSdpOffer, pcSeq=' + result.subscriberSdpOffer.pcSeq);
|
log('Incoming subscriberSdpOffer, pcSeq=' + result.subscriberSdpOffer.pcSeq);
|
||||||
}
|
}
|
||||||
if (result && result.slotsChanged) {
|
if (result && result.slotsChanged) {
|
||||||
log('Incoming slotsChanged:', JSON.stringify(result.slotsChanged).substring(0, 200));
|
log('Incoming slotsChanged:', JSON.stringify(result.slotsChanged));
|
||||||
}
|
}
|
||||||
if (result && result.participantsChanged) {
|
if (result && result.participantsChanged) {
|
||||||
log('Incoming participantsChanged');
|
log('Incoming participantsChanged');
|
||||||
}
|
}
|
||||||
if (result && result.connectionStatusChanged) {
|
if (result && result.connectionStatusChanged) {
|
||||||
log('Incoming connectionStatusChanged:', JSON.stringify(result.connectionStatusChanged).substring(0, 200));
|
log('Incoming connectionStatusChanged:', JSON.stringify(result.connectionStatusChanged));
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|||||||
+1
-1
@@ -386,7 +386,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (msg.notification === 'remote-media-settings' || msg.notification === 'media-settings' || msg.notification === 'media-settings-changed') {
|
if (msg.notification === 'remote-media-settings' || msg.notification === 'media-settings' || msg.notification === 'media-settings-changed') {
|
||||||
log('VK media-settings notification:', maskAddr(JSON.stringify(msg).substring(0, 300)));
|
log('VK media-settings notification:', maskAddr(JSON.stringify(msg)));
|
||||||
}
|
}
|
||||||
if (msg.notification === 'participant-added' || msg.notification === 'participant-removed') {
|
if (msg.notification === 'participant-added' || msg.notification === 'participant-removed') {
|
||||||
log('VK participant event: ' + msg.notification);
|
log('VK participant event: ' + msg.notification);
|
||||||
|
|||||||
Executable
+19
@@ -0,0 +1,19 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
PREBUILTS="$ROOT/prebuilts"
|
||||||
|
|
||||||
|
mkdir -p "$PREBUILTS"
|
||||||
|
|
||||||
|
echo "=== Building Android app ==="
|
||||||
|
"$ROOT/build-go.sh"
|
||||||
|
"$ROOT/build-app.sh"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "=== Building creator-app + headless creators ==="
|
||||||
|
"$ROOT/build-creator.sh"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "=== Release complete ==="
|
||||||
|
ls -lh "$PREBUILTS/"
|
||||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user