wbstream support
This commit is contained in:
1 parent
b48b0cb927
commit
3b3ffed0b3
49 files changed
+3060
-151
No files matched your search
Binary file not shown.
@@ -21,6 +21,7 @@ import bypass.whitelist.tunnel.ProxyService
|
||||
import bypass.whitelist.tunnel.TunnelVpnService
|
||||
import bypass.whitelist.tunnel.VpnStatus
|
||||
import bypass.whitelist.ui.HeadlessTelemostFragment
|
||||
import bypass.whitelist.ui.HeadlessWBStreamFragment
|
||||
import bypass.whitelist.ui.HeadlessVkFragment
|
||||
import bypass.whitelist.ui.JoinFragmentHost
|
||||
import bypass.whitelist.ui.JsHookJoinFragment
|
||||
@@ -168,7 +169,7 @@ class MainActivity : AppCompatActivity(), SettingsDialogFragment.Listener, JoinF
|
||||
if (url.isEmpty()) return
|
||||
|
||||
val platform = CallPlatform.fromUrl(url)
|
||||
if (Prefs.tunnelMode == TunnelMode.DC && platform != CallPlatform.VK) {
|
||||
if (Prefs.tunnelMode == TunnelMode.DC && platform == CallPlatform.TELEMOST) {
|
||||
Prefs.tunnelMode = TunnelMode.VIDEO
|
||||
statusCtrl.tunnelMode = TunnelMode.VIDEO
|
||||
Toast.makeText(this, R.string.dc_mode_not_supported, Toast.LENGTH_SHORT).show()
|
||||
@@ -186,10 +187,11 @@ class MainActivity : AppCompatActivity(), SettingsDialogFragment.Listener, JoinF
|
||||
Prefs.lastUrl = url
|
||||
}
|
||||
|
||||
val fragment = if (Prefs.headless) {
|
||||
when (CallPlatform.fromUrl(url)) {
|
||||
val fragment = if (Prefs.headless || platform == CallPlatform.WBSTREAM) {
|
||||
when (platform) {
|
||||
CallPlatform.VK -> HeadlessVkFragment.newInstance(url)
|
||||
CallPlatform.TELEMOST -> HeadlessTelemostFragment.newInstance(url)
|
||||
CallPlatform.WBSTREAM -> HeadlessWBStreamFragment.newInstance(url)
|
||||
}
|
||||
} else {
|
||||
JsHookJoinFragment.newInstance(url)
|
||||
|
||||
@@ -2,10 +2,17 @@ package bypass.whitelist.tunnel
|
||||
|
||||
enum class CallPlatform(val id: String, val urlMarker: String) {
|
||||
VK("vk", ""),
|
||||
TELEMOST("telemost", "telemost.yandex");
|
||||
TELEMOST("telemost", "telemost.yandex"),
|
||||
WBSTREAM("wbstream", "wbstream://");
|
||||
|
||||
companion object {
|
||||
fun fromUrl(url: String): CallPlatform =
|
||||
if (url.contains(TELEMOST.urlMarker)) TELEMOST else VK
|
||||
fun fromUrl(url: String): CallPlatform = when {
|
||||
url.contains(WBSTREAM.urlMarker) -> WBSTREAM
|
||||
url.contains(TELEMOST.urlMarker) -> TELEMOST
|
||||
else -> VK
|
||||
}
|
||||
|
||||
fun extractRoomId(url: String): String =
|
||||
url.removePrefix(WBSTREAM.urlMarker).trim()
|
||||
}
|
||||
}
|
||||
@@ -118,10 +118,8 @@ class HeadlessRelayController(
|
||||
put("joinLink", joinLink)
|
||||
put("displayName", displayName)
|
||||
put("tunnelMode", tunnelMode)
|
||||
if (bypass.whitelist.util.Prefs.vp8PacingEnabled) {
|
||||
put("vp8Fps", bypass.whitelist.util.Prefs.vp8Fps)
|
||||
put("vp8Batch", bypass.whitelist.util.Prefs.vp8Batch)
|
||||
}
|
||||
put("vp8Fps", bypass.whitelist.util.Prefs.vp8Fps)
|
||||
put("vp8Batch", bypass.whitelist.util.Prefs.vp8Batch)
|
||||
}
|
||||
writeStdin("AUTH:$json")
|
||||
}
|
||||
|
||||
@@ -41,10 +41,8 @@ class HeadlessTelemostFragment : Fragment() {
|
||||
val params = JSONObject().apply {
|
||||
put("joinLink", joinLink)
|
||||
put("displayName", displayName)
|
||||
if (Prefs.vp8PacingEnabled) {
|
||||
put("vp8Fps", Prefs.vp8Fps)
|
||||
put("vp8Batch", Prefs.vp8Batch)
|
||||
}
|
||||
put("vp8Fps", Prefs.vp8Fps)
|
||||
put("vp8Batch", Prefs.vp8Batch)
|
||||
}
|
||||
relay.sendJoinParams(params.toString())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
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.CallPlatform
|
||||
import bypass.whitelist.tunnel.HeadlessRelayController
|
||||
import bypass.whitelist.tunnel.VpnStatus
|
||||
import bypass.whitelist.util.Prefs
|
||||
import org.json.JSONObject
|
||||
|
||||
class HeadlessWBStreamFragment : 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_wbstream, container, false)
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
val rawUrl = requireArguments().getString(ARG_URL, "")
|
||||
val roomId = CallPlatform.extractRoomId(rawUrl)
|
||||
val displayName = Prefs.autoclickName
|
||||
|
||||
relay = HeadlessRelayController(
|
||||
requireContext().applicationInfo.nativeLibraryDir,
|
||||
relayMode = "wbstream-headless-joiner",
|
||||
onLog = { host?.appendLog(it) },
|
||||
onStatus = { status ->
|
||||
Log.d("WB-HEADLESS", "status: $status")
|
||||
host?.onJoinStatus(status)
|
||||
when (status) {
|
||||
VpnStatus.STARTING -> {
|
||||
val params = JSONObject().apply {
|
||||
put("roomId", roomId)
|
||||
put("displayName", displayName)
|
||||
put("tunnelMode", Prefs.tunnelMode.relayArg)
|
||||
put("vp8Fps", Prefs.vp8Fps)
|
||||
put("vp8Batch", Prefs.vp8Batch)
|
||||
}
|
||||
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): HeadlessWBStreamFragment {
|
||||
return HeadlessWBStreamFragment().apply {
|
||||
arguments = Bundle().apply {
|
||||
putString(ARG_URL, url)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-25
@@ -2,50 +2,31 @@ package bypass.whitelist.ui
|
||||
|
||||
import android.app.Dialog
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.CheckBox
|
||||
import android.widget.EditText
|
||||
import android.widget.LinearLayout
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.fragment.app.DialogFragment
|
||||
import bypass.whitelist.R
|
||||
import bypass.whitelist.util.Prefs
|
||||
import bypass.whitelist.util.VP8Defaults
|
||||
|
||||
class Vp8PacingSettingsDialogFragment : DialogFragment() {
|
||||
|
||||
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
|
||||
val view = layoutInflater.inflate(R.layout.dialog_vp8_pacing_settings, null)
|
||||
|
||||
val enabledCheckbox = view.findViewById<CheckBox>(R.id.vp8PacingEnabledCheckbox)
|
||||
val inputsContainer = view.findViewById<LinearLayout>(R.id.vp8PacingInputs)
|
||||
val fpsInput = view.findViewById<EditText>(R.id.vp8FpsInput)
|
||||
val batchInput = view.findViewById<EditText>(R.id.vp8BatchInput)
|
||||
|
||||
enabledCheckbox.isChecked = Prefs.vp8PacingEnabled
|
||||
inputsContainer.visibility = if (Prefs.vp8PacingEnabled) View.VISIBLE else View.GONE
|
||||
fpsInput.setText(Prefs.vp8Fps.toString())
|
||||
batchInput.setText(Prefs.vp8Batch.toString())
|
||||
|
||||
enabledCheckbox.setOnCheckedChangeListener { _, checked ->
|
||||
inputsContainer.visibility = if (checked) View.VISIBLE else View.GONE
|
||||
}
|
||||
|
||||
return AlertDialog.Builder(requireContext())
|
||||
.setTitle(R.string.vp8_pacing_title)
|
||||
.setView(view)
|
||||
.setPositiveButton(android.R.string.ok) { _, _ ->
|
||||
Prefs.vp8PacingEnabled = enabledCheckbox.isChecked
|
||||
if (enabledCheckbox.isChecked) {
|
||||
val fps = fpsInput.text.toString().toIntOrNull()
|
||||
if (fps != null && fps in 1..240) {
|
||||
Prefs.vp8Fps = fps
|
||||
}
|
||||
val batch = batchInput.text.toString().toIntOrNull()
|
||||
if (batch != null && batch in 1..256) {
|
||||
Prefs.vp8Batch = batch
|
||||
}
|
||||
}
|
||||
val fps = fpsInput.text.toString().toIntOrNull()
|
||||
if (fps != null && fps in 1..240) Prefs.vp8Fps = fps
|
||||
val batch = batchInput.text.toString().toIntOrNull()
|
||||
if (batch != null && batch in 1..256) Prefs.vp8Batch = batch
|
||||
}
|
||||
.setNegativeButton(android.R.string.cancel, null)
|
||||
.create()
|
||||
@@ -53,7 +34,5 @@ class Vp8PacingSettingsDialogFragment : DialogFragment() {
|
||||
|
||||
companion object {
|
||||
const val TAG = "Vp8PacingSettingsDialog"
|
||||
|
||||
fun defaults(): Pair<Int, Int> = VP8Defaults.FPS to VP8Defaults.BATCH
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,6 @@ object PrefsKeys {
|
||||
const val DNS_MODE = "dns_mode"
|
||||
const val DNS_PRIMARY = "dns_primary"
|
||||
const val DNS_SECONDARY = "dns_secondary"
|
||||
const val VP8_PACING_ENABLED = "vp8_pacing_enabled"
|
||||
const val VP8_FPS = "vp8_fps"
|
||||
const val VP8_BATCH = "vp8_batch"
|
||||
}
|
||||
|
||||
@@ -110,10 +110,6 @@ object Prefs {
|
||||
get() = prefs.getString(PrefsKeys.DNS_SECONDARY, Vpn.DNS_SECONDARY)!!
|
||||
set(value) = prefs.edit { putString(PrefsKeys.DNS_SECONDARY, value) }
|
||||
|
||||
var vp8PacingEnabled: Boolean
|
||||
get() = prefs.getBoolean(PrefsKeys.VP8_PACING_ENABLED, false)
|
||||
set(value) = prefs.edit { putBoolean(PrefsKeys.VP8_PACING_ENABLED, value) }
|
||||
|
||||
var vp8Fps: Int
|
||||
get() = prefs.getInt(PrefsKeys.VP8_FPS, VP8Defaults.FPS)
|
||||
set(value) = prefs.edit { putInt(PrefsKeys.VP8_FPS, value) }
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -5,56 +5,31 @@
|
||||
android:layout_height="wrap_content"
|
||||
android:padding="12dp">
|
||||
|
||||
<CheckBox
|
||||
android:id="@+id/vp8PacingEnabledCheckbox"
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/vp8_pacing_enabled_label"
|
||||
android:textSize="16sp" />
|
||||
android:text="@string/vp8_fps_label"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/vp8FpsInput"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:hint="@string/vp8_fps_hint"
|
||||
android:inputType="number" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:text="@string/vp8_pacing_hint"
|
||||
android:textSize="12sp"
|
||||
android:alpha="0.7" />
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/vp8_batch_label"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/vp8PacingInputs"
|
||||
<EditText
|
||||
android:id="@+id/vp8BatchInput"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:visibility="gone"
|
||||
android:paddingTop="12dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/vp8_fps_label"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/vp8FpsInput"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:hint="@string/vp8_fps_hint"
|
||||
android:inputType="number" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/vp8_batch_label"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/vp8BatchInput"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:hint="@string/vp8_batch_hint"
|
||||
android:inputType="number" />
|
||||
|
||||
</LinearLayout>
|
||||
android:hint="@string/vp8_batch_hint"
|
||||
android:inputType="number" />
|
||||
|
||||
</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" />
|
||||
@@ -59,12 +59,10 @@
|
||||
<string name="dns_secondary_hint">Secondary DNS</string>
|
||||
<string name="menu_vp8_pacing">VP8 pacing</string>
|
||||
<string name="vp8_pacing_title">VP8 pacing</string>
|
||||
<string name="vp8_pacing_enabled_label">Override VP8 pacing</string>
|
||||
<string name="vp8_pacing_hint">When off, defaults are used (fps=25, batch=1). Higher batch = higher throughput.</string>
|
||||
<string name="vp8_fps_label">FPS</string>
|
||||
<string name="vp8_fps_hint">e.g. 25</string>
|
||||
<string name="vp8_fps_hint">e.g. 24</string>
|
||||
<string name="vp8_batch_label">Batch</string>
|
||||
<string name="vp8_batch_hint">e.g. 1, 8, 16</string>
|
||||
<string name="vp8_batch_hint">e.g. 1, 8, 30</string>
|
||||
<string name="notification_vpn_title">VPN active</string>
|
||||
<string name="notification_proxy_title">Proxy active</string>
|
||||
<string name="notification_disconnect">Disconnect</string>
|
||||
|
||||
+22
-1
@@ -7,6 +7,7 @@ CREATOR_DIR="$ROOT/creator-app"
|
||||
HEADLESS_DIR="$ROOT/headless"
|
||||
HEADLESS_VK_DIR="$HEADLESS_DIR/vk"
|
||||
HEADLESS_TM_DIR="$HEADLESS_DIR/telemost"
|
||||
HEADLESS_WB_DIR="$HEADLESS_DIR/wbstream"
|
||||
|
||||
echo "=== Building relay binaries ==="
|
||||
cd "$RELAY_DIR"
|
||||
@@ -69,7 +70,27 @@ GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-tel
|
||||
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 "=== Building headless-wbstream-creator ==="
|
||||
cd "$HEADLESS_WB_DIR"
|
||||
|
||||
echo "macOS (universal)..."
|
||||
GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-wbstream-darwin-amd64" .
|
||||
GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-wbstream-darwin-arm64" .
|
||||
lipo -create -output "$HEADLESS_DIR/headless-wbstream-darwin" "$HEADLESS_DIR/headless-wbstream-darwin-amd64" "$HEADLESS_DIR/headless-wbstream-darwin-arm64"
|
||||
rm "$HEADLESS_DIR/headless-wbstream-darwin-amd64" "$HEADLESS_DIR/headless-wbstream-darwin-arm64"
|
||||
|
||||
echo "Windows x64..."
|
||||
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-wbstream-windows-x64.exe" .
|
||||
echo "Windows x86..."
|
||||
GOOS=windows GOARCH=386 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-wbstream-windows-ia32.exe" .
|
||||
|
||||
echo "Linux x64..."
|
||||
GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-wbstream-linux-x64" .
|
||||
echo "Linux x86..."
|
||||
GOOS=linux GOARCH=386 go build -ldflags="-s -w" -o "$HEADLESS_DIR/headless-wbstream-linux-ia32" .
|
||||
|
||||
ls -lh "$HEADLESS_DIR"/headless-vk-darwin "$HEADLESS_DIR"/headless-telemost-darwin "$HEADLESS_DIR"/headless-wbstream-darwin
|
||||
|
||||
echo ""
|
||||
echo "=== Building Electron apps ==="
|
||||
|
||||
+4
-1
@@ -39,5 +39,8 @@ 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 "Building headless-wbstream-creator..."
|
||||
go -C "$ROOT/headless/wbstream" build -ldflags="-s -w" -o headless-wbstream-creator .
|
||||
|
||||
echo "Done."
|
||||
ls -lh "$ROOT/relay/relay" "$ROOT/headless/vk/headless-vk-creator" "$ROOT/headless/telemost/headless-telemost-creator"
|
||||
ls -lh "$ROOT/relay/relay" "$ROOT/headless/vk/headless-vk-creator" "$ROOT/headless/telemost/headless-telemost-creator" "$ROOT/headless/wbstream/headless-wbstream-creator"
|
||||
+7
-1
@@ -8,5 +8,11 @@ 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 "Building headless-wbstream-creator..."
|
||||
go -C "$ROOT/headless/wbstream" build -ldflags="-s -w" -o headless-wbstream-creator .
|
||||
|
||||
echo "Building headless-wbstream-joiner..."
|
||||
go -C "$ROOT/headless/wbstream-joiner" build -ldflags="-s -w" -o headless-wbstream-joiner .
|
||||
|
||||
echo "Done."
|
||||
ls -lh "$ROOT/headless/vk/headless-vk-creator" "$ROOT/headless/telemost/headless-telemost-creator"
|
||||
ls -lh "$ROOT/headless/vk/headless-vk-creator" "$ROOT/headless/telemost/headless-telemost-creator" "$ROOT/headless/wbstream/headless-wbstream-creator" "$ROOT/headless/wbstream-joiner/headless-wbstream-joiner"
|
||||
@@ -20,6 +20,7 @@
|
||||
<button class="btn-telemost" id="btnTelemost">Telemost</button>
|
||||
<button class="btn-headless" id="btnHeadlessVK">Headless VK</button>
|
||||
<button class="btn-headless-tm" id="btnHeadlessTM">Headless TM</button>
|
||||
<button class="btn-headless-wb" id="btnHeadlessWB">Headless WB</button>
|
||||
<span class="toolbar-spacer"></span>
|
||||
<span class="toolbar-label" id="tunnelLabel" style="display:none">Tunnel:</span>
|
||||
<select id="modeSelect" class="toolbar-select" style="display:none">
|
||||
@@ -46,6 +47,9 @@
|
||||
<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 class="headless-call-info" id="headlessCallInfoWB">
|
||||
<div class="headless-row"><span class="headless-label">Join link:</span> <a id="headlessWBJoinLink" href="#" class="headless-link"></a><img class="headless-copy" src="resources/icons8-copy-50.png" data-copy="headlessWBJoinLink" title="Copy"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="logs" id="logsPanel" style="display:none">
|
||||
|
||||
@@ -163,7 +163,10 @@ export class BotManager {
|
||||
if (payload?.cmd) {
|
||||
const handled = await this.handlePayloadCommand(payload, peerId);
|
||||
if (handled) return;
|
||||
const cmdPrefix = payload.cmd === BotCommand.VK ? '/vk' : payload.cmd === BotCommand.TM ? '/tm' : null;
|
||||
let cmdPrefix: string | null = null;
|
||||
if (payload.cmd === BotCommand.VK) cmdPrefix = '/vk';
|
||||
else if (payload.cmd === BotCommand.TM) cmdPrefix = '/tm';
|
||||
else if (payload.cmd === BotCommand.WB) cmdPrefix = '/wb';
|
||||
if (cmdPrefix && payload.mode) {
|
||||
text = `${cmdPrefix} ${payload.mode}`;
|
||||
}
|
||||
@@ -195,6 +198,7 @@ export class BotManager {
|
||||
}
|
||||
|
||||
private parseTunnelMode(text: string, platform: Platform): TunnelMode {
|
||||
if (platform === Platform.WBStream) return TunnelMode.HeadlessWBStream;
|
||||
if (text.includes('headless')) {
|
||||
return platform === Platform.VK ? TunnelMode.HeadlessVK : TunnelMode.HeadlessTelemost;
|
||||
}
|
||||
@@ -206,6 +210,7 @@ export class BotManager {
|
||||
switch (mode) {
|
||||
case TunnelMode.HeadlessVK:
|
||||
case TunnelMode.HeadlessTelemost:
|
||||
case TunnelMode.HeadlessWBStream:
|
||||
return 'Headless';
|
||||
case TunnelMode.PionVideo:
|
||||
return 'Video';
|
||||
@@ -225,6 +230,11 @@ export class BotManager {
|
||||
console.log('[BOT] Creating Telemost tab with mode:', mode);
|
||||
this.onCreateTab({ mode, peerId, platform: Platform.Telemost });
|
||||
await this.sendMessage(peerId, `Creating Telemost call (${this.tunnelModeLabel(mode)})`, createMainKeyboard());
|
||||
} else if (text.startsWith('/wb')) {
|
||||
const mode = this.parseTunnelMode(text, Platform.WBStream);
|
||||
console.log('[BOT] Creating WB Stream tab with mode:', mode);
|
||||
this.onCreateTab({ mode, peerId, platform: Platform.WBStream });
|
||||
await this.sendMessage(peerId, `Creating WB Stream room (${this.tunnelModeLabel(mode)})`, createMainKeyboard());
|
||||
} else if (text === '/list') {
|
||||
await this.showList(peerId);
|
||||
} else if (text.startsWith('/close ')) {
|
||||
|
||||
@@ -34,6 +34,9 @@ export function createMainKeyboard() {
|
||||
{ action: { type: 'text', label: '📹 TM Video', payload: JSON.stringify({ cmd: BotCommand.TM, mode: 'video' }) } },
|
||||
{ action: { type: 'text', label: '👻 TM Headless', payload: JSON.stringify({ cmd: BotCommand.TM, mode: 'headless' }) } },
|
||||
],
|
||||
[
|
||||
{ action: { type: 'text', label: '👻 WB Headless', payload: JSON.stringify({ cmd: BotCommand.WB, mode: 'headless' }) } },
|
||||
],
|
||||
[
|
||||
{ action: { type: 'text', label: '📋 Active Tabs', payload: JSON.stringify({ cmd: BotCommand.List }) } },
|
||||
],
|
||||
|
||||
@@ -37,6 +37,7 @@ export class TabManager {
|
||||
private relayPath: string;
|
||||
private headlessVKPath: string;
|
||||
private headlessTelemostPath: string;
|
||||
private headlessWBStreamPath: string;
|
||||
private hooksDir: string;
|
||||
|
||||
constructor() {
|
||||
@@ -52,6 +53,10 @@ export class TabManager {
|
||||
path.join('headless', 'telemost', binaryName('headless-telemost-creator')),
|
||||
binaryName('headless-telemost-creator'),
|
||||
);
|
||||
this.headlessWBStreamPath = resolveResourcePath(
|
||||
path.join('headless', 'wbstream', binaryName('headless-wbstream-creator')),
|
||||
binaryName('headless-wbstream-creator'),
|
||||
);
|
||||
this.hooksDir = app.isPackaged
|
||||
? path.join(process.resourcesPath!, 'hooks')
|
||||
: path.join(__dirname, '..', '..', '..', 'hooks');
|
||||
@@ -217,9 +222,24 @@ export class TabManager {
|
||||
|
||||
async startHeadless(tabId: string, platform: Platform): Promise<void> {
|
||||
const tab = await this.getOrCreateTab(tabId);
|
||||
tab.platform = platform;
|
||||
|
||||
if (platform === Platform.WBStream) {
|
||||
tab.tunnelMode = TunnelMode.HeadlessWBStream;
|
||||
this.killRelay(tabId, tab);
|
||||
const proc = spawn(this.headlessWBStreamPath, ['--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}`);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const isTelemost = platform === Platform.Telemost;
|
||||
tab.tunnelMode = isTelemost ? TunnelMode.HeadlessTelemost : TunnelMode.HeadlessVK;
|
||||
tab.platform = platform;
|
||||
const cookies = isTelemost
|
||||
? await this.getYandexCookies()
|
||||
: await this.getVKCookies();
|
||||
|
||||
@@ -45,28 +45,33 @@ export function renderContent(tm: RendererTabManager): void {
|
||||
if (activeTab.headless) {
|
||||
toolbar.style.display = 'none';
|
||||
headlessInfo.style.display = 'block';
|
||||
const title = activeTab.platform === Platform.Telemost ? 'Headless Telemost' : 'Headless VK';
|
||||
let title = 'Headless VK';
|
||||
if (activeTab.platform === Platform.Telemost) title = 'Headless Telemost';
|
||||
else if (activeTab.platform === Platform.WBStream) title = 'Headless WB Stream';
|
||||
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';
|
||||
const callInfoWB = document.getElementById('headlessCallInfoWB')!;
|
||||
callInfoVK.style.display = 'none';
|
||||
callInfoTM.style.display = 'none';
|
||||
callInfoWB.style.display = 'none';
|
||||
if (callInfo) {
|
||||
if (activeTab.platform === Platform.WBStream) {
|
||||
callInfoWB.style.display = 'block';
|
||||
document.getElementById('headlessWBJoinLink')!.textContent = callInfo.joinLink || '';
|
||||
} else if (activeTab.platform === Platform.Telemost) {
|
||||
callInfoTM.style.display = 'block';
|
||||
document.getElementById('headlessTMJoinLink')!.textContent = callInfo.joinLink || '';
|
||||
document.getElementById('headlessTMProtocol')!.textContent = callInfo.protocol || '';
|
||||
} else {
|
||||
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 {
|
||||
toolbar.style.display = 'flex';
|
||||
|
||||
@@ -55,6 +55,7 @@ function bindToolbarEvents(): void {
|
||||
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('btnHeadlessWB')!.addEventListener('click', () => tm.switchToHeadless(Platform.WBStream));
|
||||
document.getElementById('modeSelect')!.addEventListener('change', (event) => {
|
||||
tm.setTunnelMode((event.target as HTMLSelectElement).value);
|
||||
});
|
||||
@@ -159,6 +160,8 @@ function init(): void {
|
||||
tm.switchToHeadless(Platform.VK);
|
||||
} else if (data.mode === TunnelMode.HeadlessTelemost) {
|
||||
tm.switchToHeadless(Platform.Telemost);
|
||||
} else if (data.mode === TunnelMode.HeadlessWBStream) {
|
||||
tm.switchToHeadless(Platform.WBStream);
|
||||
} else {
|
||||
const url = data.platform === Platform.Telemost ? TELEMOST_URL : VK_IM_URL;
|
||||
loadURL(tm, url);
|
||||
|
||||
@@ -38,11 +38,21 @@ export class RendererTabManager {
|
||||
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';
|
||||
switch (platform) {
|
||||
case Platform.Telemost:
|
||||
tab.mode = TunnelMode.HeadlessTelemost;
|
||||
tab.name = 'Headless TM';
|
||||
break;
|
||||
case Platform.WBStream:
|
||||
tab.mode = TunnelMode.HeadlessWBStream;
|
||||
tab.name = 'Headless WB';
|
||||
break;
|
||||
default:
|
||||
tab.mode = TunnelMode.HeadlessVK;
|
||||
tab.name = 'Headless VK';
|
||||
}
|
||||
tab.headless = true;
|
||||
tab.platform = platform;
|
||||
tab.callInfo = undefined;
|
||||
|
||||
@@ -5,11 +5,13 @@ export enum TunnelMode {
|
||||
PionVideo = 'pion-video',
|
||||
HeadlessVK = 'headless-vk',
|
||||
HeadlessTelemost = 'headless-telemost',
|
||||
HeadlessWBStream = 'headless-wbstream',
|
||||
}
|
||||
|
||||
export enum Platform {
|
||||
VK = 'vk',
|
||||
Telemost = 'telemost',
|
||||
WBStream = 'wbstream',
|
||||
}
|
||||
|
||||
export enum RelayMode {
|
||||
@@ -26,6 +28,7 @@ export enum CallStatus {
|
||||
export enum BotCommand {
|
||||
VK = 'vk',
|
||||
TM = 'tm',
|
||||
WB = 'wb',
|
||||
List = 'list',
|
||||
Menu = 'menu',
|
||||
Close = 'close',
|
||||
|
||||
@@ -176,6 +176,12 @@ body {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.btn-headless-wb {
|
||||
background: linear-gradient(90deg, #cb11ab 0%, #481173 100%);
|
||||
color: white;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.toolbar-spacer {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
Executable
+128
@@ -0,0 +1,128 @@
|
||||
#!/bin/sh
|
||||
# End-to-end smoke test: spawn a wbstream creator + joiner pair, route curl
|
||||
# through the joiner's SOCKS5 and verify the response arrives.
|
||||
#
|
||||
# Usage:
|
||||
# ./test-wbstream.sh [video|dc] # default: video
|
||||
|
||||
set -u
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
CREATOR="$ROOT/headless/wbstream/headless-wbstream-creator"
|
||||
JOINER="$ROOT/headless/wbstream-joiner/headless-wbstream-joiner"
|
||||
SOCKS_PORT=11080
|
||||
TARGET_URL="https://api.ipify.org"
|
||||
PROBE_TIMEOUT=15
|
||||
SETTLE_TIMEOUT=20
|
||||
|
||||
mode_arg="${1:-video}"
|
||||
case "$mode_arg" in
|
||||
video|dc) ;;
|
||||
*)
|
||||
echo "Unknown mode: $mode_arg (expected video or dc)" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
CREATOR_LOG=$(mktemp -t wb-c.XXXXXX.log)
|
||||
JOINER_LOG=$(mktemp -t wb-j.XXXXXX.log)
|
||||
CREATOR_PID=""
|
||||
JOINER_PID=""
|
||||
|
||||
cleanup() {
|
||||
[ -n "$JOINER_PID" ] && kill "$JOINER_PID" 2>/dev/null
|
||||
[ -n "$CREATOR_PID" ] && kill "$CREATOR_PID" 2>/dev/null
|
||||
wait 2>/dev/null
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
require_bin() {
|
||||
if [ ! -x "$1" ]; then
|
||||
echo "FAIL: missing binary $1" >&2
|
||||
echo "Run ./build-headless.sh first." >&2
|
||||
exit 2
|
||||
fi
|
||||
}
|
||||
|
||||
require_bin "$CREATOR"
|
||||
require_bin "$JOINER"
|
||||
|
||||
echo "=== mode=$mode_arg ==="
|
||||
|
||||
"$CREATOR" > "$CREATOR_LOG" 2>&1 &
|
||||
CREATOR_PID=$!
|
||||
|
||||
waited=0
|
||||
JOIN_LINK=""
|
||||
while [ "$waited" -lt "$SETTLE_TIMEOUT" ]; do
|
||||
JOIN_LINK=$(grep -m1 "join_link:" "$CREATOR_LOG" | awk '{print $2}')
|
||||
[ -n "$JOIN_LINK" ] && break
|
||||
sleep 1
|
||||
waited=$((waited + 1))
|
||||
done
|
||||
|
||||
if [ -z "$JOIN_LINK" ]; then
|
||||
echo "FAIL: creator did not print a join_link within ${SETTLE_TIMEOUT}s" >&2
|
||||
tail -20 "$CREATOR_LOG" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "join_link=$JOIN_LINK"
|
||||
|
||||
"$JOINER" --room "$JOIN_LINK" --socks-port "$SOCKS_PORT" --tunnel-mode "$mode_arg" \
|
||||
> "$JOINER_LOG" 2>&1 &
|
||||
JOINER_PID=$!
|
||||
|
||||
waited=0
|
||||
while [ "$waited" -lt "$SETTLE_TIMEOUT" ]; do
|
||||
if grep -q "TUNNEL CONNECTED" "$JOINER_LOG"; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
waited=$((waited + 1))
|
||||
done
|
||||
|
||||
if ! grep -q "TUNNEL CONNECTED" "$JOINER_LOG"; then
|
||||
echo "FAIL: joiner did not reach TUNNEL CONNECTED within ${SETTLE_TIMEOUT}s" >&2
|
||||
tail -20 "$JOINER_LOG" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# SOCKS listener starts in a goroutine after TUNNEL CONNECTED prints; poll.
|
||||
waited=0
|
||||
while [ "$waited" -lt 10 ]; do
|
||||
if nc -z 127.0.0.1 "$SOCKS_PORT" 2>/dev/null; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
waited=$((waited + 1))
|
||||
done
|
||||
if ! nc -z 127.0.0.1 "$SOCKS_PORT" 2>/dev/null; then
|
||||
echo "FAIL: SOCKS5 port $SOCKS_PORT never opened" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
response=$(curl --socks5 "127.0.0.1:$SOCKS_PORT" -m "$PROBE_TIMEOUT" -sv "$TARGET_URL" 2>&1)
|
||||
if ! echo "$response" | grep -q "HTTP/.* 200"; then
|
||||
echo "FAIL: SOCKS5 request did not return HTTP 200" >&2
|
||||
echo "--- curl output ---" >&2
|
||||
echo "$response" >&2
|
||||
echo "--- joiner log tail ---" >&2
|
||||
tail -30 "$JOINER_LOG" >&2
|
||||
echo "--- creator log tail ---" >&2
|
||||
tail -30 "$CREATOR_LOG" >&2
|
||||
exit 1
|
||||
fi
|
||||
response=$(echo "$response" | tail -1)
|
||||
echo "remote_ip=$response"
|
||||
|
||||
speed=$(curl --socks5 "127.0.0.1:$SOCKS_PORT" -m 30 -s -o /dev/null \
|
||||
-w "%{speed_download}" \
|
||||
"https://speed.cloudflare.com/__down?bytes=10485760")
|
||||
if [ -z "$speed" ] || [ "$speed" = "0" ]; then
|
||||
echo "FAIL: throughput probe returned 0 B/s" >&2
|
||||
exit 1
|
||||
fi
|
||||
mbps=$(awk -v b="$speed" 'BEGIN { printf "%.2f", b * 8 / 1000000 }')
|
||||
echo "throughput=${mbps} Mbps"
|
||||
|
||||
echo "PASS: mode=$mode_arg"
|
||||
@@ -0,0 +1,33 @@
|
||||
module headless-wbstream-joiner
|
||||
|
||||
go 1.26.1
|
||||
|
||||
require whitelist-bypass/relay v0.0.0
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/pion/datachannel v1.6.0 // indirect
|
||||
github.com/pion/dtls/v3 v3.1.2 // indirect
|
||||
github.com/pion/ice/v4 v4.2.1 // 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/rtp v1.10.1 // indirect
|
||||
github.com/pion/sctp v1.9.2 // 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/pion/webrtc/v4 v4.2.9 // 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
|
||||
)
|
||||
|
||||
replace whitelist-bypass/relay => ../../relay
|
||||
@@ -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.1 h1:XPRYXaLiFq3LFDG7a7bMrmr3mFr27G/gtXN3v/TVfxY=
|
||||
github.com/pion/ice/v4 v4.2.1/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.2 h1:HxsOzEV9pWoeggv7T5kewVkstFNcGvhMPx0GvUOUQXo=
|
||||
github.com/pion/sctp v1.9.2/go.mod h1:OTOlsQ5EDQ6mQ0z4MUGXt2CgQmKyafBEXhUVqLRB6G8=
|
||||
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.9 h1:DZIh1HAhPIL3RvwEDFsmL5hfPSLEpxsQk9/Jir2vkJE=
|
||||
github.com/pion/webrtc/v4 v4.2.9/go.mod h1:9EmLZve0H76eTzf8v2FmchZ6tcBXtDgpfTEu+drW6SY=
|
||||
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=
|
||||
@@ -0,0 +1,97 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
"whitelist-bypass/relay/tunnel"
|
||||
"whitelist-bypass/relay/wbstream"
|
||||
)
|
||||
|
||||
func main() {
|
||||
roomFlag := flag.String("room", "", "WB Stream room id or wbstream://<id> (required)")
|
||||
displayName := flag.String("name", "Joiner", "display name in the room")
|
||||
socksPort := flag.Int("socks-port", 1080, "SOCKS5 listen port")
|
||||
socksUser := flag.String("socks-user", "", "SOCKS5 username (optional)")
|
||||
socksPass := flag.String("socks-pass", "", "SOCKS5 password (optional)")
|
||||
resources := flag.String("resources", "default", "resource mode: moderate, default, unlimited")
|
||||
tunnelMode := flag.String("tunnel-mode", "video", "tunnel mode: video, dc")
|
||||
vp8FPS := flag.Int("vp8-fps", 24, "VP8 frame rate (video mode only)")
|
||||
vp8Batch := flag.Int("vp8-batch", 30, "VP8 batch multiplier (video mode only)")
|
||||
flag.Parse()
|
||||
|
||||
if *roomFlag == "" {
|
||||
log.Fatal("--room is required")
|
||||
}
|
||||
|
||||
var memLimit int64
|
||||
switch *resources {
|
||||
case "moderate":
|
||||
memLimit = 64 << 20
|
||||
case "default":
|
||||
memLimit = 128 << 20
|
||||
case "unlimited":
|
||||
memLimit = 256 << 20
|
||||
default:
|
||||
log.Fatalf("[config] unknown resources mode: %s", *resources)
|
||||
}
|
||||
if memLimit > 0 {
|
||||
debug.SetMemoryLimit(memLimit)
|
||||
}
|
||||
common.MaskingEnabled = true
|
||||
|
||||
roomID := strings.TrimPrefix(strings.TrimSpace(*roomFlag), "wbstream://")
|
||||
id, roomToken, _, err := wbstream.AuthAndGetToken(nil, roomID, *displayName)
|
||||
if err != nil {
|
||||
log.Fatalf("[auth] %v", err)
|
||||
}
|
||||
log.Printf("[auth] room=%s mode=%s", id, *tunnelMode)
|
||||
|
||||
obf, err := tunnel.NewTunnelObfuscator(tunnel.DeriveSecretFromJoinLink(id))
|
||||
if err != nil {
|
||||
log.Fatalf("[obf] init failed: %v", err)
|
||||
}
|
||||
log.Printf("[obf] localEpoch=0x%08x", obf.LocalEpoch())
|
||||
|
||||
sess := wbstream.NewSession(wbstream.SessionConfig{
|
||||
RoomToken: roomToken,
|
||||
DisplayName: *displayName,
|
||||
TunnelMode: *tunnelMode,
|
||||
Obfuscator: obf,
|
||||
LogFn: log.Printf,
|
||||
VP8FPS: *vp8FPS,
|
||||
VP8Batch: *vp8Batch,
|
||||
})
|
||||
sess.OnConnected = func(tun tunnel.DataTunnel) {
|
||||
readBuf := common.VP8BufSize
|
||||
if _, ok := tun.(*tunnel.DCTunnel); ok {
|
||||
readBuf = common.DCBufSize
|
||||
}
|
||||
bridge := tunnel.NewRelayBridgeWithAuth(tun, "joiner", readBuf, log.Printf, *socksUser, *socksPass)
|
||||
bridge.MarkReady()
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", *socksPort)
|
||||
go func() {
|
||||
if err := bridge.ListenSOCKS(addr); err != nil {
|
||||
log.Printf("socks listen: %v", err)
|
||||
}
|
||||
}()
|
||||
fmt.Printf("\n TUNNEL CONNECTED (mode=%s)\n socks5 -> %s\n\n", *tunnelMode, addr)
|
||||
}
|
||||
|
||||
if err := sess.Start(); err != nil {
|
||||
log.Fatalf("[session] %v", err)
|
||||
}
|
||||
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
|
||||
<-sig
|
||||
log.Printf("[main] shutting down")
|
||||
sess.Close()
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
module headless-wbstream-creator
|
||||
|
||||
go 1.26.1
|
||||
|
||||
require whitelist-bypass/relay v0.0.0
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
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/rtp v1.10.1 // 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/pion/webrtc/v4 v4.2.11 // 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
|
||||
)
|
||||
|
||||
replace whitelist-bypass/relay => ../../relay
|
||||
@@ -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=
|
||||
@@ -0,0 +1,108 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
"whitelist-bypass/relay/tunnel"
|
||||
"whitelist-bypass/relay/wbstream"
|
||||
)
|
||||
|
||||
func main() {
|
||||
roomFlag := flag.String("room", "", "WB Stream room id or wbstream://<id> (empty = create new)")
|
||||
displayName := flag.String("name", "Headless", "display name in the room")
|
||||
resources := flag.String("resources", "default", "resource mode: moderate, default, unlimited")
|
||||
writeFile := flag.String("write-file", "", "path to file where active room id is appended")
|
||||
flag.Parse()
|
||||
|
||||
var memLimit int64
|
||||
switch *resources {
|
||||
case "moderate":
|
||||
memLimit = 64 << 20
|
||||
case "default":
|
||||
memLimit = 128 << 20
|
||||
case "unlimited":
|
||||
memLimit = 256 << 20
|
||||
default:
|
||||
log.Fatalf("[config] unknown resources mode: %s", *resources)
|
||||
}
|
||||
if memLimit > 0 {
|
||||
debug.SetMemoryLimit(memLimit)
|
||||
}
|
||||
common.MaskingEnabled = true
|
||||
log.Printf("[config] resources=%s mem-limit=%d", *resources, memLimit)
|
||||
|
||||
requestedRoom := strings.TrimPrefix(strings.TrimSpace(*roomFlag), "wbstream://")
|
||||
roomID, roomToken, accessToken, err := wbstream.AuthAndGetToken(nil, requestedRoom, *displayName)
|
||||
if err != nil {
|
||||
log.Fatalf("[auth] %v", err)
|
||||
}
|
||||
log.Printf("[auth] room=%s", roomID)
|
||||
|
||||
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, "wbstream://"+roomID)
|
||||
f.Close()
|
||||
log.Printf("[config] Wrote join link to %s", *writeFile)
|
||||
}
|
||||
|
||||
obf, err := tunnel.NewTunnelObfuscator(tunnel.DeriveSecretFromJoinLink(roomID))
|
||||
if err != nil {
|
||||
log.Fatalf("[obf] init failed: %v", err)
|
||||
}
|
||||
log.Printf("[obf] key-source=%q localEpoch=0x%08x", roomID, obf.LocalEpoch())
|
||||
|
||||
sess := wbstream.NewSession(wbstream.SessionConfig{
|
||||
RoomToken: roomToken,
|
||||
DisplayName: *displayName,
|
||||
Obfuscator: obf,
|
||||
LogFn: log.Printf,
|
||||
RoomID: roomID,
|
||||
AccessToken: accessToken,
|
||||
})
|
||||
var activeBridge *tunnel.RelayBridge
|
||||
sess.OnConnected = func(tun tunnel.DataTunnel) {
|
||||
if activeBridge != nil {
|
||||
activeBridge.Reset()
|
||||
}
|
||||
readBuf := common.VP8BufSize
|
||||
mode := "video"
|
||||
if _, ok := tun.(*tunnel.DCTunnel); ok {
|
||||
readBuf = common.DCBufSize
|
||||
mode = "dc"
|
||||
}
|
||||
activeBridge = tunnel.NewRelayBridge(tun, "creator", readBuf, log.Printf)
|
||||
fmt.Printf("\n TUNNEL CONNECTED (mode=%s)\n", mode)
|
||||
}
|
||||
sess.OnPeerRestart = func() {
|
||||
if activeBridge != nil {
|
||||
log.Printf("[creator] new peer detected, resetting relay bridge")
|
||||
activeBridge.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("")
|
||||
fmt.Println(" CALL CREATED")
|
||||
fmt.Println(" join_link: wbstream://" + roomID)
|
||||
fmt.Println("")
|
||||
|
||||
if err := sess.Start(); err != nil {
|
||||
log.Fatalf("[session] %v", err)
|
||||
}
|
||||
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
|
||||
<-sig
|
||||
log.Printf("[main] shutting down")
|
||||
sess.Close()
|
||||
}
|
||||
@@ -9,7 +9,6 @@ enum DefaultsKeys {
|
||||
static let socksAuthMode = "socksAuthMode"
|
||||
static let socksUser = "socksUser"
|
||||
static let socksPass = "socksPass"
|
||||
static let vp8PacingEnabled = "vp8PacingEnabled"
|
||||
static let vp8Fps = "vp8Fps"
|
||||
static let vp8Batch = "vp8Batch"
|
||||
}
|
||||
@@ -62,11 +61,6 @@ struct AppDefaults {
|
||||
set { defaults.set(newValue, forKey: DefaultsKeys.socksPass) }
|
||||
}
|
||||
|
||||
static var vp8PacingEnabled: Bool {
|
||||
get { defaults.object(forKey: DefaultsKeys.vp8PacingEnabled) as? Bool ?? false }
|
||||
set { defaults.set(newValue, forKey: DefaultsKeys.vp8PacingEnabled) }
|
||||
}
|
||||
|
||||
static var vp8Fps: Int {
|
||||
get { defaults.object(forKey: DefaultsKeys.vp8Fps) as? Int ?? VP8Defaults.fps }
|
||||
set { defaults.set(newValue, forKey: DefaultsKeys.vp8Fps) }
|
||||
|
||||
@@ -230,24 +230,21 @@ struct SettingsView: View {
|
||||
}
|
||||
|
||||
Section(NSLocalizedString("settings_vp8_pacing", comment: "")) {
|
||||
Toggle(NSLocalizedString("settings_vp8_pacing_enabled", comment: ""), isOn: $proxyManager.vp8PacingEnabled)
|
||||
if proxyManager.vp8PacingEnabled {
|
||||
HStack {
|
||||
Text(NSLocalizedString("settings_vp8_fps", comment: ""))
|
||||
Spacer()
|
||||
TextField("", value: $proxyManager.vp8Fps, format: .number)
|
||||
.keyboardType(.numberPad)
|
||||
.multilineTextAlignment(.trailing)
|
||||
.frame(width: 80)
|
||||
}
|
||||
HStack {
|
||||
Text(NSLocalizedString("settings_vp8_batch", comment: ""))
|
||||
Spacer()
|
||||
TextField("", value: $proxyManager.vp8Batch, format: .number)
|
||||
.keyboardType(.numberPad)
|
||||
.multilineTextAlignment(.trailing)
|
||||
.frame(width: 80)
|
||||
}
|
||||
HStack {
|
||||
Text(NSLocalizedString("settings_vp8_fps", comment: ""))
|
||||
Spacer()
|
||||
TextField("", value: $proxyManager.vp8Fps, format: .number)
|
||||
.keyboardType(.numberPad)
|
||||
.multilineTextAlignment(.trailing)
|
||||
.frame(width: 80)
|
||||
}
|
||||
HStack {
|
||||
Text(NSLocalizedString("settings_vp8_batch", comment: ""))
|
||||
Spacer()
|
||||
TextField("", value: $proxyManager.vp8Batch, format: .number)
|
||||
.keyboardType(.numberPad)
|
||||
.multilineTextAlignment(.trailing)
|
||||
.frame(width: 80)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
"btn_go" = "Go";
|
||||
"btn_done" = "Done";
|
||||
"btn_open_in_telegram" = "Open in Telegram";
|
||||
"hint_call_link" = "VK or Telemost call link";
|
||||
"hint_call_link" = "VK / Telemost link or wbstream://<room-id>";
|
||||
"hint_username" = "Username";
|
||||
"hint_password" = "Password";
|
||||
"hint_display_name" = "Display Name";
|
||||
@@ -25,7 +25,6 @@
|
||||
"settings_display" = "Display";
|
||||
"settings_show_logs" = "Show Logs";
|
||||
"settings_vp8_pacing" = "VP8 Pacing";
|
||||
"settings_vp8_pacing_enabled" = "Override VP8 Pacing";
|
||||
"settings_vp8_fps" = "FPS";
|
||||
"settings_vp8_batch" = "Batch";
|
||||
"proxy_url_copied" = "Proxy URL copied";
|
||||
|
||||
@@ -117,13 +117,26 @@ enum TunnelMode: String, CaseIterable {
|
||||
enum CallPlatform: String {
|
||||
case vk = "vk"
|
||||
case telemost = "telemost"
|
||||
case wbstream = "wbstream"
|
||||
|
||||
static let wbstreamPrefix = "wbstream://"
|
||||
|
||||
static func detect(url: String) -> CallPlatform {
|
||||
if url.hasPrefix(wbstreamPrefix) {
|
||||
return .wbstream
|
||||
}
|
||||
if url.contains("telemost.yandex") {
|
||||
return .telemost
|
||||
}
|
||||
return .vk
|
||||
}
|
||||
|
||||
static func extractRoomId(url: String) -> String {
|
||||
if url.hasPrefix(wbstreamPrefix) {
|
||||
return String(url.dropFirst(wbstreamPrefix.count)).trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
return url.trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
}
|
||||
|
||||
class ProxyManager: ObservableObject {
|
||||
@@ -143,7 +156,6 @@ class ProxyManager: ObservableObject {
|
||||
@Published var socksAuthMode: SocksAuthMode = AppDefaults.socksAuthMode { didSet { AppDefaults.socksAuthMode = socksAuthMode } }
|
||||
@Published var manualSocksUser: String = AppDefaults.socksUser { didSet { AppDefaults.socksUser = manualSocksUser } }
|
||||
@Published var manualSocksPass: String = AppDefaults.socksPass { didSet { AppDefaults.socksPass = manualSocksPass } }
|
||||
@Published var vp8PacingEnabled: Bool = AppDefaults.vp8PacingEnabled { didSet { AppDefaults.vp8PacingEnabled = vp8PacingEnabled } }
|
||||
@Published var vp8Fps: Int = AppDefaults.vp8Fps { didSet { AppDefaults.vp8Fps = vp8Fps } }
|
||||
@Published var vp8Batch: Int = AppDefaults.vp8Batch { didSet { AppDefaults.vp8Batch = vp8Batch } }
|
||||
|
||||
@@ -258,7 +270,7 @@ class ProxyManager: ObservableObject {
|
||||
detectedPlatform = CallPlatform.detect(url: callUrl)
|
||||
appendLog("Platform: \(detectedPlatform.rawValue)")
|
||||
|
||||
if tunnelMode == .dc && detectedPlatform != .vk {
|
||||
if tunnelMode == .dc && detectedPlatform == .telemost {
|
||||
tunnelMode = .video
|
||||
showToast(NSLocalizedString("dc_mode_not_supported", comment: ""))
|
||||
}
|
||||
@@ -267,14 +279,12 @@ class ProxyManager: ObservableObject {
|
||||
case .telemost:
|
||||
IosStartTelemostHeadless(socksPort, activeSocksUser, activeSocksPass, bridge)
|
||||
appendLog("Started Telemost headless joiner")
|
||||
var joinParams: [String: Any] = [
|
||||
let joinParams: [String: Any] = [
|
||||
"joinLink": callUrl,
|
||||
"displayName": displayName,
|
||||
"vp8Fps": vp8Fps,
|
||||
"vp8Batch": vp8Batch,
|
||||
]
|
||||
if vp8PacingEnabled {
|
||||
joinParams["vp8Fps"] = vp8Fps
|
||||
joinParams["vp8Batch"] = vp8Batch
|
||||
}
|
||||
if let jsonData = try? JSONSerialization.data(withJSONObject: joinParams),
|
||||
let jsonString = String(data: jsonData, encoding: .utf8) {
|
||||
IosSendJoinParams(jsonString)
|
||||
@@ -282,10 +292,24 @@ class ProxyManager: ObservableObject {
|
||||
}
|
||||
|
||||
case .vk:
|
||||
let fps = vp8PacingEnabled ? vp8Fps : 0
|
||||
let batch = vp8PacingEnabled ? vp8Batch : 0
|
||||
IosStartVKHeadless(socksPort, activeSocksUser, activeSocksPass, callUrl, displayName, tunnelMode.rawValue, fps, batch, bridge)
|
||||
IosStartVKHeadless(socksPort, activeSocksUser, activeSocksPass, callUrl, displayName, tunnelMode.rawValue, vp8Fps, vp8Batch, bridge)
|
||||
appendLog("Started VK headless joiner")
|
||||
|
||||
case .wbstream:
|
||||
IosStartWBStreamHeadless(socksPort, activeSocksUser, activeSocksPass, bridge)
|
||||
appendLog("Started WB Stream headless joiner")
|
||||
let joinParams: [String: Any] = [
|
||||
"roomId": CallPlatform.extractRoomId(url: callUrl),
|
||||
"displayName": displayName,
|
||||
"tunnelMode": tunnelMode.rawValue,
|
||||
"vp8Fps": vp8Fps,
|
||||
"vp8Batch": vp8Batch,
|
||||
]
|
||||
if let jsonData = try? JSONSerialization.data(withJSONObject: joinParams),
|
||||
let jsonString = String(data: jsonData, encoding: .utf8) {
|
||||
IosSendJoinParams(jsonString)
|
||||
appendLog("Sent join params")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
package livekit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/pion/webrtc/v4"
|
||||
"whitelist-bypass/relay/common"
|
||||
)
|
||||
|
||||
const (
|
||||
ProtocolVersion = "15"
|
||||
SDKName = "js"
|
||||
SDKVersion = "2.7.0"
|
||||
PingPeriod = 5 * time.Second
|
||||
|
||||
TargetPublisher = signalTargetPublisher
|
||||
TargetSubscriber = signalTargetSubscriber
|
||||
|
||||
TrackTypeAudio = trackTypeAudio
|
||||
TrackTypeVideo = trackTypeVideo
|
||||
TrackTypeData = trackTypeData
|
||||
TrackSourceCamera = trackSourceCamera
|
||||
)
|
||||
|
||||
type ICEServer = iceServer
|
||||
type JoinResponse = joinResponse
|
||||
|
||||
type Config struct {
|
||||
ServerURL string
|
||||
Token string
|
||||
Origin string
|
||||
UserAgent string
|
||||
LogFn func(string, ...any)
|
||||
SettingEngine *webrtc.SettingEngine
|
||||
NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
ResolveICEHost func(host string) (string, error)
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
logFn func(string, ...any)
|
||||
|
||||
wsURL string
|
||||
token string
|
||||
origin string
|
||||
ua string
|
||||
|
||||
settingEngine *webrtc.SettingEngine
|
||||
netDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
resolveICEHost func(host string) (string, error)
|
||||
|
||||
ws *websocket.Conn
|
||||
wsMu sync.Mutex
|
||||
|
||||
join JoinResponse
|
||||
|
||||
pubPC *webrtc.PeerConnection
|
||||
subPC *webrtc.PeerConnection
|
||||
pubMu sync.Mutex
|
||||
subMu sync.Mutex
|
||||
pubRemoteSet bool
|
||||
subRemoteSet bool
|
||||
|
||||
closed atomic.Bool
|
||||
|
||||
OnReady func()
|
||||
OnTrack func(*webrtc.TrackRemote, *webrtc.RTPReceiver)
|
||||
OnDataChannel func(*webrtc.DataChannel)
|
||||
OnPubConnected func()
|
||||
OnParticipantUpdate func([]ParticipantInfo)
|
||||
}
|
||||
|
||||
func NewClient(cfg Config) *Client {
|
||||
logFn := cfg.LogFn
|
||||
if logFn == nil {
|
||||
logFn = func(string, ...any) {}
|
||||
}
|
||||
return &Client{
|
||||
logFn: logFn,
|
||||
wsURL: cfg.ServerURL,
|
||||
token: cfg.Token,
|
||||
origin: cfg.Origin,
|
||||
ua: cfg.UserAgent,
|
||||
settingEngine: cfg.SettingEngine,
|
||||
netDialContext: cfg.NetDialContext,
|
||||
resolveICEHost: cfg.ResolveICEHost,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Join() JoinResponse { return c.join }
|
||||
func (c *Client) PubPC() *webrtc.PeerConnection { return c.pubPC }
|
||||
func (c *Client) SubPC() *webrtc.PeerConnection { return c.subPC }
|
||||
|
||||
func (c *Client) Connect() error {
|
||||
u, err := url.Parse(c.wsURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse url: %w", err)
|
||||
}
|
||||
u.Path = "/rtc"
|
||||
q := u.Query()
|
||||
q.Set("access_token", c.token)
|
||||
q.Set("protocol", ProtocolVersion)
|
||||
q.Set("sdk", SDKName)
|
||||
q.Set("version", SDKVersion)
|
||||
q.Set("auto_subscribe", "1")
|
||||
q.Set("adaptive_stream", "true")
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
headers := http.Header{}
|
||||
if c.ua != "" {
|
||||
headers.Set("User-Agent", c.ua)
|
||||
}
|
||||
if c.origin != "" {
|
||||
headers.Set("Origin", c.origin)
|
||||
}
|
||||
|
||||
dialer := *websocket.DefaultDialer
|
||||
if c.netDialContext != nil {
|
||||
dialer.NetDialContext = c.netDialContext
|
||||
}
|
||||
conn, resp, err := dialer.Dial(u.String(), headers)
|
||||
if err != nil {
|
||||
if resp != nil {
|
||||
return fmt.Errorf("ws dial: %w (status %d)", err, resp.StatusCode)
|
||||
}
|
||||
return fmt.Errorf("ws dial: %w", err)
|
||||
}
|
||||
c.ws = conn
|
||||
c.logFn("[lk] signaling connected")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) sendSignal(payload []byte) error {
|
||||
c.wsMu.Lock()
|
||||
defer c.wsMu.Unlock()
|
||||
if c.ws == nil {
|
||||
return fmt.Errorf("ws not connected")
|
||||
}
|
||||
return c.ws.WriteMessage(websocket.BinaryMessage, payload)
|
||||
}
|
||||
|
||||
func (c *Client) SendOffer(sdp string) error {
|
||||
return c.sendSignal(encSignalRequestOffer(sessionDescription{Type: "offer", SDP: sdp}))
|
||||
}
|
||||
|
||||
func (c *Client) SendAnswer(sdp string) error {
|
||||
return c.sendSignal(encSignalRequestAnswer(sessionDescription{Type: "answer", SDP: sdp}))
|
||||
}
|
||||
|
||||
func (c *Client) SendTrickle(candidate webrtc.ICECandidateInit, target int) error {
|
||||
js, _ := json.Marshal(candidate)
|
||||
return c.sendSignal(encSignalRequestTrickle(trickleMsg{
|
||||
CandidateInit: string(js),
|
||||
Target: target,
|
||||
}))
|
||||
}
|
||||
|
||||
func (c *Client) SendAddTrack(cid, name string, trackType, source int, width, height uint32) error {
|
||||
return c.sendSignal(encSignalRequestAddTrack(cid, name, trackType, source, width, height))
|
||||
}
|
||||
|
||||
func (c *Client) SendLeave() error { return c.sendSignal(encSignalRequestLeave()) }
|
||||
|
||||
func (c *Client) SendPing() error {
|
||||
return c.sendSignal(encSignalRequestPing(time.Now().UnixMilli()))
|
||||
}
|
||||
|
||||
func (c *Client) Close() {
|
||||
if !c.closed.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
c.wsMu.Lock()
|
||||
ws := c.ws
|
||||
c.wsMu.Unlock()
|
||||
if ws != nil {
|
||||
_ = ws.Close()
|
||||
}
|
||||
if c.pubPC != nil {
|
||||
_ = c.pubPC.Close()
|
||||
}
|
||||
if c.subPC != nil {
|
||||
_ = c.subPC.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) iceServersAsWebRTC() []webrtc.ICEServer {
|
||||
out := make([]webrtc.ICEServer, 0, len(c.join.ICEServers))
|
||||
resolved := make(map[string]string)
|
||||
for _, s := range c.join.ICEServers {
|
||||
urls := make([]string, len(s.URLs))
|
||||
copy(urls, s.URLs)
|
||||
if c.resolveICEHost != nil {
|
||||
for k, u := range urls {
|
||||
host := common.ExtractICEHost(u)
|
||||
if host == "" || net.ParseIP(host) != nil {
|
||||
continue
|
||||
}
|
||||
ip, ok := resolved[host]
|
||||
if !ok {
|
||||
var err error
|
||||
ip, err = c.resolveICEHost(host)
|
||||
if err != nil {
|
||||
c.logFn("[lk] resolve ICE host %s failed: %v", host, err)
|
||||
continue
|
||||
}
|
||||
resolved[host] = ip
|
||||
c.logFn("[lk] resolved ICE host %s -> %s", host, ip)
|
||||
}
|
||||
urls[k] = strings.Replace(u, host, ip, 1)
|
||||
}
|
||||
}
|
||||
ice := webrtc.ICEServer{URLs: urls}
|
||||
if s.Username != "" {
|
||||
ice.Username = s.Username
|
||||
ice.Credential = s.Credential
|
||||
}
|
||||
out = append(out, ice)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *Client) buildPeerConnections() error {
|
||||
cfg := webrtc.Configuration{ICEServers: c.iceServersAsWebRTC()}
|
||||
|
||||
se := webrtc.SettingEngine{}
|
||||
if c.settingEngine != nil {
|
||||
se = *c.settingEngine
|
||||
}
|
||||
se.DetachDataChannels()
|
||||
api := webrtc.NewAPI(webrtc.WithSettingEngine(se))
|
||||
|
||||
pubPC, err := api.NewPeerConnection(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create pub pc: %w", err)
|
||||
}
|
||||
subPC, err := api.NewPeerConnection(cfg)
|
||||
if err != nil {
|
||||
_ = pubPC.Close()
|
||||
return fmt.Errorf("create sub pc: %w", err)
|
||||
}
|
||||
|
||||
c.pubPC = pubPC
|
||||
c.subPC = subPC
|
||||
|
||||
pubPC.OnICECandidate(func(cand *webrtc.ICECandidate) {
|
||||
if cand == nil {
|
||||
c.logFn("[lk] pub ICE gathering complete")
|
||||
return
|
||||
}
|
||||
c.logFn("[lk] pub local cand: %s", cand.String())
|
||||
_ = c.SendTrickle(cand.ToJSON(), TargetPublisher)
|
||||
})
|
||||
subPC.OnICECandidate(func(cand *webrtc.ICECandidate) {
|
||||
if cand == nil {
|
||||
c.logFn("[lk] sub ICE gathering complete")
|
||||
return
|
||||
}
|
||||
c.logFn("[lk] sub local cand: %s", cand.String())
|
||||
_ = c.SendTrickle(cand.ToJSON(), TargetSubscriber)
|
||||
})
|
||||
|
||||
pubPC.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
|
||||
c.logFn("[lk] pub PC state: %s", state.String())
|
||||
if state == webrtc.PeerConnectionStateConnected && c.OnPubConnected != nil {
|
||||
c.OnPubConnected()
|
||||
}
|
||||
})
|
||||
subPC.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
|
||||
c.logFn("[lk] sub PC state: %s", state.String())
|
||||
})
|
||||
pubPC.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
|
||||
c.logFn("[lk] pub ICE state: %s", state.String())
|
||||
})
|
||||
subPC.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
|
||||
c.logFn("[lk] sub ICE state: %s", state.String())
|
||||
})
|
||||
|
||||
subPC.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
|
||||
c.logFn("[lk] sub remote track: %s", track.Codec().MimeType)
|
||||
if c.OnTrack != nil {
|
||||
c.OnTrack(track, receiver)
|
||||
}
|
||||
})
|
||||
subPC.OnDataChannel(func(dc *webrtc.DataChannel) {
|
||||
c.logFn("[lk] sub data channel: %s", dc.Label())
|
||||
if c.OnDataChannel != nil {
|
||||
c.OnDataChannel(dc)
|
||||
}
|
||||
})
|
||||
|
||||
c.logFn("[lk] PCs created (%d ICE servers)", len(c.join.ICEServers))
|
||||
for i, s := range c.join.ICEServers {
|
||||
c.logFn("[lk] iceServer[%d]: urls=%v hasCred=%v", i, s.URLs, s.Username != "")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) handleSignal(data []byte) {
|
||||
sr, err := decSignalResponse(data)
|
||||
if err != nil {
|
||||
c.logFn("[lk] decode signal: %v", err)
|
||||
return
|
||||
}
|
||||
switch sr.Kind {
|
||||
case signalRespJoin:
|
||||
if sr.Join != nil {
|
||||
c.join = *sr.Join
|
||||
c.logFn("[lk] join: room=%s participant=%s subscriberPrimary=%v iceServers=%d pingTimeout=%ds pingInterval=%ds",
|
||||
c.join.RoomName, c.join.ParticipantID, c.join.SubscriberPrimary, len(c.join.ICEServers),
|
||||
c.join.PingTimeoutSec, c.join.PingIntervalSec)
|
||||
if err := c.buildPeerConnections(); err != nil {
|
||||
c.logFn("[lk] %v", err)
|
||||
return
|
||||
}
|
||||
if c.OnReady != nil {
|
||||
c.OnReady()
|
||||
}
|
||||
}
|
||||
case signalRespAnswer:
|
||||
c.logFn("[lk] <- pub answer (%d bytes)", len(sr.SDP.SDP))
|
||||
if sr.SDP != nil {
|
||||
c.applyPubAnswer(sr.SDP.SDP)
|
||||
}
|
||||
case signalRespOffer:
|
||||
c.logFn("[lk] <- sub offer (%d bytes)", len(sr.SDP.SDP))
|
||||
if sr.SDP != nil {
|
||||
c.applySubOfferAndAnswer(sr.SDP.SDP)
|
||||
}
|
||||
case signalRespTrickle:
|
||||
if sr.Trickle != nil {
|
||||
c.logFn("[lk] <- trickle target=%d", sr.Trickle.Target)
|
||||
c.applyRemoteTrickle(*sr.Trickle)
|
||||
}
|
||||
case signalRespRefreshToken:
|
||||
if sr.Token != "" {
|
||||
c.token = sr.Token
|
||||
c.logFn("[lk] token refreshed")
|
||||
}
|
||||
case signalRespLeave:
|
||||
if sr.Leave != nil {
|
||||
c.logFn("[lk] ignored leave reason=%s action=%s",
|
||||
DisconnectReasonName(sr.Leave.Reason), LeaveActionName(sr.Leave.Action))
|
||||
} else {
|
||||
c.logFn("[lk] ignored leave")
|
||||
}
|
||||
case signalRespUpdate:
|
||||
if c.OnParticipantUpdate != nil && len(sr.Participants) > 0 {
|
||||
c.OnParticipantUpdate(sr.Participants)
|
||||
}
|
||||
default:
|
||||
c.logFn("[lk] <- signal kind=%d (%d bytes)", sr.Kind, len(data))
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) applyPubAnswer(sdp string) {
|
||||
c.pubMu.Lock()
|
||||
defer c.pubMu.Unlock()
|
||||
if c.pubPC == nil {
|
||||
return
|
||||
}
|
||||
if err := c.pubPC.SetRemoteDescription(webrtc.SessionDescription{Type: webrtc.SDPTypeAnswer, SDP: sdp}); err != nil {
|
||||
c.logFn("[lk] set pub remote answer: %v", err)
|
||||
return
|
||||
}
|
||||
c.pubRemoteSet = true
|
||||
}
|
||||
|
||||
func (c *Client) applySubOfferAndAnswer(sdp string) {
|
||||
c.subMu.Lock()
|
||||
defer c.subMu.Unlock()
|
||||
if c.subPC == nil {
|
||||
return
|
||||
}
|
||||
if err := c.subPC.SetRemoteDescription(webrtc.SessionDescription{Type: webrtc.SDPTypeOffer, SDP: sdp}); err != nil {
|
||||
c.logFn("[lk] set sub remote offer: %v", err)
|
||||
return
|
||||
}
|
||||
c.subRemoteSet = true
|
||||
answer, err := c.subPC.CreateAnswer(nil)
|
||||
if err != nil {
|
||||
c.logFn("[lk] create sub answer: %v", err)
|
||||
return
|
||||
}
|
||||
if err := c.subPC.SetLocalDescription(answer); err != nil {
|
||||
c.logFn("[lk] set sub local answer: %v", err)
|
||||
return
|
||||
}
|
||||
if err := c.SendAnswer(answer.SDP); err != nil {
|
||||
c.logFn("[lk] send answer: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) applyRemoteTrickle(m trickleMsg) {
|
||||
if m.CandidateInit == "" {
|
||||
return
|
||||
}
|
||||
var ic webrtc.ICECandidateInit
|
||||
if err := json.Unmarshal([]byte(m.CandidateInit), &ic); err != nil {
|
||||
c.logFn("[lk] decode trickle candidate: %v", err)
|
||||
return
|
||||
}
|
||||
switch m.Target {
|
||||
case TargetPublisher:
|
||||
c.pubMu.Lock()
|
||||
ready := c.pubRemoteSet
|
||||
c.pubMu.Unlock()
|
||||
if ready {
|
||||
_ = c.pubPC.AddICECandidate(ic)
|
||||
}
|
||||
case TargetSubscriber:
|
||||
c.subMu.Lock()
|
||||
ready := c.subRemoteSet
|
||||
c.subMu.Unlock()
|
||||
if ready {
|
||||
_ = c.subPC.AddICECandidate(ic)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) ReadLoop() error {
|
||||
defer c.Close()
|
||||
for {
|
||||
mt, data, err := c.ws.ReadMessage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mt != websocket.BinaryMessage {
|
||||
continue
|
||||
}
|
||||
c.handleSignal(data)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) PingLoop() {
|
||||
period := PingPeriod
|
||||
if c.join.PingIntervalSec > 0 {
|
||||
period = time.Duration(c.join.PingIntervalSec) * time.Second
|
||||
}
|
||||
t := time.NewTicker(period)
|
||||
defer t.Stop()
|
||||
var sentN int
|
||||
for range t.C {
|
||||
if c.closed.Load() {
|
||||
return
|
||||
}
|
||||
if err := c.SendPing(); err != nil {
|
||||
c.logFn("[lk] ping send failed: %v", err)
|
||||
return
|
||||
}
|
||||
sentN++
|
||||
if sentN <= 3 || sentN%12 == 0 {
|
||||
c.logFn("[lk] ping #%d sent", sentN)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,707 @@
|
||||
package livekit
|
||||
|
||||
import "fmt"
|
||||
|
||||
const (
|
||||
signalReqOffer = 1
|
||||
signalReqAnswer = 2
|
||||
signalReqTrickle = 3
|
||||
signalReqAddTrack = 4
|
||||
signalReqLeave = 8
|
||||
signalReqPingLegacy = 14
|
||||
signalReqPingReq = 16
|
||||
|
||||
signalRespJoin = 1
|
||||
signalRespAnswer = 2
|
||||
signalRespOffer = 3
|
||||
signalRespTrickle = 4
|
||||
signalRespUpdate = 5
|
||||
signalRespTrackPublished = 6
|
||||
signalRespLeave = 8
|
||||
signalRespRoomUpdate = 11
|
||||
signalRespRefreshToken = 16
|
||||
signalRespPongResp = 20
|
||||
signalRespRequestResponse = 22
|
||||
signalRespTrackSubscribed = 23
|
||||
|
||||
sdpFieldType = 1
|
||||
sdpFieldSDP = 2
|
||||
sdpFieldID = 3
|
||||
|
||||
trickleFieldCandidate = 1
|
||||
trickleFieldTarget = 2
|
||||
trickleFieldFinal = 3
|
||||
|
||||
addTrackFieldCID = 1
|
||||
addTrackFieldName = 2
|
||||
addTrackFieldType = 3
|
||||
addTrackFieldWidth = 4
|
||||
addTrackFieldHeight = 5
|
||||
addTrackFieldSource = 8
|
||||
addTrackFieldLayers = 9
|
||||
|
||||
videoLayerFieldQuality = 1
|
||||
videoLayerFieldWidth = 2
|
||||
videoLayerFieldHeight = 3
|
||||
|
||||
videoQualityHigh = 2
|
||||
|
||||
joinFieldRoom = 1
|
||||
joinFieldParticipant = 2
|
||||
joinFieldOtherParticipants = 3
|
||||
joinFieldServerVersion = 4
|
||||
joinFieldICEServers = 5
|
||||
joinFieldSubscriberPrimary = 6
|
||||
joinFieldServerRegion = 9
|
||||
joinFieldPingTimeout = 10
|
||||
joinFieldPingInterval = 11
|
||||
|
||||
iceServerFieldURLs = 1
|
||||
iceServerFieldUsername = 2
|
||||
iceServerFieldCredential = 3
|
||||
|
||||
pingFieldTimestamp = 1
|
||||
pingFieldRTT = 2
|
||||
|
||||
dataPacketFieldKind = 1
|
||||
dataPacketFieldUser = 2
|
||||
|
||||
userPacketFieldPayload = 2
|
||||
|
||||
DataPacketKindReliable = 0
|
||||
DataPacketKindLossy = 1
|
||||
|
||||
leaveFieldCanReconnect = 1
|
||||
leaveFieldReason = 2
|
||||
leaveFieldAction = 3
|
||||
|
||||
roomFieldSID = 1
|
||||
roomFieldName = 2
|
||||
|
||||
participantFieldSID = 1
|
||||
participantFieldIdentity = 2
|
||||
participantFieldState = 3
|
||||
participantFieldName = 9
|
||||
|
||||
trackTypeAudio = 0
|
||||
trackTypeVideo = 1
|
||||
trackTypeData = 2
|
||||
|
||||
signalTargetPublisher = 0
|
||||
signalTargetSubscriber = 1
|
||||
)
|
||||
|
||||
var disconnectReasonNames = map[int]string{
|
||||
0: "UNKNOWN",
|
||||
1: "CLIENT_INITIATED",
|
||||
2: "DUPLICATE_IDENTITY",
|
||||
3: "SERVER_SHUTDOWN",
|
||||
4: "PARTICIPANT_REMOVED",
|
||||
5: "ROOM_DELETED",
|
||||
6: "STATE_MISMATCH",
|
||||
7: "JOIN_FAILURE",
|
||||
8: "MIGRATION",
|
||||
9: "SIGNAL_CLOSE",
|
||||
10: "ROOM_CLOSED",
|
||||
11: "USER_UNAVAILABLE",
|
||||
12: "USER_REJECTED",
|
||||
13: "SIP_TRUNK_FAILURE",
|
||||
14: "CONNECTION_TIMEOUT",
|
||||
15: "MEDIA_FAILURE",
|
||||
16: "AGENT_ERROR",
|
||||
}
|
||||
|
||||
var leaveActionNames = map[int]string{
|
||||
0: "DISCONNECT",
|
||||
1: "RESUME",
|
||||
2: "RECONNECT",
|
||||
}
|
||||
|
||||
func DisconnectReasonName(code int) string {
|
||||
if name, ok := disconnectReasonNames[code]; ok {
|
||||
return name
|
||||
}
|
||||
return fmt.Sprintf("CODE_%d", code)
|
||||
}
|
||||
|
||||
func LeaveActionName(code int) string {
|
||||
if name, ok := leaveActionNames[code]; ok {
|
||||
return name
|
||||
}
|
||||
return fmt.Sprintf("CODE_%d", code)
|
||||
}
|
||||
|
||||
type LeaveInfo struct {
|
||||
Reason int
|
||||
Action int
|
||||
}
|
||||
|
||||
func DecodeLeaveRequest(data []byte) LeaveInfo {
|
||||
r := pbReader{buf: data}
|
||||
var li LeaveInfo
|
||||
for !r.eof() {
|
||||
field, wire, err := r.tag()
|
||||
if err != nil {
|
||||
return li
|
||||
}
|
||||
switch {
|
||||
case field == leaveFieldReason && wire == wireVarint:
|
||||
v, _ := r.varint()
|
||||
li.Reason = int(v)
|
||||
case field == leaveFieldAction && wire == wireVarint:
|
||||
v, _ := r.varint()
|
||||
li.Action = int(v)
|
||||
default:
|
||||
if err := r.skipWire(wire); err != nil {
|
||||
return li
|
||||
}
|
||||
}
|
||||
}
|
||||
return li
|
||||
}
|
||||
|
||||
type sessionDescription struct {
|
||||
Type string
|
||||
SDP string
|
||||
ID uint32
|
||||
}
|
||||
|
||||
type trickleMsg struct {
|
||||
CandidateInit string
|
||||
Target int
|
||||
Final bool
|
||||
}
|
||||
|
||||
type iceServer struct {
|
||||
URLs []string
|
||||
Username string
|
||||
Credential string
|
||||
}
|
||||
|
||||
type joinResponse struct {
|
||||
RoomSID string
|
||||
RoomName string
|
||||
ParticipantSID string
|
||||
ParticipantID string
|
||||
ServerVersion string
|
||||
ServerRegion string
|
||||
ICEServers []iceServer
|
||||
SubscriberPrimary bool
|
||||
PingTimeoutSec int32
|
||||
PingIntervalSec int32
|
||||
}
|
||||
|
||||
type signalResponse struct {
|
||||
Kind int
|
||||
Join *joinResponse
|
||||
SDP *sessionDescription
|
||||
Trickle *trickleMsg
|
||||
Token string
|
||||
PongTime int64
|
||||
Leave *LeaveInfo
|
||||
Participants []ParticipantInfo
|
||||
}
|
||||
|
||||
func encSessionDescription(sd sessionDescription) []byte {
|
||||
w := pbWriter{}
|
||||
if sd.Type != "" {
|
||||
w.string(sdpFieldType, sd.Type)
|
||||
}
|
||||
if sd.SDP != "" {
|
||||
w.string(sdpFieldSDP, sd.SDP)
|
||||
}
|
||||
if sd.ID != 0 {
|
||||
w.uint32(sdpFieldID, sd.ID)
|
||||
}
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func encTrickle(m trickleMsg) []byte {
|
||||
w := pbWriter{}
|
||||
w.string(trickleFieldCandidate, m.CandidateInit)
|
||||
w.int32(trickleFieldTarget, int32(m.Target))
|
||||
if m.Final {
|
||||
w.bool(trickleFieldFinal, true)
|
||||
}
|
||||
return w.buf
|
||||
}
|
||||
|
||||
const trackSourceCamera = 1
|
||||
|
||||
func encVideoLayer(quality, width, height uint32) []byte {
|
||||
w := pbWriter{}
|
||||
if quality != 0 {
|
||||
w.uint32(videoLayerFieldQuality, quality)
|
||||
}
|
||||
if width != 0 {
|
||||
w.uint32(videoLayerFieldWidth, width)
|
||||
}
|
||||
if height != 0 {
|
||||
w.uint32(videoLayerFieldHeight, height)
|
||||
}
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func encAddTrack(cid, name string, trackType, source int, width, height uint32) []byte {
|
||||
w := pbWriter{}
|
||||
w.string(addTrackFieldCID, cid)
|
||||
w.string(addTrackFieldName, name)
|
||||
w.int32(addTrackFieldType, int32(trackType))
|
||||
if width != 0 {
|
||||
w.uint32(addTrackFieldWidth, width)
|
||||
}
|
||||
if height != 0 {
|
||||
w.uint32(addTrackFieldHeight, height)
|
||||
}
|
||||
w.int32(addTrackFieldSource, int32(source))
|
||||
if trackType == trackTypeVideo {
|
||||
w.message(addTrackFieldLayers, encVideoLayer(videoQualityHigh, width, height))
|
||||
}
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func encPing(timestamp int64) []byte {
|
||||
w := pbWriter{}
|
||||
w.int64(pingFieldTimestamp, timestamp)
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func encUserPacket(payload []byte) []byte {
|
||||
w := pbWriter{}
|
||||
w.bytes(userPacketFieldPayload, payload)
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func EncodeDataPacketUser(payload []byte, kind int) []byte {
|
||||
w := pbWriter{}
|
||||
if kind != 0 {
|
||||
w.int32(dataPacketFieldKind, int32(kind))
|
||||
}
|
||||
w.message(dataPacketFieldUser, encUserPacket(payload))
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func DecodeDataPacketUser(data []byte) ([]byte, bool) {
|
||||
r := pbReader{buf: data}
|
||||
for !r.eof() {
|
||||
field, wire, err := r.tag()
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
if field == dataPacketFieldUser && wire == wireBytes {
|
||||
inner, err := r.bytes()
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
ur := pbReader{buf: inner}
|
||||
for !ur.eof() {
|
||||
ufield, uwire, uerr := ur.tag()
|
||||
if uerr != nil {
|
||||
return nil, false
|
||||
}
|
||||
if ufield == userPacketFieldPayload && uwire == wireBytes {
|
||||
payload, perr := ur.bytes()
|
||||
if perr != nil {
|
||||
return nil, false
|
||||
}
|
||||
out := make([]byte, len(payload))
|
||||
copy(out, payload)
|
||||
return out, true
|
||||
}
|
||||
if err := ur.skipWire(uwire); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
if err := r.skipWire(wire); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func encSignalRequestOffer(sd sessionDescription) []byte {
|
||||
w := pbWriter{}
|
||||
w.message(signalReqOffer, encSessionDescription(sd))
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func encSignalRequestAnswer(sd sessionDescription) []byte {
|
||||
w := pbWriter{}
|
||||
w.message(signalReqAnswer, encSessionDescription(sd))
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func encSignalRequestTrickle(m trickleMsg) []byte {
|
||||
w := pbWriter{}
|
||||
w.message(signalReqTrickle, encTrickle(m))
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func encSignalRequestAddTrack(cid, name string, trackType, source int, width, height uint32) []byte {
|
||||
w := pbWriter{}
|
||||
w.message(signalReqAddTrack, encAddTrack(cid, name, trackType, source, width, height))
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func encSignalRequestLeave() []byte {
|
||||
w := pbWriter{}
|
||||
w.message(signalReqLeave, []byte{})
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func encSignalRequestPing(timestamp int64) []byte {
|
||||
w := pbWriter{}
|
||||
w.int64(signalReqPingLegacy, timestamp)
|
||||
w.message(signalReqPingReq, encPing(timestamp))
|
||||
return w.buf
|
||||
}
|
||||
|
||||
func decSessionDescription(data []byte) (sessionDescription, error) {
|
||||
r := pbReader{buf: data}
|
||||
var sd sessionDescription
|
||||
for !r.eof() {
|
||||
field, wire, err := r.tag()
|
||||
if err != nil {
|
||||
return sd, err
|
||||
}
|
||||
switch {
|
||||
case field == sdpFieldType && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return sd, err
|
||||
}
|
||||
sd.Type = string(b)
|
||||
case field == sdpFieldSDP && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return sd, err
|
||||
}
|
||||
sd.SDP = string(b)
|
||||
case field == sdpFieldID && wire == wireVarint:
|
||||
v, err := r.varint()
|
||||
if err != nil {
|
||||
return sd, err
|
||||
}
|
||||
sd.ID = uint32(v)
|
||||
default:
|
||||
if err := r.skipWire(wire); err != nil {
|
||||
return sd, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return sd, nil
|
||||
}
|
||||
|
||||
func decTrickle(data []byte) (trickleMsg, error) {
|
||||
r := pbReader{buf: data}
|
||||
var m trickleMsg
|
||||
for !r.eof() {
|
||||
field, wire, err := r.tag()
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
switch {
|
||||
case field == trickleFieldCandidate && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
m.CandidateInit = string(b)
|
||||
case field == trickleFieldTarget && wire == wireVarint:
|
||||
v, err := r.varint()
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
m.Target = int(v)
|
||||
case field == trickleFieldFinal && wire == wireVarint:
|
||||
v, err := r.varint()
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
m.Final = v != 0
|
||||
default:
|
||||
if err := r.skipWire(wire); err != nil {
|
||||
return m, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func decICEServer(data []byte) (iceServer, error) {
|
||||
r := pbReader{buf: data}
|
||||
var s iceServer
|
||||
for !r.eof() {
|
||||
field, wire, err := r.tag()
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
switch {
|
||||
case field == iceServerFieldURLs && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
s.URLs = append(s.URLs, string(b))
|
||||
case field == iceServerFieldUsername && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
s.Username = string(b)
|
||||
case field == iceServerFieldCredential && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
s.Credential = string(b)
|
||||
default:
|
||||
if err := r.skipWire(wire); err != nil {
|
||||
return s, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func decRoom(data []byte) (string, string, error) {
|
||||
r := pbReader{buf: data}
|
||||
var sid, name string
|
||||
for !r.eof() {
|
||||
field, wire, err := r.tag()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
switch {
|
||||
case field == roomFieldSID && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
sid = string(b)
|
||||
case field == roomFieldName && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
name = string(b)
|
||||
default:
|
||||
if err := r.skipWire(wire); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
}
|
||||
}
|
||||
return sid, name, nil
|
||||
}
|
||||
|
||||
func decParticipant(data []byte) (string, string, error) {
|
||||
info := DecodeParticipantInfo(data)
|
||||
return info.SID, info.Identity, nil
|
||||
}
|
||||
|
||||
type ParticipantInfo struct {
|
||||
SID string
|
||||
Identity string
|
||||
State int32
|
||||
Name string
|
||||
}
|
||||
|
||||
const (
|
||||
ParticipantStateJoining int32 = 0
|
||||
ParticipantStateJoined int32 = 1
|
||||
ParticipantStateActive int32 = 2
|
||||
ParticipantStateDisconnected int32 = 3
|
||||
)
|
||||
|
||||
func DecodeParticipantInfo(data []byte) ParticipantInfo {
|
||||
r := pbReader{buf: data}
|
||||
var info ParticipantInfo
|
||||
for !r.eof() {
|
||||
field, wire, err := r.tag()
|
||||
if err != nil {
|
||||
return info
|
||||
}
|
||||
switch {
|
||||
case field == participantFieldSID && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return info
|
||||
}
|
||||
info.SID = string(b)
|
||||
case field == participantFieldIdentity && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return info
|
||||
}
|
||||
info.Identity = string(b)
|
||||
case field == participantFieldState && wire == wireVarint:
|
||||
v, err := r.varint()
|
||||
if err != nil {
|
||||
return info
|
||||
}
|
||||
info.State = int32(v)
|
||||
case field == participantFieldName && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return info
|
||||
}
|
||||
info.Name = string(b)
|
||||
default:
|
||||
if err := r.skipWire(wire); err != nil {
|
||||
return info
|
||||
}
|
||||
}
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
func DecodeParticipantUpdate(data []byte) []ParticipantInfo {
|
||||
r := pbReader{buf: data}
|
||||
var out []ParticipantInfo
|
||||
for !r.eof() {
|
||||
field, wire, err := r.tag()
|
||||
if err != nil {
|
||||
return out
|
||||
}
|
||||
if field == 1 && wire == wireBytes {
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return out
|
||||
}
|
||||
out = append(out, DecodeParticipantInfo(b))
|
||||
} else {
|
||||
if err := r.skipWire(wire); err != nil {
|
||||
return out
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func decJoinResponse(data []byte) (joinResponse, error) {
|
||||
r := pbReader{buf: data}
|
||||
var jr joinResponse
|
||||
for !r.eof() {
|
||||
field, wire, err := r.tag()
|
||||
if err != nil {
|
||||
return jr, err
|
||||
}
|
||||
switch {
|
||||
case field == joinFieldRoom && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return jr, err
|
||||
}
|
||||
sid, name, _ := decRoom(b)
|
||||
jr.RoomSID = sid
|
||||
jr.RoomName = name
|
||||
case field == joinFieldParticipant && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return jr, err
|
||||
}
|
||||
sid, identity, _ := decParticipant(b)
|
||||
jr.ParticipantSID = sid
|
||||
jr.ParticipantID = identity
|
||||
case field == joinFieldServerVersion && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return jr, err
|
||||
}
|
||||
jr.ServerVersion = string(b)
|
||||
case field == joinFieldICEServers && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return jr, err
|
||||
}
|
||||
s, _ := decICEServer(b)
|
||||
jr.ICEServers = append(jr.ICEServers, s)
|
||||
case field == joinFieldSubscriberPrimary && wire == wireVarint:
|
||||
v, err := r.varint()
|
||||
if err != nil {
|
||||
return jr, err
|
||||
}
|
||||
jr.SubscriberPrimary = v != 0
|
||||
case field == joinFieldServerRegion && wire == wireBytes:
|
||||
b, err := r.bytes()
|
||||
if err != nil {
|
||||
return jr, err
|
||||
}
|
||||
jr.ServerRegion = string(b)
|
||||
case field == joinFieldPingTimeout && wire == wireVarint:
|
||||
v, err := r.varint()
|
||||
if err != nil {
|
||||
return jr, err
|
||||
}
|
||||
jr.PingTimeoutSec = int32(v)
|
||||
case field == joinFieldPingInterval && wire == wireVarint:
|
||||
v, err := r.varint()
|
||||
if err != nil {
|
||||
return jr, err
|
||||
}
|
||||
jr.PingIntervalSec = int32(v)
|
||||
case field == joinFieldOtherParticipants && wire == wireBytes:
|
||||
if _, err := r.bytes(); err != nil {
|
||||
return jr, err
|
||||
}
|
||||
default:
|
||||
if err := r.skipWire(wire); err != nil {
|
||||
return jr, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return jr, nil
|
||||
}
|
||||
|
||||
func decSignalResponse(data []byte) (signalResponse, error) {
|
||||
r := pbReader{buf: data}
|
||||
var sr signalResponse
|
||||
for !r.eof() {
|
||||
field, wire, err := r.tag()
|
||||
if err != nil {
|
||||
return sr, err
|
||||
}
|
||||
if wire != wireBytes {
|
||||
if err := r.skipWire(wire); err != nil {
|
||||
return sr, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
inner, err := r.bytes()
|
||||
if err != nil {
|
||||
return sr, err
|
||||
}
|
||||
sr.Kind = int(field)
|
||||
switch field {
|
||||
case signalRespJoin:
|
||||
jr, err := decJoinResponse(inner)
|
||||
if err != nil {
|
||||
return sr, err
|
||||
}
|
||||
sr.Join = &jr
|
||||
case signalRespAnswer, signalRespOffer:
|
||||
sd, err := decSessionDescription(inner)
|
||||
if err != nil {
|
||||
return sr, err
|
||||
}
|
||||
sr.SDP = &sd
|
||||
case signalRespTrickle:
|
||||
tm, err := decTrickle(inner)
|
||||
if err != nil {
|
||||
return sr, err
|
||||
}
|
||||
sr.Trickle = &tm
|
||||
case signalRespRefreshToken:
|
||||
sr.Token = string(inner)
|
||||
case signalRespLeave:
|
||||
li := DecodeLeaveRequest(inner)
|
||||
sr.Leave = &li
|
||||
case signalRespUpdate:
|
||||
sr.Participants = DecodeParticipantUpdate(inner)
|
||||
}
|
||||
return sr, nil
|
||||
}
|
||||
return sr, nil
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package livekit
|
||||
|
||||
import "fmt"
|
||||
|
||||
const (
|
||||
wireVarint = 0
|
||||
wireFixed64 = 1
|
||||
wireBytes = 2
|
||||
wireFixed32 = 5
|
||||
)
|
||||
|
||||
type pbWriter struct{ buf []byte }
|
||||
|
||||
func (w *pbWriter) varint(v uint64) {
|
||||
for v >= 0x80 {
|
||||
w.buf = append(w.buf, byte(v)|0x80)
|
||||
v >>= 7
|
||||
}
|
||||
w.buf = append(w.buf, byte(v))
|
||||
}
|
||||
|
||||
func (w *pbWriter) tag(field, wire uint64) { w.varint(field<<3 | wire) }
|
||||
|
||||
func (w *pbWriter) string(field uint64, s string) {
|
||||
w.tag(field, wireBytes)
|
||||
w.varint(uint64(len(s)))
|
||||
w.buf = append(w.buf, s...)
|
||||
}
|
||||
|
||||
func (w *pbWriter) bytes(field uint64, b []byte) {
|
||||
w.tag(field, wireBytes)
|
||||
w.varint(uint64(len(b)))
|
||||
w.buf = append(w.buf, b...)
|
||||
}
|
||||
|
||||
func (w *pbWriter) message(field uint64, b []byte) { w.bytes(field, b) }
|
||||
|
||||
func (w *pbWriter) int32(field uint64, v int32) {
|
||||
w.tag(field, wireVarint)
|
||||
w.varint(uint64(uint32(v)))
|
||||
}
|
||||
|
||||
func (w *pbWriter) int64(field uint64, v int64) {
|
||||
w.tag(field, wireVarint)
|
||||
w.varint(uint64(v))
|
||||
}
|
||||
|
||||
func (w *pbWriter) uint32(field uint64, v uint32) {
|
||||
w.tag(field, wireVarint)
|
||||
w.varint(uint64(v))
|
||||
}
|
||||
|
||||
func (w *pbWriter) bool(field uint64, v bool) {
|
||||
w.tag(field, wireVarint)
|
||||
if v {
|
||||
w.varint(1)
|
||||
} else {
|
||||
w.varint(0)
|
||||
}
|
||||
}
|
||||
|
||||
type pbReader struct {
|
||||
buf []byte
|
||||
pos int
|
||||
}
|
||||
|
||||
func (r *pbReader) eof() bool { return r.pos >= len(r.buf) }
|
||||
|
||||
func (r *pbReader) varint() (uint64, error) {
|
||||
var v uint64
|
||||
var shift uint
|
||||
for {
|
||||
if r.pos >= len(r.buf) {
|
||||
return 0, fmt.Errorf("varint: unexpected eof")
|
||||
}
|
||||
b := r.buf[r.pos]
|
||||
r.pos++
|
||||
v |= uint64(b&0x7f) << shift
|
||||
if b < 0x80 {
|
||||
return v, nil
|
||||
}
|
||||
shift += 7
|
||||
if shift >= 64 {
|
||||
return 0, fmt.Errorf("varint: overflow")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *pbReader) tag() (field, wire uint64, err error) {
|
||||
t, err := r.varint()
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return t >> 3, t & 7, nil
|
||||
}
|
||||
|
||||
func (r *pbReader) bytes() ([]byte, error) {
|
||||
n, err := r.varint()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.pos+int(n) > len(r.buf) {
|
||||
return nil, fmt.Errorf("bytes: short read")
|
||||
}
|
||||
out := r.buf[r.pos : r.pos+int(n)]
|
||||
r.pos += int(n)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *pbReader) skipWire(wire uint64) error {
|
||||
switch wire {
|
||||
case wireVarint:
|
||||
_, err := r.varint()
|
||||
return err
|
||||
case wireFixed64:
|
||||
if r.pos+8 > len(r.buf) {
|
||||
return fmt.Errorf("skip: short fixed64")
|
||||
}
|
||||
r.pos += 8
|
||||
return nil
|
||||
case wireBytes:
|
||||
_, err := r.bytes()
|
||||
return err
|
||||
case wireFixed32:
|
||||
if r.pos+4 > len(r.buf) {
|
||||
return fmt.Errorf("skip: short fixed32")
|
||||
}
|
||||
r.pos += 4
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown wire type %d", wire)
|
||||
}
|
||||
@@ -99,6 +99,12 @@ func main() {
|
||||
c := pion.NewTelemostClient(log.Printf)
|
||||
c.OnConnected = creatorCallback
|
||||
startVideo(*mode, c, creatorCallback)
|
||||
case "wbstream-headless-joiner":
|
||||
c := android.NewWBStreamHeadlessJoiner(log.Printf)
|
||||
c.OnConnected = func(tun tunnel.DataTunnel) {
|
||||
startJoinerBridge(tun, common.VP8BufSize)
|
||||
}
|
||||
c.Run()
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "Unknown mode: %s\n", *mode)
|
||||
os.Exit(1)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package android
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
joiner "whitelist-bypass/relay/pion/headless-joiner-common"
|
||||
"whitelist-bypass/relay/tunnel"
|
||||
)
|
||||
|
||||
type WBStreamHeadlessJoiner struct {
|
||||
inner *joiner.WBStreamHeadlessJoiner
|
||||
OnConnected func(tunnel.DataTunnel)
|
||||
}
|
||||
|
||||
func NewWBStreamHeadlessJoiner(logFn func(string, ...any)) *WBStreamHeadlessJoiner {
|
||||
if logFn == nil {
|
||||
logFn = log.Printf
|
||||
}
|
||||
inner := joiner.NewWBStreamHeadlessJoiner(logFn, RequestResolve, StatusEmitter{}, PCConfigurer{})
|
||||
wrapper := &WBStreamHeadlessJoiner{inner: inner}
|
||||
inner.OnConnected = func(tun tunnel.DataTunnel) {
|
||||
if wrapper.OnConnected != nil {
|
||||
wrapper.OnConnected(tun)
|
||||
}
|
||||
}
|
||||
return wrapper
|
||||
}
|
||||
|
||||
func (j *WBStreamHeadlessJoiner) Run() {
|
||||
j.inner.Status.EmitStatus(common.StatusReady)
|
||||
for {
|
||||
line, err := ReadStdinLine()
|
||||
if err != nil {
|
||||
log.Printf("wbstream-joiner: stdin closed: %v", err)
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(line, "JOIN:") {
|
||||
j.inner.RunWithParams(strings.TrimPrefix(line, "JOIN:"))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package joiner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pion/webrtc/v4"
|
||||
"whitelist-bypass/relay/common"
|
||||
"whitelist-bypass/relay/tunnel"
|
||||
"whitelist-bypass/relay/wbstream"
|
||||
)
|
||||
|
||||
type WBStreamHeadlessJoiner struct {
|
||||
logFn func(string, ...any)
|
||||
OnConnected func(tunnel.DataTunnel)
|
||||
ResolveFn ResolveFunc
|
||||
Status StatusEmitter
|
||||
PCConfig PeerConnectionConfigurer
|
||||
|
||||
mu sync.Mutex
|
||||
session *wbstream.Session
|
||||
closed bool
|
||||
}
|
||||
|
||||
func NewWBStreamHeadlessJoiner(logFn func(string, ...any), resolveFn ResolveFunc, status StatusEmitter, pcConfig PeerConnectionConfigurer) *WBStreamHeadlessJoiner {
|
||||
return &WBStreamHeadlessJoiner{
|
||||
logFn: logFn,
|
||||
ResolveFn: resolveFn,
|
||||
Status: status,
|
||||
PCConfig: pcConfig,
|
||||
}
|
||||
}
|
||||
|
||||
func (j *WBStreamHeadlessJoiner) RunWithParams(jsonParams string) {
|
||||
var params struct {
|
||||
RoomID string `json:"roomId"`
|
||||
DisplayName string `json:"displayName"`
|
||||
TunnelMode string `json:"tunnelMode"`
|
||||
VP8FPS int `json:"vp8Fps"`
|
||||
VP8Batch int `json:"vp8Batch"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(jsonParams), ¶ms); err != nil {
|
||||
j.logFn("wbstream-joiner: failed to parse params: %v", err)
|
||||
j.Status.EmitStatusError("bad params: " + err.Error())
|
||||
return
|
||||
}
|
||||
if params.RoomID == "" {
|
||||
j.logFn("wbstream-joiner: missing roomId")
|
||||
j.Status.EmitStatusError("missing roomId")
|
||||
return
|
||||
}
|
||||
if params.DisplayName == "" {
|
||||
params.DisplayName = "Joiner"
|
||||
}
|
||||
|
||||
httpClient := j.makeHTTPClient()
|
||||
j.logFn("wbstream-joiner: room=%s name=%s vp8Fps=%d vp8Batch=%d", params.RoomID, params.DisplayName, params.VP8FPS, params.VP8Batch)
|
||||
j.Status.EmitStatus(common.StatusConnecting)
|
||||
|
||||
roomID, roomToken, _, err := wbstream.AuthAndGetToken(httpClient, params.RoomID, params.DisplayName)
|
||||
if err != nil {
|
||||
j.logFn("wbstream-joiner: auth failed: %v", err)
|
||||
j.Status.EmitStatusError("auth: " + err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
obf, err := tunnel.NewTunnelObfuscator(tunnel.DeriveSecretFromJoinLink(roomID))
|
||||
if err != nil {
|
||||
j.logFn("wbstream-joiner: obfuscator init failed: %v", err)
|
||||
j.Status.EmitStatusError("obfuscator init: " + err.Error())
|
||||
return
|
||||
}
|
||||
j.logFn("wbstream-joiner: obf key-source=%q localEpoch=0x%08x", roomID, obf.LocalEpoch())
|
||||
|
||||
var settingEngine *webrtc.SettingEngine
|
||||
if j.PCConfig != nil {
|
||||
se := webrtc.SettingEngine{}
|
||||
j.PCConfig.ConfigureSettingEngine(&se)
|
||||
settingEngine = &se
|
||||
}
|
||||
|
||||
sess := wbstream.NewSession(wbstream.SessionConfig{
|
||||
RoomToken: roomToken,
|
||||
DisplayName: params.DisplayName,
|
||||
TunnelMode: params.TunnelMode,
|
||||
Obfuscator: obf,
|
||||
LogFn: j.logFn,
|
||||
SettingEngine: settingEngine,
|
||||
NetDialContext: j.makeDialContext(),
|
||||
ResolveICEHost: j.ResolveFn,
|
||||
VP8FPS: params.VP8FPS,
|
||||
VP8Batch: params.VP8Batch,
|
||||
})
|
||||
sess.OnConnected = func(tun tunnel.DataTunnel) {
|
||||
j.logFn("wbstream-joiner: === TUNNEL CONNECTED ===")
|
||||
j.Status.EmitStatus(common.StatusTunnelConnected)
|
||||
if j.OnConnected != nil {
|
||||
j.OnConnected(tun)
|
||||
}
|
||||
}
|
||||
|
||||
j.mu.Lock()
|
||||
j.session = sess
|
||||
closed := j.closed
|
||||
j.mu.Unlock()
|
||||
if closed {
|
||||
sess.Close()
|
||||
return
|
||||
}
|
||||
|
||||
if err := sess.Start(); err != nil {
|
||||
j.logFn("wbstream-joiner: session start failed: %v", err)
|
||||
j.Status.EmitStatusError("session: " + err.Error())
|
||||
return
|
||||
}
|
||||
<-sess.Done()
|
||||
j.logFn("wbstream-joiner: session ended")
|
||||
j.Status.EmitStatus(common.StatusTunnelLost)
|
||||
}
|
||||
|
||||
func (j *WBStreamHeadlessJoiner) Close() {
|
||||
j.mu.Lock()
|
||||
j.closed = true
|
||||
sess := j.session
|
||||
j.session = nil
|
||||
j.mu.Unlock()
|
||||
if sess != nil {
|
||||
sess.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (j *WBStreamHeadlessJoiner) makeDialContext() func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
if j.ResolveFn == nil {
|
||||
return nil
|
||||
}
|
||||
return func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
host, port, _ := net.SplitHostPort(addr)
|
||||
resolvedIP, err := j.ResolveFn(host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return (&net.Dialer{Timeout: 10 * time.Second}).DialContext(ctx, network, resolvedIP+":"+port)
|
||||
}
|
||||
}
|
||||
|
||||
func (j *WBStreamHeadlessJoiner) makeHTTPClient() *http.Client {
|
||||
transport := &http.Transport{DialContext: j.makeDialContext()}
|
||||
return &http.Client{Timeout: 60 * time.Second, Transport: transport}
|
||||
}
|
||||
@@ -99,6 +99,26 @@ func init() {
|
||||
common.MaskingEnabled = true
|
||||
}
|
||||
|
||||
func StartWBStreamHeadless(socksPort int, socksUser, socksPass string, callback HeadlessCallback) {
|
||||
StopHeadless()
|
||||
|
||||
activeHeadless.Lock()
|
||||
activeHeadless.callback = callback
|
||||
activeHeadless.stopped = false
|
||||
activeHeadless.platform = "wbstream"
|
||||
activeHeadless.Unlock()
|
||||
|
||||
logFn, resolveFn, statusEmitter := makeHelpers(callback)
|
||||
wbJoiner := joiner.NewWBStreamHeadlessJoiner(logFn, resolveFn, statusEmitter, nil)
|
||||
wbJoiner.OnConnected = makeOnConnected(socksPort, socksUser, socksPass, logFn, callback)
|
||||
|
||||
activeHeadless.Lock()
|
||||
activeHeadless.joiner = wbJoiner
|
||||
activeHeadless.Unlock()
|
||||
|
||||
callback.OnStatus(common.StatusReady)
|
||||
}
|
||||
|
||||
func StartTelemostHeadless(socksPort int, socksUser, socksPass string, callback HeadlessCallback) {
|
||||
StopHeadless()
|
||||
|
||||
@@ -180,6 +200,10 @@ func SendJoinParams(jsonParams string) {
|
||||
if vkJoiner, ok := currentJoiner.(*joiner.VKHeadlessJoiner); ok {
|
||||
go vkJoiner.RunWithParams(jsonParams)
|
||||
}
|
||||
case "wbstream":
|
||||
if wbJoiner, ok := currentJoiner.(*joiner.WBStreamHeadlessJoiner); ok {
|
||||
go wbJoiner.RunWithParams(jsonParams)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -88,6 +88,13 @@ func NewChunkedDCTunnel(readRaw datachannel.ReadWriteCloser, writeDC *webrtc.Dat
|
||||
return t
|
||||
}
|
||||
|
||||
func NewChunkedDCTunnelFromRaw(readRaw, writeRaw datachannel.ReadWriteCloser, obf *TunnelObfuscator, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
t := &DCTunnel{raw: readRaw, writeRaw: writeRaw, obf: obf, readBuf: readBuf, logFn: logFn, chunked: true}
|
||||
go t.readLoop()
|
||||
go t.statsLoop()
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *DCTunnel) readLoop() {
|
||||
buf := make([]byte, t.readBuf)
|
||||
for {
|
||||
@@ -241,6 +248,7 @@ func (t *DCTunnel) SendData(data []byte) {
|
||||
}
|
||||
|
||||
func (t *DCTunnel) SetOnData(fn func([]byte)) { t.onData = fn }
|
||||
func (t *DCTunnel) OnData() func([]byte) { return t.onData }
|
||||
func (t *DCTunnel) SetOnClose(fn func()) { t.onClose = fn }
|
||||
func (t *DCTunnel) Reconfigure(fps, batch int) {}
|
||||
|
||||
|
||||
@@ -67,6 +67,10 @@ func (rb *RelayBridge) closeAll() {
|
||||
})
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) Reset() {
|
||||
rb.closeAll()
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) MarkReady() {
|
||||
rb.once.Do(func() { close(rb.ready) })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
package wbstream
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
)
|
||||
|
||||
const (
|
||||
APIBase = "https://stream.wb.ru"
|
||||
WSURL = "wss://wbstream01-el.wb.ru:7880"
|
||||
Origin = "https://stream.wb.ru"
|
||||
)
|
||||
|
||||
type guestRegisterRequest struct {
|
||||
DisplayName string `json:"displayName"`
|
||||
Device guestDeviceCfg `json:"device"`
|
||||
}
|
||||
|
||||
type guestDeviceCfg struct {
|
||||
DeviceName string `json:"deviceName"`
|
||||
DeviceType string `json:"deviceType"`
|
||||
}
|
||||
|
||||
type guestRegisterResponse struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
}
|
||||
|
||||
type createRoomRequest struct {
|
||||
RoomType string `json:"roomType"`
|
||||
RoomPrivacy string `json:"roomPrivacy"`
|
||||
}
|
||||
|
||||
type createRoomResponse struct {
|
||||
RoomID string `json:"roomId"`
|
||||
}
|
||||
|
||||
type tokenResponse struct {
|
||||
RoomToken string `json:"roomToken"`
|
||||
}
|
||||
|
||||
func httpDo(client *http.Client, req *http.Request) (*http.Response, error) {
|
||||
req.Header.Set("User-Agent", common.UserAgent)
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
func RegisterGuest(client *http.Client, displayName string) (string, error) {
|
||||
body, _ := json.Marshal(guestRegisterRequest{
|
||||
DisplayName: displayName,
|
||||
Device: guestDeviceCfg{
|
||||
DeviceName: "Linux",
|
||||
DeviceType: "PARTICIPANT_DEVICE_TYPE_WEB_DESKTOP",
|
||||
},
|
||||
})
|
||||
req, err := http.NewRequest(http.MethodPost, APIBase+"/auth/api/v1/auth/user/guest-register", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := httpDo(client, req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("guest-register: status %d: %s", resp.StatusCode, string(raw))
|
||||
}
|
||||
|
||||
var r guestRegisterResponse
|
||||
if err := json.Unmarshal(raw, &r); err != nil {
|
||||
return "", fmt.Errorf("guest-register decode: %w", err)
|
||||
}
|
||||
return r.AccessToken, nil
|
||||
}
|
||||
|
||||
func CreateRoom(client *http.Client, accessToken string) (string, error) {
|
||||
body, _ := json.Marshal(createRoomRequest{
|
||||
RoomType: "ROOM_TYPE_ALL_ON_SCREEN",
|
||||
RoomPrivacy: "ROOM_PRIVACY_FREE",
|
||||
})
|
||||
req, err := http.NewRequest(http.MethodPost, APIBase+"/api-room/api/v2/room", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
|
||||
resp, err := httpDo(client, req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
|
||||
return "", fmt.Errorf("create-room: status %d: %s", resp.StatusCode, string(raw))
|
||||
}
|
||||
|
||||
var r createRoomResponse
|
||||
if err := json.Unmarshal(raw, &r); err != nil {
|
||||
return "", fmt.Errorf("create-room decode: %w", err)
|
||||
}
|
||||
return r.RoomID, nil
|
||||
}
|
||||
|
||||
func JoinRoom(client *http.Client, accessToken, roomID string) error {
|
||||
url := fmt.Sprintf("%s/api-room/api/v1/room/%s/join", APIBase, roomID)
|
||||
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader([]byte("{}")))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
|
||||
resp, err := httpDo(client, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("join-room: status %d: %s", resp.StatusCode, string(raw))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetRoomToken(client *http.Client, accessToken, roomID, displayName string) (string, error) {
|
||||
url := fmt.Sprintf("%s/api-room-manager/api/v1/room/%s/token?deviceType=PARTICIPANT_DEVICE_TYPE_WEB_DESKTOP&displayName=%s",
|
||||
APIBase, roomID, displayName)
|
||||
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
|
||||
resp, err := httpDo(client, req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("get-token: status %d: %s", resp.StatusCode, string(raw))
|
||||
}
|
||||
|
||||
var r tokenResponse
|
||||
if err := json.Unmarshal(raw, &r); err != nil {
|
||||
return "", fmt.Errorf("get-token decode: %w", err)
|
||||
}
|
||||
return r.RoomToken, nil
|
||||
}
|
||||
|
||||
func AuthAndGetToken(client *http.Client, roomID, displayName string) (string, string, string, error) {
|
||||
accessToken, err := RegisterGuest(client, displayName)
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("register guest: %w", err)
|
||||
}
|
||||
if roomID == "" {
|
||||
roomID, err = CreateRoom(client, accessToken)
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("create room: %w", err)
|
||||
}
|
||||
}
|
||||
if err := JoinRoom(client, accessToken, roomID); err != nil {
|
||||
return "", "", "", fmt.Errorf("join room: %w", err)
|
||||
}
|
||||
roomToken, err := GetRoomToken(client, accessToken, roomID, displayName)
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("get token: %w", err)
|
||||
}
|
||||
return roomID, roomToken, accessToken, nil
|
||||
}
|
||||
|
||||
func KickParticipant(client *http.Client, accessToken, roomID, participantID string) error {
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
url := fmt.Sprintf("%s/api-room-manager/api/v1/room/%s/participant/%s/kick", APIBase, roomID, participantID)
|
||||
req, err := http.NewRequest("DELETE", url, strings.NewReader("{}"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
req.Header.Set("User-Agent", common.UserAgent)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("kick %s -> %d %s", participantID, resp.StatusCode, string(body))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package wbstream
|
||||
|
||||
import (
|
||||
"github.com/pion/datachannel"
|
||||
"whitelist-bypass/relay/livekit"
|
||||
)
|
||||
|
||||
type dataPacketWrapper struct {
|
||||
inner datachannel.ReadWriteCloser
|
||||
kind int
|
||||
}
|
||||
|
||||
func newDataPacketWrapper(inner datachannel.ReadWriteCloser, kind int) *dataPacketWrapper {
|
||||
return &dataPacketWrapper{inner: inner, kind: kind}
|
||||
}
|
||||
|
||||
func (w *dataPacketWrapper) ReadDataChannel(p []byte) (int, bool, error) {
|
||||
buf := make([]byte, len(p))
|
||||
for {
|
||||
n, isString, err := w.inner.ReadDataChannel(buf)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
if n == 0 {
|
||||
continue
|
||||
}
|
||||
payload, ok := livekit.DecodeDataPacketUser(buf[:n])
|
||||
if !ok || len(payload) == 0 {
|
||||
continue
|
||||
}
|
||||
copied := copy(p, payload)
|
||||
return copied, isString, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (w *dataPacketWrapper) WriteDataChannel(p []byte, isString bool) (int, error) {
|
||||
wire := livekit.EncodeDataPacketUser(p, w.kind)
|
||||
if _, err := w.inner.WriteDataChannel(wire, isString); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (w *dataPacketWrapper) Read(p []byte) (int, error) {
|
||||
n, _, err := w.ReadDataChannel(p)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (w *dataPacketWrapper) Write(p []byte) (int, error) {
|
||||
return w.WriteDataChannel(p, false)
|
||||
}
|
||||
|
||||
func (w *dataPacketWrapper) Close() error { return w.inner.Close() }
|
||||
@@ -0,0 +1,458 @@
|
||||
package wbstream
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/pion/rtp"
|
||||
"github.com/pion/rtp/codecs"
|
||||
"github.com/pion/webrtc/v4"
|
||||
"whitelist-bypass/relay/common"
|
||||
"whitelist-bypass/relay/livekit"
|
||||
"whitelist-bypass/relay/tunnel"
|
||||
)
|
||||
|
||||
type peerEntry struct {
|
||||
sid string
|
||||
identity string
|
||||
firstSeen time.Time
|
||||
state int32
|
||||
}
|
||||
|
||||
const (
|
||||
TunnelModeVideo = "video"
|
||||
TunnelModeDC = "dc"
|
||||
)
|
||||
|
||||
type SessionConfig struct {
|
||||
RoomToken string
|
||||
DisplayName string
|
||||
TunnelMode string
|
||||
Obfuscator *tunnel.TunnelObfuscator
|
||||
LogFn func(string, ...any)
|
||||
SettingEngine *webrtc.SettingEngine
|
||||
NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
ResolveICEHost func(host string) (string, error)
|
||||
VP8FPS int
|
||||
VP8Batch int
|
||||
RoomID string
|
||||
AccessToken string
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
cfg SessionConfig
|
||||
|
||||
lk *livekit.Client
|
||||
sampleTrack *webrtc.TrackLocalStaticSample
|
||||
|
||||
pubReliableDC *webrtc.DataChannel
|
||||
pubReliableDCReady bool
|
||||
subReliableDC *webrtc.DataChannel
|
||||
|
||||
vp8tun *tunnel.VP8DataTunnel
|
||||
dctun *tunnel.DCTunnel
|
||||
mu sync.Mutex
|
||||
tunFired bool
|
||||
remoteTracks int
|
||||
done chan struct{}
|
||||
|
||||
peersBySID map[string]peerEntry // SID -> first-seen time + state
|
||||
|
||||
OnConnected func(tunnel.DataTunnel)
|
||||
OnPeerRestart func()
|
||||
}
|
||||
|
||||
func NewSession(cfg SessionConfig) *Session {
|
||||
if cfg.LogFn == nil {
|
||||
cfg.LogFn = log.Printf
|
||||
}
|
||||
return &Session{cfg: cfg, done: make(chan struct{})}
|
||||
}
|
||||
|
||||
func (s *Session) Done() <-chan struct{} { return s.done }
|
||||
|
||||
func (s *Session) Start() error {
|
||||
s.lk = livekit.NewClient(livekit.Config{
|
||||
ServerURL: WSURL,
|
||||
Token: s.cfg.RoomToken,
|
||||
Origin: Origin,
|
||||
UserAgent: common.UserAgent,
|
||||
LogFn: s.cfg.LogFn,
|
||||
SettingEngine: s.cfg.SettingEngine,
|
||||
NetDialContext: s.cfg.NetDialContext,
|
||||
ResolveICEHost: s.cfg.ResolveICEHost,
|
||||
})
|
||||
s.lk.OnReady = s.onLKReady
|
||||
s.lk.OnTrack = s.onRemoteTrack
|
||||
s.lk.OnDataChannel = s.onRemoteDataChannel
|
||||
s.lk.OnPubConnected = s.startTunnel
|
||||
if s.cfg.AccessToken != "" && s.cfg.RoomID != "" {
|
||||
s.lk.OnParticipantUpdate = s.onParticipantUpdate
|
||||
}
|
||||
|
||||
if err := s.lk.Connect(); err != nil {
|
||||
return err
|
||||
}
|
||||
go s.lk.PingLoop()
|
||||
go func() {
|
||||
if err := s.lk.ReadLoop(); err != nil {
|
||||
s.cfg.LogFn("[lk] read loop ended: %v", err)
|
||||
}
|
||||
close(s.done)
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Session) onLKReady() {
|
||||
pubPC := s.lk.PubPC()
|
||||
if pubPC == nil {
|
||||
return
|
||||
}
|
||||
|
||||
trackID := "videochannel-" + uuid.New().String()
|
||||
track, err := webrtc.NewTrackLocalStaticSample(
|
||||
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8, ClockRate: 90000},
|
||||
trackID, "tunnel-video-"+uuid.New().String(),
|
||||
)
|
||||
if err != nil {
|
||||
s.cfg.LogFn("[lk] create local track: %v", err)
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.sampleTrack = track
|
||||
s.mu.Unlock()
|
||||
|
||||
if _, err := pubPC.AddTransceiverFromTrack(track,
|
||||
webrtc.RTPTransceiverInit{Direction: webrtc.RTPTransceiverDirectionSendonly}); err != nil {
|
||||
s.cfg.LogFn("[lk] add transceiver: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
ordered := true
|
||||
dc, err := pubPC.CreateDataChannel("_reliable", &webrtc.DataChannelInit{
|
||||
Ordered: &ordered,
|
||||
})
|
||||
if err != nil {
|
||||
s.cfg.LogFn("[lk] create reliable DC: %v", err)
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.pubReliableDC = dc
|
||||
s.mu.Unlock()
|
||||
dc.OnOpen(func() {
|
||||
s.cfg.LogFn("[lk] reliable DC open")
|
||||
s.mu.Lock()
|
||||
s.pubReliableDCReady = true
|
||||
s.mu.Unlock()
|
||||
s.maybeStartDCTunnel()
|
||||
})
|
||||
|
||||
if err := s.lk.SendAddTrack(track.ID(), "videochannel",
|
||||
livekit.TrackTypeVideo, livekit.TrackSourceCamera, 1280, 720); err != nil {
|
||||
s.cfg.LogFn("[lk] send add-track: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
offer, err := pubPC.CreateOffer(nil)
|
||||
if err != nil {
|
||||
s.cfg.LogFn("[lk] create offer: %v", err)
|
||||
return
|
||||
}
|
||||
if err := pubPC.SetLocalDescription(offer); err != nil {
|
||||
s.cfg.LogFn("[lk] set local offer: %v", err)
|
||||
return
|
||||
}
|
||||
if err := s.lk.SendOffer(offer.SDP); err != nil {
|
||||
s.cfg.LogFn("[lk] send offer: %v", err)
|
||||
return
|
||||
}
|
||||
s.cfg.LogFn("[lk] sent publisher offer (%d bytes)", len(offer.SDP))
|
||||
}
|
||||
|
||||
func (s *Session) startTunnel() {
|
||||
s.mu.Lock()
|
||||
if s.vp8tun != nil || s.sampleTrack == nil {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.vp8tun = tunnel.NewVP8DataTunnel(s.sampleTrack, s.cfg.Obfuscator, s.cfg.LogFn)
|
||||
s.vp8tun.Start(s.cfg.VP8FPS, s.cfg.VP8Batch)
|
||||
s.mu.Unlock()
|
||||
s.cfg.LogFn("[lk] vp8 tunnel writer started")
|
||||
|
||||
if s.cfg.TunnelMode == TunnelModeVideo {
|
||||
s.fireOnConnected(s.vp8tun)
|
||||
return
|
||||
}
|
||||
if s.cfg.TunnelMode == "" {
|
||||
s.vp8tun.SetOnData(func(payload []byte) { s.activate(s.vp8tun, payload) })
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) maybeStartDCTunnel() {
|
||||
s.mu.Lock()
|
||||
if s.dctun != nil {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
pubDC := s.pubReliableDC
|
||||
subDC := s.subReliableDC
|
||||
pubReady := s.pubReliableDCReady
|
||||
s.mu.Unlock()
|
||||
if pubDC == nil || subDC == nil || !pubReady {
|
||||
return
|
||||
}
|
||||
if subDC.ReadyState() != webrtc.DataChannelStateOpen {
|
||||
return
|
||||
}
|
||||
subRaw, err := subDC.Detach()
|
||||
if err != nil {
|
||||
s.cfg.LogFn("[lk] detach sub DC: %v", err)
|
||||
return
|
||||
}
|
||||
pubRaw, err := pubDC.Detach()
|
||||
if err != nil {
|
||||
s.cfg.LogFn("[lk] detach pub DC: %v", err)
|
||||
return
|
||||
}
|
||||
readWrapped := newDataPacketWrapper(subRaw, livekit.DataPacketKindReliable)
|
||||
writeWrapped := newDataPacketWrapper(pubRaw, livekit.DataPacketKindReliable)
|
||||
dctun := tunnel.NewChunkedDCTunnelFromRaw(readWrapped, writeWrapped, s.cfg.Obfuscator, common.DCBufSize, s.cfg.LogFn)
|
||||
if dctun == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.dctun = dctun
|
||||
s.mu.Unlock()
|
||||
s.cfg.LogFn("[lk] dc tunnel ready (pub+sub _reliable)")
|
||||
|
||||
if s.cfg.TunnelMode == TunnelModeDC {
|
||||
s.fireOnConnected(dctun)
|
||||
return
|
||||
}
|
||||
if s.cfg.TunnelMode == "" {
|
||||
dctun.SetOnData(func(payload []byte) { s.activate(dctun, payload) })
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) fireOnConnected(tun tunnel.DataTunnel) {
|
||||
s.mu.Lock()
|
||||
if s.tunFired {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.tunFired = true
|
||||
s.mu.Unlock()
|
||||
if s.OnConnected != nil {
|
||||
s.OnConnected(tun)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) activate(tun tunnel.DataTunnel, payload []byte) {
|
||||
s.mu.Lock()
|
||||
if s.tunFired {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.tunFired = true
|
||||
s.mu.Unlock()
|
||||
s.cfg.LogFn("[lk] auto-detected active tunnel: %T", tun)
|
||||
if s.OnConnected != nil {
|
||||
s.OnConnected(tun)
|
||||
}
|
||||
var fwd func([]byte)
|
||||
switch v := tun.(type) {
|
||||
case *tunnel.VP8DataTunnel:
|
||||
fwd = v.OnData
|
||||
case *tunnel.DCTunnel:
|
||||
fwd = v.OnData()
|
||||
}
|
||||
if fwd != nil {
|
||||
fwd(payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) currentVP8Tun() *tunnel.VP8DataTunnel {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.vp8tun
|
||||
}
|
||||
|
||||
func (s *Session) rearmAutoDetect() {
|
||||
if s.cfg.TunnelMode != "" {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.tunFired = false
|
||||
vp8 := s.vp8tun
|
||||
dc := s.dctun
|
||||
s.mu.Unlock()
|
||||
if vp8 != nil {
|
||||
vp8.SetOnData(func(payload []byte) { s.activate(vp8, payload) })
|
||||
}
|
||||
if dc != nil {
|
||||
dc.SetOnData(func(payload []byte) { s.activate(dc, payload) })
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) onRemoteTrack(track *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {
|
||||
if track.Codec().MimeType != webrtc.MimeTypeVP8 {
|
||||
go func() {
|
||||
buf := make([]byte, common.UDPBufSize)
|
||||
for {
|
||||
if _, _, err := track.Read(buf); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.remoteTracks++
|
||||
count := s.remoteTracks
|
||||
s.mu.Unlock()
|
||||
if count > 1 {
|
||||
s.cfg.LogFn("[wb] new peer track #%d, signalling peer-restart", count)
|
||||
s.rearmAutoDetect()
|
||||
if s.OnPeerRestart != nil {
|
||||
s.OnPeerRestart()
|
||||
}
|
||||
}
|
||||
go s.readVP8Track(track)
|
||||
}
|
||||
|
||||
func (s *Session) readVP8Track(track *webrtc.TrackRemote) {
|
||||
var vp8Pkt codecs.VP8Packet
|
||||
var frameBuf []byte
|
||||
var lastSeq uint16
|
||||
var haveLastSeq bool
|
||||
frameValid := false
|
||||
var recvCount int
|
||||
buf := make([]byte, common.RTPBufSize)
|
||||
for {
|
||||
n, _, err := track.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
pkt := &rtp.Packet{}
|
||||
if pkt.Unmarshal(buf[:n]) != nil {
|
||||
continue
|
||||
}
|
||||
if haveLastSeq && pkt.SequenceNumber != lastSeq+1 {
|
||||
frameValid = false
|
||||
frameBuf = frameBuf[:0]
|
||||
}
|
||||
lastSeq = pkt.SequenceNumber
|
||||
haveLastSeq = true
|
||||
|
||||
vp8Payload, err := vp8Pkt.Unmarshal(pkt.Payload)
|
||||
if err != nil {
|
||||
frameValid = false
|
||||
frameBuf = frameBuf[:0]
|
||||
continue
|
||||
}
|
||||
if vp8Pkt.S == 1 {
|
||||
frameBuf = frameBuf[:0]
|
||||
frameValid = true
|
||||
}
|
||||
if !frameValid {
|
||||
continue
|
||||
}
|
||||
frameBuf = append(frameBuf, vp8Payload...)
|
||||
if !pkt.Marker {
|
||||
continue
|
||||
}
|
||||
recvCount++
|
||||
if recvCount <= 3 || recvCount%200 == 0 {
|
||||
s.cfg.LogFn("[lk-video] recv vp8 frame #%d %d bytes", recvCount, len(frameBuf))
|
||||
}
|
||||
|
||||
tun := s.currentVP8Tun()
|
||||
if tun != nil {
|
||||
tun.HandleFrame(frameBuf)
|
||||
}
|
||||
frameBuf = frameBuf[:0]
|
||||
frameValid = false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) onRemoteDataChannel(dc *webrtc.DataChannel) {
|
||||
s.cfg.LogFn("[lk] remote DC label=%s id=%v", dc.Label(), dc.ID())
|
||||
if dc.Label() != "_reliable" {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.subReliableDC = dc
|
||||
s.mu.Unlock()
|
||||
dc.OnOpen(func() {
|
||||
s.cfg.LogFn("[lk] remote _reliable DC open")
|
||||
s.maybeStartDCTunnel()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Session) onParticipantUpdate(updates []livekit.ParticipantInfo) {
|
||||
selfSID := s.lk.Join().ParticipantSID
|
||||
|
||||
s.mu.Lock()
|
||||
if s.peersBySID == nil {
|
||||
s.peersBySID = make(map[string]peerEntry)
|
||||
}
|
||||
newcomerSIDs := make(map[string]bool)
|
||||
for _, p := range updates {
|
||||
if p.SID == "" || p.SID == selfSID {
|
||||
continue
|
||||
}
|
||||
if p.State == livekit.ParticipantStateDisconnected {
|
||||
delete(s.peersBySID, p.SID)
|
||||
continue
|
||||
}
|
||||
entry, ok := s.peersBySID[p.SID]
|
||||
if !ok {
|
||||
entry = peerEntry{sid: p.SID, identity: p.Identity, firstSeen: time.Now()}
|
||||
newcomerSIDs[p.SID] = true
|
||||
}
|
||||
if p.Identity != "" {
|
||||
entry.identity = p.Identity
|
||||
}
|
||||
entry.state = p.State
|
||||
s.peersBySID[p.SID] = entry
|
||||
}
|
||||
|
||||
var stale []peerEntry
|
||||
if len(newcomerSIDs) > 0 {
|
||||
for _, e := range s.peersBySID {
|
||||
if e.state == livekit.ParticipantStateActive && !newcomerSIDs[e.sid] {
|
||||
stale = append(stale, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if len(stale) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for _, e := range stale {
|
||||
if e.identity == "" {
|
||||
continue
|
||||
}
|
||||
if err := KickParticipant(http.DefaultClient, s.cfg.AccessToken, s.cfg.RoomID, e.identity); err != nil {
|
||||
s.cfg.LogFn("[wb] kick failed identity=%s: %v", e.identity, err)
|
||||
continue
|
||||
}
|
||||
s.cfg.LogFn("[wb] kicked stale peer identity=%s sid=%s", e.identity, e.sid)
|
||||
s.mu.Lock()
|
||||
delete(s.peersBySID, e.sid)
|
||||
s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) Close() {
|
||||
if s.lk != nil {
|
||||
s.lk.Close()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user