Parcourir la source

Added vpn connection methods on AutoConnectService class

Khubaib il y a 4 mois
Parent
commit
e66c4f6b96

+ 656 - 10
app/src/main/java/com/vpn/fastestvpnservice/utils/AutoConnectService.kt

@@ -5,7 +5,9 @@ import android.app.Notification
 import android.app.NotificationChannel
 import android.app.NotificationManager
 import android.app.Service
+import android.content.BroadcastReceiver
 import android.content.ComponentName
+import android.content.Context
 import android.content.Intent
 import android.content.IntentFilter
 import android.content.ServiceConnection
@@ -14,31 +16,53 @@ import android.net.ConnectivityManager
 import android.net.wifi.ScanResult
 import android.net.wifi.SupplicantState
 import android.net.wifi.WifiManager
+import android.os.AsyncTask
 import android.os.Binder
 import android.os.Build
 import android.os.CountDownTimer
+import android.os.Handler
 import android.os.IBinder
+import android.os.RemoteException
 import android.util.Log
 import androidx.core.app.ActivityCompat
+import androidx.localbroadcastmanager.content.LocalBroadcastManager
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+import com.vpn.fastestvpnservice.MainActivity
 import com.vpn.fastestvpnservice.R
 import com.vpn.fastestvpnservice.beans.AutoConnectModel
+import com.vpn.fastestvpnservice.constants.AppConstant
+import com.vpn.fastestvpnservice.constants.AppEnum
 import com.vpn.fastestvpnservice.constants.smartConnect
+import com.vpn.fastestvpnservice.constants.splitList
 import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper
-import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.homeViewModel1
-import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.isHomeViewModel1
-import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.isVpnConnectionsUtil
-import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.vpnConnectionsUtil
+import com.vpn.fastestvpnservice.openVpnUtils.EncryptData
 import com.vpn.fastestvpnservice.screens.settingsScreenAll.autoConnectCallback
-import com.vpn.fastestvpnservice.utils.WireGuardService.IkevConnectionStatesReceiverWidget
+import com.vpn.fastestvpnservice.widgets.SimpleAppWidget
+import com.wireguard.android.backend.GoBackend
+import com.wireguard.android.backend.Tunnel
+import com.wireguard.config.Config
+import com.wireguard.config.InetEndpoint
+import com.wireguard.config.InetNetwork
+import com.wireguard.config.Interface
+import de.blinkt.openvpn.LaunchVPN
 import de.blinkt.openvpn.VpnProfile
 import de.blinkt.openvpn.core.App
 import de.blinkt.openvpn.core.ConfigParser
+import de.blinkt.openvpn.core.ConnectionStatus
 import de.blinkt.openvpn.core.IOpenVPNServiceInternal
+import de.blinkt.openvpn.core.OpenVPNService
 import de.blinkt.openvpn.core.ProfileManager
+import de.blinkt.openvpn.core.VpnStatus
+import org.json.JSONObject
+import org.strongswan.android.logic.CharonVpnService
+import org.strongswan.android.ui.VpnProfileControlActivity
 import java.io.BufferedReader
 import java.io.InputStream
+import java.io.InputStreamReader
+import java.util.SortedSet
 
