Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## 0.3.0
* Support of latest Android and iOS
* Improvements on example app
* Updates from RandomModderJDK

## 0.2.3

Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
package com.victorblaess.native_flutter_proxy

import android.content.BroadcastReceiver
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Proxy
import android.net.ProxyInfo
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.core.content.ContextCompat.getSystemService
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.util.LinkedHashMap

class FlutterProxyPlugin : FlutterPlugin, MethodCallHandler {

class FlutterProxyPlugin : FlutterPlugin, MethodCallHandler, BroadcastReceiver() {

private var methodChannel: MethodChannel? = null
private var context: Context? = null

private fun setupChannel(messenger: BinaryMessenger) {
methodChannel = MethodChannel(messenger, "native_flutter_proxy")
Expand All @@ -19,25 +32,88 @@ class FlutterProxyPlugin : FlutterPlugin, MethodCallHandler {

override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
setupChannel(binding.binaryMessenger)
context = binding.applicationContext

// initial default proxy, that could not be captured beforehand
val pi = refreshProxyInfo(null) // this does not look consider proxies from PAC
Log.d("ProxyChangeReceiver", "Properties: ${System.getProperty("http.proxyHost")}:${System.getProperty("http.proxyPort")}")
Log.d("ProxyChangeReceiver", "ProxyInfo without intent: ${pi?.host}:${pi?.port}")

context!!.registerReceiver(this, IntentFilter(Proxy.PROXY_CHANGE_ACTION))
}

override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel?.setMethodCallHandler(null)
methodChannel = null
context!!.unregisterReceiver(this)
context = null
}

override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "getProxySetting") {
result.success(getProxySetting())
result.success(proxySetting)
} else {
result.notImplemented()
}
}

private fun getProxySetting(): Any? {
val map = LinkedHashMap<String, Any?>()
map["host"] = System.getProperty("http.proxyHost")
map["port"] = System.getProperty("http.proxyPort")
return map
private val proxySetting: LinkedHashMap<String, Any?> = LinkedHashMap<String, Any?>()

override fun onReceive(context: Context, intent: Intent) {
if (Proxy.PROXY_CHANGE_ACTION == intent.action) {
// Handle the proxy change here
Log.d("ProxyChangeReceiver", "Proxy settings changed")
val pi = refreshProxyInfo(intent)
Log.d("ProxyChangeReceiver", "ProxyInfo: ${pi?.host}:${pi?.port}")
methodChannel!!.invokeMethod("proxyChangedCallback", proxySetting)
}
}

/**
* Get system proxy and update cache with optional intent argument needed for PAC.
*/
private fun refreshProxyInfo(intent: Intent?): ProxyInfo? {
val connectivityManager = getSystemService(context!!,ConnectivityManager::class.java)
var info: ProxyInfo? = connectivityManager!!.defaultProxy
if (info == null) {
proxySetting["host"] = null
proxySetting["port"] = null
return null
}

// If a proxy is configured using the PAC file use
// Android's injected localhost HTTP proxy.
//
// Android's injected localhost proxy can be accessed using a proxy host
// equal to `localhost` and a proxy port retrieved from intent's 'extras'.
// We cannot take a proxy port from the ProxyInfo object that's exposed by
// the connectivity manager as it's always equal to -1 for cases when PAC
// proxy is configured.
if (info.pacFileUrl != null && info.pacFileUrl !== Uri.EMPTY) {
if (intent == null) {
proxySetting["host"] = null
proxySetting["port"] = null
// PAC proxies are supported only when Intent is present
return null
}

val extras = intent.extras
if (extras == null) {
proxySetting["host"] = null
proxySetting["port"] = null
return null
}

info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
extras.getParcelable("android.intent.extra.PROXY_INFO", ProxyInfo::class.java)
} else {
@Suppress("DEPRECATION")
extras.getParcelable("android.intent.extra.PROXY_INFO") as? ProxyInfo
}
}

proxySetting["host"] = info!!.host
proxySetting["port"] = info.port
return info
}
}
12 changes: 9 additions & 3 deletions example/lib/app.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'data/models/proxy_info.dart';
Expand All @@ -6,9 +7,9 @@ import 'view/screens/proxy_screen.dart';
export 'data/models/proxy_info.dart';

class App extends StatelessWidget {
const App({super.key, required this.proxyInfo});
const App({super.key, required this.proxyInfoListenable});

final ProxyInfo proxyInfo;
final ValueListenable<ProxyInfo> proxyInfoListenable;

@override
Widget build(BuildContext context) {
Expand Down Expand Up @@ -60,7 +61,12 @@ class App extends StatelessWidget {
scaffoldBackgroundColor: const Color(0xFFF7EFE6),
textTheme: textTheme,
),
home: ProxyScreen(info: proxyInfo),
home: ValueListenableBuilder<ProxyInfo>(
valueListenable: proxyInfoListenable,
builder: (context, info, _) {
return ProxyScreen(info: info);
},
),
);
}
}
83 changes: 53 additions & 30 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,44 +1,67 @@
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:native_flutter_proxy/native_flutter_proxy.dart';

import 'app.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();

bool enabled = false;
String? host;
int? port;
bool applied = false;
String? error;
final proxyInfoNotifier = ValueNotifier<ProxyInfo>(
const ProxyInfo(enabled: false, applied: false),
);

Future<void> updateProxyInfo(ProxySetting settings) async {
final enabled = settings.enabled;
final host = settings.host;
final port = settings.port;
var applied = false;

if (enabled && host != null) {
final proxy = CustomProxy(ipAddress: host, port: port);
proxy.enable();
applied = true;
debugPrint('====\nProxy enabled\n====');
} else {
HttpOverrides.global = null;
debugPrint('====\nProxy disabled\n====');
}

proxyInfoNotifier.value = ProxyInfo(
enabled: enabled,
applied: applied,
host: host,
port: port,
);
}

Future<void> handleError(Object error) async {
HttpOverrides.global = null;
final message = error.toString();
debugPrint(message);
proxyInfoNotifier.value = ProxyInfo(
enabled: false,
applied: false,
error: message,
);
}

try {
ProxySetting settings = await NativeProxyReader.proxySetting;
enabled = settings.enabled;
host = settings.host;
port = settings.port;
final settings = await NativeProxyReader.proxySetting;
await updateProxyInfo(settings);
} catch (e) {
error = e.toString();
debugPrint(error);
await handleError(e);
}

if (enabled && host != null) {
final proxy = CustomProxy(ipAddress: host, port: port);
proxy.enable();
applied = true;
debugPrint("====\nProxy enabled\n====");
} else {
debugPrint("====\nProxy disabled\n====");
}
NativeProxyReader.setProxyChangedCallback((settings) async {
debugPrint('Callback for proxy change was used');
try {
await updateProxyInfo(settings);
} catch (e) {
await handleError(e);
}
});

runApp(
App(
proxyInfo: ProxyInfo(
enabled: enabled,
applied: applied,
host: host,
port: port,
error: error,
),
),
);
runApp(App(proxyInfoListenable: proxyInfoNotifier));
}
Loading