-class AutoConnectService : Service() {
+class AutoConnectService : Service(), VpnStatus.StateListener {
 
     private var wifiScanReceiver: WifiScanReceiver? = null
     private var wifiManager: WifiManager? = null
@@ -52,6 +76,7 @@ class AutoConnectService : Service() {
             get() = this@AutoConnectService
     }
 
+    lateinit var basePreferenceHelper: BasePreferenceHelper
     var countDownTimer: CountDownTimer? = null
 
 //    /*IKEV2*/
@@ -70,12 +95,12 @@ class AutoConnectService : Service() {
         override fun onServiceConnected(className: ComponentName, service: IBinder) {
 
             App.mService = IOpenVPNServiceInternal.Stub.asInterface(service)
-            Log.d("wg test s tcp wid", "onServiceConnected widget ${App.mService}")
+            Log.d("auto_conn tcp osc", "onServiceConnected widget ${App.mService}")
 
         }
 
         override fun onServiceDisconnected(arg0: ComponentName) {
-            Log.d("wg test s tcp", "onServiceDisconnected")
+            Log.d("auto_conn tcp osd", "onServiceDisconnected")
 
             App.mService = null
         }
@@ -83,7 +108,7 @@ class AutoConnectService : Service() {
 
     companion object {
         /*IKEV2*/
-        lateinit var ikevConnectionStatesReceiver: IkevConnectionStatesReceiverWidget
+        lateinit var ikevConnectionStatesReceiverAutoConnect: IkevConnectionStatesReceiverAutoConnect
     }
 
     override fun onCreate() {
@@ -100,6 +125,7 @@ class AutoConnectService : Service() {
     override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
 
         startForegroundNotification()
+        startListenerIKEV2()
 
         return START_STICKY
     }
@@ -141,7 +167,7 @@ class AutoConnectService : Service() {
         }
 
         // currently commenting below ...
-        val basePreferenceHelper = BasePreferenceHelper(applicationContext)
+        basePreferenceHelper = BasePreferenceHelper(applicationContext)
         wifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
         val scanResults = wifiManager?.scanResults
         Log.d("AutoConnectService", "Job scanResults + " + scanResults?.size)
@@ -235,12 +261,15 @@ class AutoConnectService : Service() {
 
                     if (isTrustedWifiConnected && isConnect == App.CONNECTED) {
                         Log.d("AutoConnectService", "Disconnect VPN")
+                        stopVpn()
                     }
                     else if (!isTrustedWifiConnected && isConnect == App.DISCONNECTED) {
                         Log.d("AutoConnectService", "Connect VPN")
+                        startVpn()
                     }
                     else if (isTrustedWifiConnected && isConnect == App.CONNECTING) {
                         Log.d("AutoConnectService", "Connecting VPN")
+                        stopVpn()
                     }
                 }
             }
@@ -248,8 +277,625 @@ class AutoConnectService : Service() {
 
     }
 
+    fun connectVpn() {
+
+        basePreferenceHelper = BasePreferenceHelper(applicationContext)
+        val connectState = basePreferenceHelper.getConnectState()
+        Log.d("auto_conn connectVpn", "connectState = $connectState")
+        if (connectState == App.DISCONNECTED) {
+            startVpn()
+        }
+        else if (connectState == App.CONNECTED ||
+            connectState == App.CONNECTING) {
+
+            Log.d("testing func", "1")
+            stopVpn()
+            Log.d("testing func", "3")
+
+        }
+        else if (connectState == App.CONNECTION_STATE_SERVER_NOT_RESPONDING) {
+            startTcpUDP()
+        }
+    }
+
+    fun startVpn() {
+        countDownTimer()
+        try {
+            basePreferenceHelper = BasePreferenceHelper(applicationContext)
+            Log.d("auto_conn startVpn", App.connection_status.toString())
+            if (CheckInternetConnection.getInternetConnection(applicationContext).isConnectedToInternet) {
+                if (basePreferenceHelper.getProtocol().title.toLowerCase()
+                        .contentEquals(AppEnum.WG_PROTOCOL.key.toLowerCase())
+                ) {
+                    /*Connect Wire-Guard*/
+                    MainActivity.isWGDown = true
+                    vpnWireGuardPermission(true)
+                }
+                else if (basePreferenceHelper.getProtocol().title.contentEquals(AppEnum.IKEV2_PROTOCOL.key))
+                {
+
+                    basePreferenceHelper.getConnectedServer().let { server ->
+
+                        /*Connect IKEV2*/
+                        Log.d("auto_conn onstart", "IKEv2 Connection")
+
+//                            startListenerIKEV2()
+//                        App.createIKEV2Listener()
+
+                        val intent = Intent(applicationContext, VpnProfileControlActivity::class.java)
+                        App.connection_status = App.CONNECTION_STATE_CONNECTING
+                        MainActivity.vpnConnectionCallBacks?.onVpnConnecting()
+
+                        basePreferenceHelper.setConnectState(App.CONNECTING)
+                        val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+                        widgetIntent.action = SimpleAppWidget.ACTION_CONNECTING_VPN
+                        applicationContext?.sendBroadcast(widgetIntent)
+
+                        intent.action = VpnProfileControlActivity.START_PROFILE
+                        intent.putExtra(VpnProfileControlActivity.EXTRA_VPN_PROFILE_ID, server?.id)
+                        intent.putExtra(AppConstant.SERVER, Gson().toJson(server))
+                        intent.putExtra("username", basePreferenceHelper.getUser()?.userinfo?.email)
+                        intent.putExtra("password", basePreferenceHelper.getPassword()
+                        )
+                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+                        applicationContext.startActivity(intent)
+
+                    }
+
+                    /* setting receiver to listen ikev2 protocol connection states */
+                }
+                else {
+
+                    startTcpUDP()
+                }
+            }
+        } catch (e: Exception) {
+            e.printStackTrace()
+        }
+    }
+
+    fun startTcpUDP() {
+        Log.d("auto_conn startVpn", "startTcpUDP()")
+
+        countDownTimer?.start()
+
+        /*Connect UDP,TCP*/
+        App.connection_status = App.CONNECTION_STATE_CONNECTING
+        MainActivity.vpnConnectionCallBacks?.onVpnConnecting()
+
+        basePreferenceHelper.setConnectState(App.CONNECTING)
+
+        val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+        widgetIntent.action = SimpleAppWidget.ACTION_CONNECTING_VPN
+        applicationContext?.sendBroadcast(widgetIntent)
+
+        try {
+            Log.d("auto_conn startVpn", "startTcpUDP() try")
+
+            VpnStatus.addStateListener(this)
+            val intent = Intent(applicationContext, OpenVPNService::class.java)
+            intent.action = OpenVPNService.START_SERVICE
+            applicationContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
+        } catch (e: Exception) {
+            Log.d("auto_conn startVpn", "startTcpUDP() catch")
+
+            e.printStackTrace()
+        }
+
+        try {
+            inputStream = null
+            bufferedReader = null
+            inputStream = getJsonFileDetails()
+            assert(inputStream != null)
+            bufferedReader =
+                BufferedReader(InputStreamReader(inputStream /*, Charset.forName("UTF-8")*/))
+            cp = ConfigParser(applicationContext)
+            cp!!.parseConfig(bufferedReader)
+            vp = cp!!.convertProfile()
+
+            ///////////////// openvpn split tunneling start /////////////////
+            val type = object : TypeToken<SortedSet<String?>?>() {}.type
+
+            val selectedApps = Gson().fromJson<SortedSet<String>>(
+                basePreferenceHelper.getSplitTunneledApps(), type
+            )
+            val selectedAppsNoVpn = Gson().fromJson<SortedSet<String>>(
+                basePreferenceHelper.getSplitTunneledAppsNotAllow(), type
+            )
+
+            basePreferenceHelper.getSplitPosition().let {
+                when (it) {
+                    splitList[0] -> {
+                    }
+                    splitList[1] -> {
+                        if (selectedApps != null && selectedApps.size > 0) {
+                            for (app in selectedApps) {
+                                try {
+                                    vp?.mAllowedAppsVpn?.add(app)
+                                    Log.d("packages Vpn", app)
+                                } catch (e: PackageManager.NameNotFoundException) {
+                                    e.printStackTrace()
+                                }
+                            }
+                        }
+                    }
+                    splitList[2] -> {
+                        if (selectedAppsNoVpn != null && selectedAppsNoVpn.size > 0) {
+                            for (app in selectedAppsNoVpn) {
+                                try {
+                                    vp?.mAllowedAppsVpn?.add(app)
+                                    Log.d("packages NoVpn", app)
+                                } catch (e: PackageManager.NameNotFoundException) {
+                                    e.printStackTrace()
+                                }
+                            }
+                        }
+                    }
+                }
+            }   // Android
+
+            ///////////////// openvpn split tunneling end /////////////////
+            vp?.mAllowedAppsVpnAreDisallowed = false
+            val En = EncryptData()
+            val AppDetailsValues = En.decrypt(basePreferenceHelper.getAppDetails())
+            Log.d("auto_conn startVpn", "startTcpUDP() $AppDetailsValues")
+
+            val json_response = JSONObject(AppDetailsValues)
+            val jsonArray = json_response.getJSONArray("blocked")
+            for (i in 0 until jsonArray.length()) {
+                val json_object = jsonArray.getJSONObject(i)
+                vp?.mAllowedAppsVpn?.add(json_object.getString("app"))
+                Log.e("packages end", json_object.getString("app"))
+            }
+
+            vp?.mName = Build.MODEL
+            vp?.mUsername = basePreferenceHelper.getUser()?.userinfo?.email
+            vp?.mPassword = basePreferenceHelper.getPassword()
+            pm = ProfileManager.getInstance(applicationContext)
+            pm?.addProfile(vp)
+            pm?.saveProfileList(applicationContext)
+            pm?.saveProfile(applicationContext, vp)
+            vp = pm?.getProfileByName(Build.MODEL)
+            val intent = Intent(applicationContext, LaunchVPN::class.java)
+            intent.putExtra(LaunchVPN.EXTRA_KEY, vp?.uuid.toString())
+            intent.action = Intent.ACTION_MAIN
+            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+            applicationContext.startActivity(intent)
+        }
+        catch (e: Exception) {
+            e.printStackTrace()
+
+        }
+    }
+
+    fun startListenerIKEV2() {
+        try {
+            ikevConnectionStatesReceiverAutoConnect = IkevConnectionStatesReceiverAutoConnect()
+            val filter = IntentFilter()
+            filter.addAction(CharonVpnService.ACTION_VPN_CONNECTED)
+            filter.addAction(CharonVpnService.ACTION_VPN_NOT_CONNECTED)
+            filter.addAction(CharonVpnService.ACTION_VPN_CONNECTING)
+            filter.addAction(CharonVpnService.ACTION_VPN_SERVER_NOT_RESPONDING)
+            filter.addAction(CharonVpnService.ACTION_VPN_DISABLED)
+            LocalBroadcastManager.getInstance(applicationContext)
+                .registerReceiver(ikevConnectionStatesReceiverAutoConnect, filter)
+        } catch (e: Exception) {
+            e.printStackTrace()
+        }
+    }
+
+    fun stopVpn() {
+        Log.d("auto_conn", "2")
+
+        try {
+            basePreferenceHelper = BasePreferenceHelper(applicationContext)
+
+            val connectState = basePreferenceHelper.getConnectState()
+            Log.d("auto_conn stopVpn", "connectState = $connectState")
+
+            /*Disconnect Wireguard*/
+            if (basePreferenceHelper.getProtocol().title.toLowerCase()
+                    .contentEquals(AppEnum.WG_PROTOCOL.key.toLowerCase())
+            )
+            {
+                vpnWireGuardPermission(false)
+            }
+            else if (basePreferenceHelper.getProtocol().title.contentEquals(AppEnum.IKEV2_PROTOCOL.key))
+            {
+                /*Disconnect IKEV2*/
+                val intent = Intent(applicationContext, VpnProfileControlActivity::class.java)
+                intent.action = VpnProfileControlActivity.DISCONNECT
+                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+                applicationContext.startActivity(intent)
+
+                basePreferenceHelper.setConnectState(App.DISCONNECTED)
+                val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+                widgetIntent.action = SimpleAppWidget.ACTION_DISCONNECT_VPN
+                applicationContext?.sendBroadcast(widgetIntent)
+
+//                App.connection_status = App.CONNECTION_STATE_DISCONNECTED
+//                MainActivity.vpnConnectionCallBacks?.onVpnDisconnected()
+            }
+            else {
+
+//                applicationContext.unbindService(mConnection)
+
+                Log.d("auto_conn msr mcon", App.mService.toString() + " " + mConnection.toString())
+
+                /*Disconnect TCP,UDP*/
+                App.connection_status = App.CONNECTION_STATE_DISCONNECTED
+                MainActivity.vpnConnectionCallBacks?.onVpnDisconnected()
+
+                val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+                widgetIntent.action = SimpleAppWidget.ACTION_DISCONNECT_VPN
+                applicationContext?.sendBroadcast(widgetIntent)
+
+                basePreferenceHelper.setConnectState(App.DISCONNECTED)
+                OpenVPNService.abortConnectionVPN = true
+                ProfileManager.setConntectedVpnProfileDisconnected(applicationContext)
+
+                if (App.mService != null) {
+                    try {
+                        Log.d("auto_conn msr1 try", App.mService.toString())
+
+                        App.mService!!.stopVPN(false)
+                    } catch (e: RemoteException) {
+                        e.printStackTrace()
+                    }
+                    try {
+                        Log.d("auto_conn msr2 try", App.mService.toString())
+
+                        pm = ProfileManager.getInstance(applicationContext)
+                        vp = pm?.getProfileByName(Build.MODEL)
+                        pm?.removeProfile(applicationContext, vp)
+                    } catch (e: Exception) {
+                        e.printStackTrace()
+                    }
+                }
+            }
+
+            val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+            widgetIntent.action = SimpleAppWidget.ACTION_STOP_SERVICE
+            applicationContext.sendBroadcast(widgetIntent)
+
+            Handler().postDelayed({
+                try {
+                    LocalBroadcastManager.getInstance(applicationContext)
+                        .unregisterReceiver(ikevConnectionStatesReceiverAutoConnect)
+
+                } catch (e: Exception) {
+                    e.printStackTrace()
+                }
+            }, 500)
+
+        } catch (e: Exception) {
+            e.printStackTrace()
+        }
+    }
+
+    fun vpnWireGuardPermission(isUp: Boolean) {
+
+        try{
+            vpnWireGuard(isUp)
+//            val intentPrepare: Intent = GoBackend.VpnService.prepare(context)
+//            if (intentPrepare != null) {
+//                context.startActivity(intentPrepare)
+//            }
+        }catch (e :Exception){
+        }
+    }
+
+    fun vpnWireGuard(isUp: Boolean) {
+        AsyncTask.execute {
+            try {
+                basePreferenceHelper = BasePreferenceHelper(applicationContext)
+
+                Log.d("auto_conn wg", "${App.tunnelStatus}, ${App.getTunnel()}, ${App.backend}, ${App.peerBuilder}")
+
+
+                if (isUp) {
+                    App.connection_status = App.CONNECTION_STATE_UP_WG
+                    App.tunnelStatus = Tunnel.State.UP
+                    App.backend = GoBackend(App.getContext())
+                    MainActivity.vpnConnectionCallBacks?.onVpnConnected()
+
+                    basePreferenceHelper.setConnectState(App.CONNECTED)
+
+                    val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+                    widgetIntent.action = SimpleAppWidget.ACTION_CONNECT_VPN
+                    applicationContext?.sendBroadcast(widgetIntent)
+
+                } else {
+                    App.connection_status = App.CONNECTION_STATE_DOWN_WG
+                    App.tunnelStatus = Tunnel.State.DOWN
+                    MainActivity.vpnConnectionCallBacks?.onVpnDisconnected()
+
+                    basePreferenceHelper.setConnectState(App.DISCONNECTED)
+
+                    val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+                    widgetIntent.action = SimpleAppWidget.ACTION_DISCONNECT_VPN
+                    applicationContext?.sendBroadcast(widgetIntent)
+                }
+
+                basePreferenceHelper.getSplitPosition().let {
+                    when(it){
+                        splitList[0] -> {
+                            App.backend.setState(App.getTunnel(), App.tunnelStatus, createWireGuardConfiguration()?.build())
+                        }
+                        splitList[1] -> {
+                            App.backend.setState(App.getTunnel(), App.tunnelStatus, createWireGuardConfigurationInclude()?.build())
+                        }
+                        splitList[2] -> {
+                            App.backend.setState(App.getTunnel(), App.tunnelStatus, createWireGuardConfigurationExclude()?.build())
+                        }
+                        else -> {}
+                    }
+                }
+
+//                App.backend.setState(App.getTunnel(), App.tunnelStatus, createWireGuardConfiguration()?.build())
+
+            } catch (e: java.lang.Exception) {
+                e.printStackTrace()
+            }
+        }
+
+    }
+
+    fun createWireGuardConfiguration(): Config.Builder? {
+        return try {
+            basePreferenceHelper = BasePreferenceHelper(applicationContext)
+            var dnswg = if (basePreferenceHelper.getAdBlockState()) {
+                "10.8.8.8"
+            } else {
+                "10.9.9.9"
+            }
+            val prefHelper = BasePreferenceHelper(App.getContext().applicationContext)
+            val interfaceBuilder = Interface.Builder()
+            val builder = Config.Builder()
+            builder.setInterface(
+                interfaceBuilder.addAddress(InetNetwork.parse(prefHelper.getWireGuard()!!.ip + "/32"))
+                    .parsePrivateKey(prefHelper.getWireGuard()!!.key)
+                    .parseDnsServers(dnswg)
+                    .build()
+            ).addPeer(
+                App.peerBuilder.addAllowedIp(InetNetwork.parse("0.0.0.0/0"))
+                    .setEndpoint(InetEndpoint.parse(prefHelper.getConnectedServer()!!.dns + ":51820"))
+                    .parsePublicKey(prefHelper.getConnectedServer()!!.wg_key)
+                    .build()
+            )
+            builder
+        } catch (e: java.lang.Exception) {
+            e.printStackTrace()
+            null
+        }
+    }
+
+    fun createWireGuardConfigurationInclude(): Config.Builder? {
+        return try {
+            basePreferenceHelper = BasePreferenceHelper(applicationContext)
+            val type = object : TypeToken<SortedSet<String?>?>() {}.type
+            val selectedApps = Gson().fromJson<SortedSet<String>>(
+                basePreferenceHelper.getSplitTunneledApps(), type
+            )
+            val selectedAppsNoVpn = Gson().fromJson<SortedSet<String>>(
+                basePreferenceHelper.getSplitTunneledAppsNotAllow(), type
+            )
+
+            val dnswg = if (basePreferenceHelper.getAdBlockState()) {
+                "10.8.8.8"
+            } else {
+                "10.9.9.9"
+            }
+            val prefHelper = BasePreferenceHelper(App.getContext().applicationContext)
+            val interfaceBuilder = Interface.Builder()
+            val builder = Config.Builder()
+            builder.setInterface(
+                interfaceBuilder.addAddress(InetNetwork.parse(prefHelper.getWireGuard()!!.ip + "/32"))
+                    .parsePrivateKey(prefHelper.getWireGuard()!!.key)
+                    .parseDnsServers(dnswg)
+                    .includeApplications(selectedApps)
+                    .build()
+            ).addPeer(
+                App.peerBuilder.addAllowedIp(InetNetwork.parse("0.0.0.0/0"))
+                    .setEndpoint(InetEndpoint.parse(prefHelper.getConnectedServer()!!.dns + ":51820"))
+                    .parsePublicKey(prefHelper.getConnectedServer()!!.wg_key)
+                    .build()
+            )
+            builder
+        } catch (e: java.lang.Exception) {
+            e.printStackTrace()
+            null
+        }
+    }
+
+    fun createWireGuardConfigurationExclude(): Config.Builder? {
+        return try {
+            basePreferenceHelper = BasePreferenceHelper(applicationContext)
+            val type = object : TypeToken<SortedSet<String?>?>() {}.type
+            val selectedApps = Gson().fromJson<SortedSet<String>>(
+                basePreferenceHelper.getSplitTunneledApps(), type
+            )
+            val selectedAppsNoVpn = Gson().fromJson<SortedSet<String>>(
+                basePreferenceHelper.getSplitTunneledAppsNotAllow(), type
+            )
+
+            val dnswg = if (basePreferenceHelper.getAdBlockState()) {
+                "10.8.8.8"
+            } else {
+                "10.9.9.9"
+            }
+            val prefHelper = BasePreferenceHelper(App.getContext().applicationContext)
+            val interfaceBuilder = Interface.Builder()
+            val builder = Config.Builder()
+            builder.setInterface(
+                interfaceBuilder.addAddress(InetNetwork.parse(prefHelper.getWireGuard()!!.ip + "/32"))
+                    .parsePrivateKey(prefHelper.getWireGuard()!!.key)
+                    .parseDnsServers(dnswg)
+                    .includeApplications(selectedAppsNoVpn)
+                    .build()
+            ).addPeer(
+                App.peerBuilder.addAllowedIp(InetNetwork.parse("0.0.0.0/0"))
+                    .setEndpoint(InetEndpoint.parse(prefHelper.getConnectedServer()!!.dns + ":51820"))
+                    .parsePublicKey(prefHelper.getConnectedServer()!!.wg_key)
+                    .build()
+            )
+            builder
+        } catch (e: java.lang.Exception) {
+            e.printStackTrace()
+            null
+        }
+    }
+
+    fun countDownTimer() {
+
+        countDownTimer = object : CountDownTimer(32000, 1000) {
+            override fun onTick(millisUntilFinished: Long) {
+                val connectState = basePreferenceHelper.getConnectState()
+                if (connectState == App.CONNECTED) {
+                    MainActivity.vpnConnectionCallBacks?.onVpnConnected()
+                    val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+                    widgetIntent.action = SimpleAppWidget.ACTION_CONNECT_VPN
+                    applicationContext?.sendBroadcast(widgetIntent)
+                    basePreferenceHelper.setConnectState(App.CONNECTED)
+                    countDownTimer!!.cancel()
+                }
+            }
+
+            override fun onFinish() {
+                val connectState = basePreferenceHelper.getConnectState()
+                if (connectState == App.CONNECTING) {
+                    stopVpn()
+                }
+            }
+        }
+
+    }
+
+    inner class IkevConnectionStatesReceiverAutoConnect : BroadcastReceiver() {
+        override fun onReceive(context: Context?, intent: Intent?) {
+            if (intent != null && intent.action != null) {
+                basePreferenceHelper = BasePreferenceHelper(applicationContext)
+                val connectState = basePreferenceHelper.getConnectState()
+                val action = intent.action
+                when (action) {
+                    CharonVpnService.ACTION_VPN_CONNECTED -> {
+                        App.connection_status = App.CONNECTION_STATE_CONNECTED
+                        MainActivity.vpnConnectionCallBacks?.onVpnConnected()
+
+//                        basePreferenceHelper.setConnectState(App.CONNECTED)
+                        val connectState1 = basePreferenceHelper.getConnectState()
+                        Log.d("auto_conn ip w", "ACTION_VPN_CONNECTED widget $connectState $connectState1")
+//                        if (connectState1 == 2) {
+//                            val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+//                            widgetIntent.action = SimpleAppWidget.ACTION_CONNECT_VPN
+//                            applicationContext?.sendBroadcast(widgetIntent)
+//                        }
+                    }
+                    CharonVpnService.ACTION_VPN_DISABLED -> {
+                        Log.d("auto_conn ip w", "ACTION_VPN_DISABLED widget $connectState")
+
+                        if (connectState == App.CONNECTING)
+                        {
+                            Log.d("auto_conn ip w", "ACTION_VPN_DISABLED ==> $connectState")
+                            App.connection_status = App.CONNECTION_STATE_CONNECTING
+                            MainActivity.vpnConnectionCallBacks?.onVpnConnecting()
+
+                            basePreferenceHelper.setConnectState(App.CONNECTING)
+
+                            val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+                            widgetIntent.action = SimpleAppWidget.ACTION_CONNECTING_VPN
+                            applicationContext?.sendBroadcast(widgetIntent)
+                        }
+                        else {
+                            Log.d("auto_conn ip w",
+                                "ACTION_VPN_DISABLED ==> else $connectState"
+                            )
+                            App.connection_status = App.CONNECTION_STATE_DISCONNECTED
+                            MainActivity.vpnConnectionCallBacks?.onVpnDisconnected()
+
+                            basePreferenceHelper.setConnectState(App.DISCONNECTED)
+
+                            val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+                            widgetIntent.action = SimpleAppWidget.ACTION_DISCONNECT_VPN
+                            applicationContext?.sendBroadcast(widgetIntent)
+//                          MainActivity.vpnConnectionCallBacks?.onGetIp()
+                        }
+                    }
+                    CharonVpnService.ACTION_VPN_NOT_CONNECTED -> {
+                        Log.d("auto_conn ip w", "ACTION_VPN_NOT_CONNECTED widget $connectState")
+                    }
+                    CharonVpnService.ACTION_VPN_CONNECTING -> {
+                        val connectState1 = basePreferenceHelper.getConnectState()
+                        Log.d("auto_conn ip w", "ACTION_VPN_CONNECTING widget $connectState1")
+                        App.connection_status = App.CONNECTION_STATE_CONNECTING
+                        MainActivity.vpnConnectionCallBacks?.onVpnConnecting()
+
+                        basePreferenceHelper.setConnectState(App.CONNECTING)
+
+                        val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+                        widgetIntent.action = SimpleAppWidget.ACTION_CONNECTING_VPN
+                        applicationContext?.sendBroadcast(widgetIntent)
+                    }
+                    CharonVpnService.ACTION_VPN_SERVER_NOT_RESPONDING -> {
+                        Log.d("auto_conn ip w", "ACTION_VPN_SERVER_NOT_RESPONDING widget")
+                        App.connection_status = App.CONNECTION_STATE_SERVER_NOT_RESPONDING
+                        if (basePreferenceHelper.getProtocol().index == 0)
+                        {
+                            Log.d("auto_conn ip w", "ACTION_VPN_SERVER_NOT_RESPONDING tcp/udp")
+                            startTcpUDP()
+                        } else {
+                            basePreferenceHelper.setConnectState(App.DISCONNECTED)
+                            val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+                            widgetIntent.action = SimpleAppWidget.ACTION_DISCONNECT_VPN
+                            applicationContext?.sendBroadcast(widgetIntent)
+                        }
+                        MainActivity.vpnConnectionCallBacks?.onServerNotResponding()
+                        val widgetIntent = Intent(applicationContext, SimpleAppWidget::class.java)
+                        widgetIntent.action = SimpleAppWidget.ACTION_SERVER_NOT_RESPONDING
+                        applicationContext?.sendBroadcast(widgetIntent)
+                    }
+                }
+            }
+        }
+    }
+
+    private fun getJsonFileDetails(): InputStream? {
+        var conf: InputStream? = null
+        try {
+            conf = if (basePreferenceHelper.getProtocol().title.equals(AppEnum.TCP_PROTOCOL.key)) {
+                applicationContext.assets.open("fileDetails/tcp.ovpn")
+            } else {
+                applicationContext.assets.open("fileDetails/udp.ovpn")
+            }
+
+            return conf
+        } catch (e: java.lang.Exception) {
+            e.printStackTrace()
+        }
+        return null
+    }
+
+    override fun onDestroy() {
+        super.onDestroy()
+
+        if (wifiScanReceiver != null) {
+            Log.d("auto_conn", "unregisterReceiver(wifiScanReceiver)")
+            unregisterReceiver(wifiScanReceiver)
+        }
+    }
 
     override fun onBind(intent: Intent?): IBinder? {
         return binder
     }
+
+    override fun updateState(
+        state: String?,
+        logmessage: String?,
+        localizedResId: Int,
+        level: ConnectionStatus?
+    ) {
+    }
+
+    override fun setConnectedVPN(uuid: String?) {
+    }
 }