no message

merge-requests/589/head
Zohaib Iqbal Kambrani 4 years ago
parent ff508de9f7
commit a8e1ba6b86

@ -2,26 +2,28 @@ package com.ejada.hmg.hmgwifi
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.net.ConnectivityManager import android.content.Intent
import android.net.Network import android.net.*
import android.net.NetworkCapabilities import android.net.wifi.*
import android.net.NetworkRequest
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSpecifier
import android.os.Build import android.os.Build
import android.os.PatternMatcher
import android.provider.Settings
import android.util.Log import android.util.Log
import androidx.annotation.RequiresApi import androidx.annotation.RequiresApi
import com.ejada.hmg.MainActivity import com.ejada.hmg.MainActivity
import com.ejada.hmg.utils.HMGUtils import com.ejada.hmg.utils.HMGUtils
class HMG_Guest(private var context: MainActivity) {
private var wifiManager: WifiManager? = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
class HMG_Guest(private var context: MainActivity, ssid: String) {
private val TAG = "HMG_Guest" private val TAG = "HMG_Guest"
private val TEST = false private val TEST = false
private var SSID = """"HMG-MobileApp"""" private var SSID = ssid
// private var SSID = "HMG-MOHEMM"
val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
private lateinit var completionListener: ((status: Boolean, message: String) -> Unit) private lateinit var completionListener: ((status: Boolean, message: String) -> Unit)
@ -29,23 +31,30 @@ class HMG_Guest(private var context: MainActivity) {
completionListener(status, message) completionListener(status, message)
} }
fun enableWifi(){
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.Q){
wifiManager?.setWifiEnabled(true)
HMGUtils.popFlutterText(context,"enablingWifi");
HMGUtils.timer(2000,false){
connectApiLessThen29()
}
}else {
val panelIntent = Intent(Settings.Panel.ACTION_WIFI)
context.startActivityForResult(panelIntent, 1)
}
}
/* /*
* Helpful: * Helpful:
* http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically * http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically
*/ */
fun connectToHMGGuestNetwork(completion: (status: Boolean, message: String) -> Unit) { fun connectToHMGGuestNetwork(completion: (status: Boolean, message: String) -> Unit) {
completionListener = completion
wifiManager?.let { wm -> wifiManager?.let { wm ->
completionListener = completion
if (!wm.isWifiEnabled){ if (!wm.isWifiEnabled){
wm.isWifiEnabled = true enableWifi()
HMGUtils.popFlutterText(context,"enablingWifi"); }else{
HMGUtils.timer(2000,false){
connectWifi()
}
connectWifi() connectWifi()
} }
} }
} }
@ -56,7 +65,7 @@ class HMG_Guest(private var context: MainActivity) {
fun connectWifi(){ fun connectWifi(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
wifiManager?.let { connectApiGreaterThen28(it) } connectApiGreaterThen28()
}else { }else {
connectApiLessThen29() connectApiLessThen29()
} }
@ -64,40 +73,48 @@ class HMG_Guest(private var context: MainActivity) {
// I }else{f CompileSDK is greater and equals to APILevel 29 // I }else{f CompileSDK is greater and equals to APILevel 29
@RequiresApi(Build.VERSION_CODES.Q) @RequiresApi(Build.VERSION_CODES.Q)
private fun connectApiGreaterThen28(wm:WifiManager){ private fun connectApiGreaterThen28(){
Log.e(TAG, "connection wifi with Android Q+") Log.e(TAG, "connection wifi with Android Q+")
val wifiNetworkSpecifier: WifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
// .setWpa2Passphrase(password)
.build()
val networkRequest: NetworkRequest = NetworkRequest.Builder() val networkRequest: NetworkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(wifiNetworkSpecifier) .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) //removeCapability added for hotspots without internet .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) //removeCapability added for hotspots without internet
.build() .setNetworkSpecifier(
WifiNetworkSpecifier.Builder()
.setSsid(SSID)
.build()
).build()
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkCallback = object : ConnectivityManager.NetworkCallback() { val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) { override fun onAvailable(network: Network) {
super.onAvailable(network) super.onAvailable(network)
connectivityManager.bindProcessToNetwork(network) connectivityManager.bindProcessToNetwork(network)
HMGUtils.timer(2000,false){
completionListener(true, "Success")
}
Log.e(TAG, "onAvailable") Log.e(TAG, "onAvailable")
} }
override fun onLosing(network: Network, maxMsToLive: Int) { override fun onLosing(network: Network, maxMsToLive: Int) {
super.onLosing(network, maxMsToLive) super.onLosing(network, maxMsToLive)
Log.e(TAG, "onLosing") Log.e(TAG, "onLosing")
completionListener(false, "fail")
} }
override fun onLost(network: Network) { override fun onLost(network: Network) {
super.onLost(network) super.onLost(network)
Log.e(TAG, "onLosing") Log.e(TAG, "onLosing")
Log.e(TAG, "losing active connection") Log.e(TAG, "losing active connection")
completionListener(false, "fail")
} }
override fun onUnavailable() { override fun onUnavailable() {
super.onUnavailable() super.onUnavailable()
Log.e(TAG, "onUnavailable") Log.e(TAG, "onUnavailable")
completionListener(false, "fail")
} }
} }
@ -107,132 +124,117 @@ class HMG_Guest(private var context: MainActivity) {
} }
/**
* This method takes a given String, searches the current list of configured WiFi
* networks, and returns the networkId for the network if the SSID matches. If not,
* it returns -1.
*/
@SuppressLint("MissingPermission")
private fun ssidToNetworkId(ssid: String): Int {
val currentNetworks = wifiManager!!.configuredNetworks
var networkId = -1
// For each network in the list, compare the SSID with the given one
for (test in currentNetworks) {
if (test.SSID == ssid) {
networkId = test.networkId
break
}
}
return networkId
}
fun connectApiLessThen29(){ fun connectApiLessThen29(){
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.Q){ val wifi = WifiConfiguration()
wifi.SSID = """"$SSID""""
// Initialize the WifiConfiguration object wifi.status = WifiConfiguration.Status.ENABLED
val security = "OPEN" wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
val networkPass = ""
Log.d(TAG, "Connecting to SSID \"$SSID\" with password \"$networkPass\" and with security \"$security\" ...") wifi.networkId = ssidToNetworkId(wifi.SSID)
if (wifi.networkId == -1) {
wifiManager?.addNetwork(wifi)
} else {
Log.v(TAG, "WiFi found - updating it.\n")
wifiManager?.updateNetwork(wifi)
}
// You need to create WifiConfiguration instance like this: Log.v(TAG, "saving config.\n")
val conf = WifiConfiguration() wifiManager?.saveConfiguration()
conf.SSID = SSID
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
conf.networkId = ssidToNetworkId(SSID)
val wm = wifiManager!! wifi.networkId = ssidToNetworkId(wifi.SSID)
if (conf.networkId == -1) { Log.v(TAG, "wifi ID in device = " + wifi.networkId)
wm.addNetwork(conf)
} else {
Log.v(TAG, "WiFi found - updating it.\n")
wm.updateNetwork(conf)
}
conf.networkId = ssidToNetworkId(SSID) var supState: SupplicantState
Log.d(TAG, "Network ID: ${conf.networkId}") val networkIdToConnect = wifi.networkId
if (networkIdToConnect >= 0) {
val networkIdToConnect = conf.networkId Log.v(TAG, "Start connecting...\n")
if (networkIdToConnect >= 0) {
Log.v(TAG, "Start connecting to $SSID Wifi...")
// We disable the network before connecting, because if this was the last connection before
// a disconnect(), this will not reconnect.
wm.disableNetwork(networkIdToConnect)
val result = wm.enableNetwork(networkIdToConnect, true)
if(result){
HMGUtils.timer(8000,false){
if(wm.getConnectionInfo().getSSID() == SSID){
completionOnUiThread(true, "successConnectingHmgNetwork")
}else{
errorConnecting()
}
}
}else{
errorConnecting()
}
// We disable the network before connecting, because if this was the last connection before
// a disconnect(), this will not reconnect.
wifiManager?.disableNetwork(networkIdToConnect)
wifiManager?.enableNetwork(networkIdToConnect, true)
val wifiInfo: WifiInfo = wifiManager!!.connectionInfo
}else{ HMGUtils.timer(5000,false){
Log.v(TAG, "Cannot connect to $SSID network") supState = wifiInfo.supplicantState
errorConnecting() Log.i(TAG, "Done connect to network : status = $supState")
val successStates = listOf(SupplicantState.COMPLETED, SupplicantState.ASSOCIATED)
if (successStates.contains(supState))
completionListener(true,"Connected to internet Wifi")
else
completionListener(false,"errorConnectingHmgNetwork")
} }
}
/*val wifi = WifiConfiguration(); } else {
wifi.hiddenSSID = this.hiddenSSID; Log.v(TAG, "WifiWizard: cannot connect to network")
wifi.SSID = newSSID; completionListener(false,"errorConnectingHmgNetwork")
wifi.preSharedKey = newPass;
wifi.status = WifiConfiguration.Status.ENABLED;
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifi.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifi.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifi.networkId = ssidToNetworkId(newSSID);
// Set network to highest priority (deprecated in API >= 26)
if(Build.VERSION.SDK_INT < 26) {
wifi.priority = getMaxWifiPriority(wifiManager) + 1;
} }
// After processing authentication types, add or update network // val wifi = WifiConfiguration()
if(wifi.networkId == -1) { // -1 means SSID configuration does not exist yet // wifi.SSID = SSID
// wifi.status = WifiConfiguration.Status.ENABLED
int newNetId = wifiManager.addNetwork(wifi); // wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
if( newNetId > -1 ){ //
callbackContext.success( newNetId ); // wifi.networkId = ssidToNetworkId(SSID)
} else { //
callbackContext.error( "ERROR_ADDING_NETWORK" ); // // Set network to highest priority (deprecated in API >= 26)
} // if(Build.VERSION.SDK_INT < 26) {
// wifi.priority = getMaxWifiPriority(wifiManager!!) + 1;
} else { // }
//
// // After processing authentication types, add or update network
// if(wifi.networkId == -1) { // -1 means SSID configuration does not exist yet
//
// val newNetId = wifiManager?.addNetwork(wifi)!!
// if( newNetId > -1 ){
// completionListener(true,"Success")
// } else {
// completionListener(false, "ERROR_ADDING_NETWORK" )
// }
//
// } else {
//
// var updatedNetID = wifiManager?.updateNetwork(wifi)
//
// if(updatedNetID == -1)
// updatedNetID = wifiManager?.addNetwork(wifi)
//
// if(updatedNetID > -1) {
// callbackContext.success( updatedNetID )
// } else {
// callbackContext.error("ERROR_UPDATING_NETWORK")
// }
//
// }
//
// // WifiManager configurations are presistent for API 26+
// if(Build.VERSION.SDK_INT < 26) {
// wifiManager?.saveConfiguration(); // Call saveConfiguration for older < 26 API
// }
}
int updatedNetID = wifiManager.updateNetwork(wifi);
if(updatedNetID == -1) /**
updatedNetID = wifiManager.addNetwork(wifi); * This method takes a given String, searches the current list of configured WiFi
* networks, and returns the networkId for the network if the SSID matches. If not,
* it returns -1.
*/
@SuppressLint("MissingPermission")
private fun ssidToNetworkId(ssid: String): Int {
val currentNetworks = wifiManager!!.configuredNetworks
var networkId = -1
if(updatedNetID > -1) { // For each network in the list, compare the SSID with the given one
callbackContext.success( updatedNetID ); for (test in currentNetworks) {
} else { if (test.SSID == ssid) {
callbackContext.error("ERROR_UPDATING_NETWORK"); networkId = test.networkId
break
} }
} }
return networkId
// WifiManager configurations are presistent for API 26+
if(API_VERSION < 26) {
wifiManager.saveConfiguration(); // Call saveConfiguration for older < 26 API
}*/
} }
companion object{ companion object{

@ -20,14 +20,11 @@ class HMG_Internet(flutterMainActivity: MainActivity) {
private lateinit var completionListener: ((status: Boolean, message: String) -> Unit) private lateinit var completionListener: ((status: Boolean, message: String) -> Unit)
private var SSID = "GUEST-POC" private var SSID = "GUEST-POC"
private var USER_NAME = ""
private var PASSWORD = ""
fun completionOnUiThread(status: Boolean, message: String){ fun completionOnUiThread(status: Boolean, message: String){
completionListener(status, message) completionListener(status, message)
// context.runOnUiThread { // context.runOnUiThread {
// // .with(message){localized ->
// FlutterText.with(message){localized ->
// completionListener(status, localized) // completionListener(status, localized)
// } // }
// } // }
@ -37,12 +34,10 @@ class HMG_Internet(flutterMainActivity: MainActivity) {
* Helpful: * Helpful:
* http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically * http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically
*/ */
fun connectToHMGGuestNetwork(patientId: String, completion: (status: Boolean, message: String) -> Unit): HMG_Internet { fun connectToHMGGuestNetwork(username: String, password: String, completion: (status: Boolean, message: String) -> Unit): HMG_Internet {
completionListener = completion completionListener = completion
getWifiCredentials(patientId) { WpaEnterprise(context,SSID).connect(username,username) { status, message ->
WpaEnterprise(context,SSID).connect(USER_NAME,PASSWORD) { status, message -> completionOnUiThread(status,message)
completionOnUiThread(status,message)
}
} }
return this return this
} }
@ -65,16 +60,28 @@ class HMG_Internet(flutterMainActivity: MainActivity) {
} }
} }
private fun getWifiCredentials(patientId:String, success: (() -> Unit)){ private fun getWifiCredentials(patientId:String, success: ((String?,String?) -> Unit)){
if (TEST){ if (TEST){
SSID = "GUEST-POC" SSID = "GUEST-POC"
USER_NAME = "0696" success("2300", "0000")
PASSWORD = "0000"
success()
return return
} }
val jsonBody = """{"PatientID":$patientId}""" val jsonBody = """{
"PatientID":$patientId
"VersionID": 8.8,
"Channel": 3,
"LanguageID": 2,
"IPAdress": "10.20.10.20",
"generalid": "Cs2020@2016$2958",
"PatientOutSA": 0,
"SessionID": "@admin",
"isDentalAllowedBackend": false,
"DeviceTypeID": 2,
"TokenID": "@admin",
"PatientTypeID": 1,
"PatientType": 1
}""".trimMargin()
API.WIFI_CREDENTIALS. API.WIFI_CREDENTIALS.
httpPost() httpPost()
.jsonBody(jsonBody, Charsets.UTF_8) .jsonBody(jsonBody, Charsets.UTF_8)
@ -91,9 +98,13 @@ class HMG_Internet(flutterMainActivity: MainActivity) {
jsonObject.getJSONArray("Hmg_SMS_Get_By_ProjectID_And_PatientIDList").let { array -> jsonObject.getJSONArray("Hmg_SMS_Get_By_ProjectID_And_PatientIDList").let { array ->
array.getJSONObject(0).let { object_ -> array.getJSONObject(0).let { object_ ->
if (object_.has("UserName") && object_.has("UserName")){ if (object_.has("UserName") && object_.has("UserName")){
USER_NAME = object_.getString("UserName") try {
PASSWORD = object_.getString("Password") val userName = object_.getString("UserName")
success() val password = object_.getString("Password")
success(userName, password)
}catch (e:Exception){
success(null, null)
}
}else{ }else{
completionOnUiThread(false, "somethingWentWrong") completionOnUiThread(false, "somethingWentWrong")
} }

@ -14,6 +14,7 @@ import android.util.Log
import androidx.annotation.RequiresApi import androidx.annotation.RequiresApi
import com.ejada.hmg.MainActivity import com.ejada.hmg.MainActivity
import com.ejada.hmg.utils.HMGUtils import com.ejada.hmg.utils.HMGUtils
import java.security.cert.X509Certificate
class WpaEnterprise(private val mainActivity: MainActivity, private var SSID: String) { class WpaEnterprise(private val mainActivity: MainActivity, private var SSID: String) {
private var TAG = "WpaEnterprise" private var TAG = "WpaEnterprise"
@ -110,8 +111,9 @@ class WpaEnterprise(private val mainActivity: MainActivity, private var SSID: St
Log.e(TAG, "connection wifi with Android Q+") Log.e(TAG, "connection wifi with Android Q+")
val wifiNetworkSpecifier: WifiNetworkSpecifier = WifiNetworkSpecifier.Builder() val wifiNetworkSpecifier: WifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
.setWpa2EnterpriseConfig(enterpriseConfig()) .setSsid(SSID)
.build() .setWpa2EnterpriseConfig(enterpriseConfig())
.build()
val networkRequest: NetworkRequest = NetworkRequest.Builder() val networkRequest: NetworkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
@ -123,6 +125,7 @@ class WpaEnterprise(private val mainActivity: MainActivity, private var SSID: St
override fun onAvailable(network: Network) { override fun onAvailable(network: Network) {
super.onAvailable(network) super.onAvailable(network)
connectivityManager.bindProcessToNetwork(network) connectivityManager.bindProcessToNetwork(network)
completion(true, "200")
Log.e(TAG, "onAvailable") Log.e(TAG, "onAvailable")
} }
@ -139,6 +142,7 @@ class WpaEnterprise(private val mainActivity: MainActivity, private var SSID: St
override fun onUnavailable() { override fun onUnavailable() {
super.onUnavailable() super.onUnavailable()
completion(false, "401")
Log.e(TAG, "onUnavailable") Log.e(TAG, "onUnavailable")
} }
@ -154,6 +158,8 @@ class WpaEnterprise(private val mainActivity: MainActivity, private var SSID: St
enterpriseConfig.eapMethod = WifiEnterpriseConfig.Eap.PEAP enterpriseConfig.eapMethod = WifiEnterpriseConfig.Eap.PEAP
enterpriseConfig.identity = identity enterpriseConfig.identity = identity
enterpriseConfig.password = password enterpriseConfig.password = password
enterpriseConfig.phase2Method = WifiEnterpriseConfig.Phase2.NONE
// enterpriseConfig.caCertificates = WifiEnterpriseConfig.Phase2.
return enterpriseConfig; return enterpriseConfig;
} }

@ -13,11 +13,10 @@ import android.net.wifi.WifiManager
import android.util.Log import android.util.Log
import com.ejada.hmg.MainActivity import com.ejada.hmg.MainActivity
import com.ejada.hmg.hmgwifi.HMG_Guest import com.ejada.hmg.hmgwifi.HMG_Guest
import com.ejada.hmg.hmgwifi.HMG_Internet
import com.ejada.hmg.geofence.GeoZoneModel import com.ejada.hmg.geofence.GeoZoneModel
import com.ejada.hmg.geofence.HMG_Geofence import com.ejada.hmg.geofence.HMG_Geofence
import com.ejada.hmg.hmgwifi.WpaEnterprise
import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel
@ -72,33 +71,53 @@ class PlatformBridge(private var flutterEngine: FlutterEngine, private var mainA
private fun connectHMGInternetWifi(methodCall: MethodCall, result: MethodChannel.Result) { private fun connectHMGInternetWifi(methodCall: MethodCall, result: MethodChannel.Result) {
(methodCall.arguments as ArrayList<*>).let { (methodCall.arguments as ArrayList<*>).let {
require(it.size > 0 && (it[0] is String), lazyMessage = { require(it.size == 3 && (it[0] is String) && (it[1] is String), lazyMessage = {
"Missing or invalid arguments (Must have one argument 'String at 0'" "Missing or invalid arguments (Must have three argument of 'String'"
}) })
val patientId = it[0].toString() val ssid = it[0].toString()
HMG_Internet(mainActivity) val username = it[1].toString()
.connectToHMGGuestNetwork(patientId) { status, message -> val password = it[2].toString()
mainActivity.runOnUiThread { WpaEnterprise(mainActivity,ssid).connect(username,password) { status, message ->
HMGUtils.timer(2000,false){
mainActivity.runOnUiThread {
if(status)
result.success(if (status) 1 else 0) result.success(if (status) 1 else 0)
else
HMGUtils.popFlutterText(mainActivity, message) result.error(message, null, null)
Log.v(this.javaClass.simpleName, "$status | $message")
}
} }
}
}
// HMG_Internet(mainActivity)
// .connectToHMGGuestNetwork(username, password) { status, message ->
// mainActivity.runOnUiThread {
// result.success(if (status) 1 else 0)
//
// HMGUtils.popFlutterText(mainActivity, message)
// Log.v(this.javaClass.simpleName, "$status | $message")
// }
//
// }
} }
} }
private fun connectHMGGuestWifi(methodCall: MethodCall, result: MethodChannel.Result) { private fun connectHMGGuestWifi(methodCall: MethodCall, result: MethodChannel.Result) {
HMG_Guest(mainActivity).connectToHMGGuestNetwork { status, message -> (methodCall.arguments as ArrayList<*>).let {
mainActivity.runOnUiThread { require(it.size == 1 && (it[0] is String), lazyMessage = {
result.success(if (status) 1 else 0) "Missing or invalid arguments (Must have one argument 'String at 0'"
})
HMGUtils.popFlutterText(mainActivity, message) val ssid = it[0].toString()
Log.v(this.javaClass.simpleName, "$status | $message") HMG_Guest(mainActivity, ssid).connectToHMGGuestNetwork { status, message ->
mainActivity.runOnUiThread {
result.success(if (status) 1 else 0)
HMGUtils.popFlutterText(mainActivity, message)
Log.v(this.javaClass.simpleName, "$status | $message")
}
} }
} }
} }

@ -515,6 +515,8 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 3A359E86ZF; DEVELOPMENT_TEAM = 3A359E86ZF;
ENABLE_BITCODE = NO; ENABLE_BITCODE = NO;
@ -535,6 +537,7 @@
MARKETING_VERSION = 4.5.17; MARKETING_VERSION = 4.5.17;
PRODUCT_BUNDLE_IDENTIFIER = "com.HMG.HMG-Smartphone"; PRODUCT_BUNDLE_IDENTIFIER = "com.HMG.HMG-Smartphone";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic"; VERSIONING_SYSTEM = "apple-generic";
@ -655,6 +658,8 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 3A359E86ZF; DEVELOPMENT_TEAM = 3A359E86ZF;
ENABLE_BITCODE = NO; ENABLE_BITCODE = NO;
@ -675,6 +680,7 @@
MARKETING_VERSION = 4.5.17; MARKETING_VERSION = 4.5.17;
PRODUCT_BUNDLE_IDENTIFIER = "com.HMG.HMG-Smartphone"; PRODUCT_BUNDLE_IDENTIFIER = "com.HMG.HMG-Smartphone";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
@ -689,6 +695,8 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
DEVELOPMENT_TEAM = 3A359E86ZF; DEVELOPMENT_TEAM = 3A359E86ZF;
ENABLE_BITCODE = NO; ENABLE_BITCODE = NO;
@ -709,6 +717,7 @@
MARKETING_VERSION = 4.5.17; MARKETING_VERSION = 4.5.17;
PRODUCT_BUNDLE_IDENTIFIER = "com.HMG.HMG-Smartphone"; PRODUCT_BUNDLE_IDENTIFIER = "com.HMG.HMG-Smartphone";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic"; VERSIONING_SYSTEM = "apple-generic";

@ -10,4 +10,21 @@ class AppNav{
'nav_name' : value 'nav_name' : value
}); });
} }
log({int tabIndex, bool isLoggedIn}){
var nav_name = "";
if(tabIndex == 1)
nav_name = "medical file";
if(tabIndex == 3)
nav_name = "my family";
if(tabIndex == 4)
nav_name = "todo list";
if(tabIndex == 5)
nav_name = "help";
if(nav_name.isNotEmpty)
logger(name, parameters: {
'nav_name' : nav_name
});
}
} }

@ -5,4 +5,8 @@ class ErrorTracking{
final GALogger logger; final GALogger logger;
ErrorTracking(this.logger); ErrorTracking(this.logger);
log({String error}){
logger(error);
}
} }

@ -10,4 +10,9 @@ class HMGServices{
'services_name' : value 'services_name' : value
}); });
} }
viewAll(){
logger('hmg_services', parameters: {
'services_name' : 'view all services'
});
}
} }

@ -65,22 +65,38 @@ class LoginRegistration{
}); });
} }
// R011.x
login_verify_otp({@required int method}){
var verification_method = '';
if(method == 1) verification_method = 'sms';
if(method == 2) verification_method = 'fingerprint';
if(method == 3) verification_method = 'face id';
if(method == 4) verification_method = 'whatsapp';
logger('login_verify_otp', parameters: {
'login_method' : verification_method
});
}
// R011.2 // R011.2
forget_file_number(){ forget_file_number(){
logger('forget_file_number'); logger('forget_file_number');
} }
// R011.3 // R011.3
register_now({@required String method}){ register_now(){
logger('register_now', parameters: { logger('register_now');
'login_method' : method
});
} }
// R012.1, R014.1 // R012.1, R014.1
login_successful({@required String method}){ login_successful({@required int method}){
var verification_method = '';
if(method == 1) verification_method = 'sms';
if(method == 2) verification_method = 'fingerprint';
if(method == 3) verification_method = 'face id';
if(method == 4) verification_method = 'whatsapp';
logger('login_successful', parameters: { logger('login_successful', parameters: {
'login_method' : method 'login_method' : verification_method
}); });
} }

@ -26,11 +26,21 @@ _logger(String name, {Map<String,dynamic> parameters}) async {
if (name != null && name.isNotEmpty) { if (name != null && name.isNotEmpty) {
if(name.contains(' ')) if(name.contains(' '))
name = name.replaceAll(' ','_'); name = name.replaceAll(' ','_');
// To LowerCase
if(parameters != null && parameters.isNotEmpty)
parameters = parameters.map((key, value) {
final key_ = key.toLowerCase();
var value_ = value;
if(value is String)
value_ = value.toLowerCase();
return MapEntry(key_, value_);
});
_analytics _analytics
.logEvent(name: name.trim(), parameters: parameters) .logEvent(name: name.trim().toLowerCase(), parameters: parameters)
.then((value) { .then((value) {
debugPrint('SUCCESS: Google analytics event "$name" sent'); debugPrint('SUCCESS: Google analytics event "$name" sent with parameters $parameters');
}).catchError((error) { }).catchError((error) {
debugPrint('ERROR: Google analytics event "$name" sent failed'); debugPrint('ERROR: Google analytics event "$name" sent failed');
}); });

@ -54,7 +54,7 @@ const GET_PRIVILEGE = 'Services/Patients.svc/REST/Service_Privilege';
// Wifi Credentials // Wifi Credentials
const WIFI_CREDENTIALS = const WIFI_CREDENTIALS =
"Services/Patients.svc/Hmg_SMS_Get_By_ProjectID_And_PatientID"; "Services/Patients.svc/REST/Hmg_SMS_Get_By_ProjectID_And_PatientID";
///Doctor ///Doctor
const GET_MY_DOCTOR = const GET_MY_DOCTOR =
@ -378,7 +378,7 @@ const UPDATE_COVID_QUESTIONNAIRE = 'Services/Doctors.svc/REST/COVID19_Questionna
const CHANNEL = 3; const CHANNEL = 3;
const GENERAL_ID = 'Cs2020@2016\$2958'; const GENERAL_ID = 'Cs2020@2016\$2958';
const IP_ADDRESS = '10.20.10.20'; const IP_ADDRESS = '10.20.10.20';
const VERSION_ID = 7.3; const VERSION_ID = 8.8;
const SETUP_ID = '91877'; const SETUP_ID = '91877';
const LANGUAGE = 2; const LANGUAGE = 2;
const PATIENT_OUT_SA = 0; const PATIENT_OUT_SA = 0;

@ -40,7 +40,7 @@ class BaseAppClient {
Function(String error, int statusCode) onFailure, Function(String error, int statusCode) onFailure,
bool isAllowAny = false, bool isAllowAny = false,
bool isExternal = false, bool isExternal = false,
bool isRCService = false}) async { bool isRCService = false, bool bypassConnectionCheck = false}) async {
String url; String url;
if (isExternal) { if (isExternal) {
url = endPoint; url = endPoint;
@ -137,7 +137,7 @@ class BaseAppClient {
final jsonBody = json.encode(body); final jsonBody = json.encode(body);
print(jsonBody); print(jsonBody);
if (await Utils.checkConnection()) { if (await Utils.checkConnection(bypassConnectionCheck: bypassConnectionCheck)) {
final response = await http.post(Uri.parse(url.trim()), body: json.encode(body), headers: headers); final response = await http.post(Uri.parse(url.trim()), body: json.encode(body), headers: headers);
final int statusCode = response.statusCode; final int statusCode = response.statusCode;
print("statusCode :$statusCode"); print("statusCode :$statusCode");

@ -1,5 +1,6 @@
import 'package:diplomaticquarterapp/core/service/AlHabibMedicalService/H2O_service.dart'; import 'package:diplomaticquarterapp/core/service/AlHabibMedicalService/H2O_service.dart';
import 'package:diplomaticquarterapp/core/service/ancillary_orders_service.dart'; import 'package:diplomaticquarterapp/core/service/ancillary_orders_service.dart';
import 'package:diplomaticquarterapp/core/service/client/base_app_client.dart';
import 'package:diplomaticquarterapp/core/service/parmacyModule/prescription_service.dart'; import 'package:diplomaticquarterapp/core/service/parmacyModule/prescription_service.dart';
import 'package:diplomaticquarterapp/core/service/qr_service.dart'; import 'package:diplomaticquarterapp/core/service/qr_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/AlHabibMedicalService/H2O_view_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/AlHabibMedicalService/H2O_view_model.dart';
@ -332,4 +333,5 @@ void setupLocator() {
// --------------------------- // ---------------------------
locator.registerFactory(() => GAnalytics()); locator.registerFactory(() => GAnalytics());
locator.registerLazySingleton(() => BaseAppClient());
} }

@ -4,6 +4,7 @@ import 'package:diplomaticquarterapp/pages/BookAppointment/SearchResults.dart';
import 'package:diplomaticquarterapp/services/clinic_services/get_clinic_service.dart'; import 'package:diplomaticquarterapp/services/clinic_services/get_clinic_service.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/widgets/offers_packages/PackagesCartItemCard.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart'; import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -93,6 +94,7 @@ class _DentalComplaintCardState extends State<DentalComplaintCard> {
} }
Future navigateToSearchResults(context, List<DoctorList> docList, List<PatientDoctorAppointmentList> patientDoctorAppointmentListHospital) async { Future navigateToSearchResults(context, List<DoctorList> docList, List<PatientDoctorAppointmentList> patientDoctorAppointmentListHospital) async {
// widget.listDentalChiefComplain
Navigator.push(context, FadePage(page: SearchResults(doctorsList: docList, patientDoctorAppointmentListHospital: patientDoctorAppointmentListHospital))); Navigator.push(context, FadePage(page: SearchResults(doctorsList: docList, patientDoctorAppointmentListHospital: patientDoctorAppointmentListHospital)));
} }
} }

@ -241,6 +241,7 @@ class _HomePageFragment2State extends State<HomePageFragment2> {
), ),
FlatButton( FlatButton(
onPressed: () { onPressed: () {
projectViewModel.analytics.hmgServices.viewAll();
Navigator.push(context, FadePage(page: AllHabibMedicalSevicePage2())); Navigator.push(context, FadePage(page: AllHabibMedicalSevicePage2()));
}, },
child: Text( child: Text(

@ -121,6 +121,7 @@ class _LandingPageState extends State<LandingPage> with WidgetsBindingObserver {
} }
changeCurrentTab(int tab) { changeCurrentTab(int tab) {
projectViewModel.analytics.bottomTabNavigation.log(tabIndex: tab, isLoggedIn: projectViewModel.isLogin);
if (!projectViewModel.isLogin) { if (!projectViewModel.isLogin) {
if (tab == 3) { if (tab == 3) {
List<ImagesInfo> imagesInfo = []; List<ImagesInfo> imagesInfo = [];
@ -136,7 +137,6 @@ class _LandingPageState extends State<LandingPage> with WidgetsBindingObserver {
imageAr: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/family-file/ar/1.png'), imageAr: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/family-file/ar/1.png'),
); );
projectViewModel.analytics.bottomTabNavigation.logNavName('my family');
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
@ -156,7 +156,6 @@ class _LandingPageState extends State<LandingPage> with WidgetsBindingObserver {
imagesInfo.add( imagesInfo.add(
ImagesInfo(imageEn: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/todo/en/0.png', imageAr: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/todo/ar/0.png')); ImagesInfo(imageEn: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/todo/en/0.png', imageAr: 'https://hmgwebservices.com/Images/MobileApp/images-info-home/todo/ar/0.png'));
projectViewModel.analytics.bottomTabNavigation.logNavName('todo list');
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
@ -177,7 +176,6 @@ class _LandingPageState extends State<LandingPage> with WidgetsBindingObserver {
if (tab == 5) { if (tab == 5) {
IS_VOICE_COMMAND_CLOSED = false; IS_VOICE_COMMAND_CLOSED = false;
triggerRobot(); triggerRobot();
projectViewModel.analytics.bottomTabNavigation.logNavName('help robot');
// pageController.jumpToPage(tab); // pageController.jumpToPage(tab);
} else { } else {
@ -236,12 +234,10 @@ class _LandingPageState extends State<LandingPage> with WidgetsBindingObserver {
familyFileProvider.getSharedRecordByStatus(); familyFileProvider.getSharedRecordByStatus();
} }
}); });
// HMG (Guest/Internet) Wifi Access [Zohaib Kambrani] // HMG (Guest/Internet) Wifi Access [Zohaib Kambrani]
//for now commented to reduce this call will enable it when needed // for now commented to reduce this call will enable it when needed
// HMGNetworkConnectivity(context, () { HMGNetworkConnectivity(context).start();
// GifLoaderDialogUtils.showMyDialog(context);
// PlatformBridge.shared().connectHMGGuestWifi().then((value) => {GifLoaderDialogUtils.hideDialog(context)});
// }).checkAndConnectIfNoInternet();
requestPermissions().then((results) { requestPermissions().then((results) {
locationUtils.getCurrentLocation(); locationUtils.getCurrentLocation();
@ -468,7 +464,6 @@ class _LandingPageState extends State<LandingPage> with WidgetsBindingObserver {
physics: NeverScrollableScrollPhysics(), physics: NeverScrollableScrollPhysics(),
controller: pageController, controller: pageController,
onPageChanged: (idx){ onPageChanged: (idx){
projectViewModel.analytics.bottomTabNavigation.logNavName('');
}, },
children: [ children: [
HomePage2( HomePage2(
@ -479,7 +474,6 @@ class _LandingPageState extends State<LandingPage> with WidgetsBindingObserver {
login(); login();
}, },
onMedicalFileClick: () { onMedicalFileClick: () {
projectViewModel.analytics.bottomTabNavigation.logNavName('medical file');
changeCurrentTab(1); changeCurrentTab(1);
}, },
), ),

@ -273,7 +273,10 @@ class _ConfirmLogin extends State<ConfirmLogin> {
), ),
DefaultButton( DefaultButton(
TranslationBase.of(context).useAnotherAccount, TranslationBase.of(context).useAnotherAccount,
() => {Navigator.of(context).pushNamed(LOGIN_TYPE)}, () {
projectViewModel.analytics.loginRegistration.login_with_other_account();
Navigator.of(context).pushNamed(LOGIN_TYPE);
},
), ),
], ],
), ),
@ -296,6 +299,7 @@ class _ConfirmLogin extends State<ConfirmLogin> {
}); });
} }
int login_method = 0;
authenticateUser(int type, {int isActive}) { authenticateUser(int type, {int isActive}) {
GifLoaderDialogUtils.showMyDialog(context); GifLoaderDialogUtils.showMyDialog(context);
if (type == 2 || type == 3) { if (type == 2 || type == 3) {
@ -303,6 +307,7 @@ class _ConfirmLogin extends State<ConfirmLogin> {
} }
this.selectedOption = fingrePrintBefore != null ? fingrePrintBefore : type; this.selectedOption = fingrePrintBefore != null ? fingrePrintBefore : type;
login_method = type;
switch (type) { switch (type) {
case 1: case 1:
this.loginWithSMS(type); this.loginWithSMS(type);
@ -603,6 +608,7 @@ class _ConfirmLogin extends State<ConfirmLogin> {
} }
else else
{ {
projectViewModel.analytics.loginRegistration.login_successful(method: login_method),
sharedPref.remove(FAMILY_FILE), sharedPref.remove(FAMILY_FILE),
result.list.isFamily = false, result.list.isFamily = false,
userData = result.list, userData = result.list,
@ -622,6 +628,7 @@ class _ConfirmLogin extends State<ConfirmLogin> {
// Navigator.of(context).pop(), // Navigator.of(context).pop(),
GifLoaderDialogUtils.hideDialog(context), GifLoaderDialogUtils.hideDialog(context),
Future.delayed(Duration(seconds: 1), () { Future.delayed(Duration(seconds: 1), () {
projectViewModel.analytics.errorTracking.log(error: "login_failed: $result");
AppToast.showErrorToast(message: result); AppToast.showErrorToast(message: result);
startSMSService(tempType); startSMSService(tempType);
}), }),
@ -711,7 +718,6 @@ class _ConfirmLogin extends State<ConfirmLogin> {
Widget _loginOptionButton(String _title, String _icon, int _flag, int _loginIndex) { Widget _loginOptionButton(String _title, String _icon, int _flag, int _loginIndex) {
bool isDisable = (_flag == 3 && !checkIfBiometricAvailable(BiometricType.face) || _flag == 2 && !checkIfBiometricAvailable(BiometricType.fingerprint)); bool isDisable = (_flag == 3 && !checkIfBiometricAvailable(BiometricType.face) || _flag == 2 && !checkIfBiometricAvailable(BiometricType.fingerprint));
return InkWell( return InkWell(
onTap: isDisable onTap: isDisable
? null ? null
@ -721,6 +727,7 @@ class _ConfirmLogin extends State<ConfirmLogin> {
isMoreOption = true; isMoreOption = true;
}); });
} else { } else {
projectViewModel.analytics.loginRegistration.login_verify_otp(method: _flag);
authenticateUser(_flag, isActive: _loginIndex); authenticateUser(_flag, isActive: _loginIndex);
} }
}, },

@ -1,4 +1,6 @@
import 'package:diplomaticquarterapp/analytics/google-analytics.dart';
import 'package:diplomaticquarterapp/config/size_config.dart'; import 'package:diplomaticquarterapp/config/size_config.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/pages/login/forgot-password.dart'; import 'package:diplomaticquarterapp/pages/login/forgot-password.dart';
import 'package:diplomaticquarterapp/pages/login/login.dart'; import 'package:diplomaticquarterapp/pages/login/login.dart';
import 'package:diplomaticquarterapp/pages/login/register_new.dart'; import 'package:diplomaticquarterapp/pages/login/register_new.dart';
@ -60,7 +62,10 @@ class LoginType extends StatelessWidget {
text: TextSpan( text: TextSpan(
text: TranslationBase.of(context).forgotPassword, text: TranslationBase.of(context).forgotPassword,
style: TextStyle(decoration: TextDecoration.underline, fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xffC9272B), letterSpacing: -0.48, height: 18 / 12), style: TextStyle(decoration: TextDecoration.underline, fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xffC9272B), letterSpacing: -0.48, height: 18 / 12),
recognizer: TapGestureRecognizer()..onTap = () => Navigator.of(context).push(FadePage(page: ForgotPassword())), recognizer: TapGestureRecognizer()..onTap = () {
locator<GAnalytics>().loginRegistration.forget_file_number();
Navigator.of(context).push(FadePage(page: ForgotPassword()));
},
), ),
), ),
], ],
@ -71,6 +76,7 @@ class LoginType extends StatelessWidget {
width: double.infinity, width: double.infinity,
child: FlatButton( child: FlatButton(
onPressed: () { onPressed: () {
locator<GAnalytics>().loginRegistration.register_now();
Navigator.of(context).push(FadePage(page: RegisterNew())); Navigator.of(context).push(FadePage(page: RegisterNew()));
}, },
child: Text( child: Text(
@ -225,9 +231,16 @@ class LoginType extends StatelessWidget {
} }
Widget getButton(BuildContext _context, String _title, String _icon, int _flag) { Widget getButton(BuildContext _context, String _title, String _icon, int _flag) {
var type = '';
if(_flag == 1)
type = 'national id';
if(_flag == 2)
type = 'file number';
return InkWell( return InkWell(
onTap: () { onTap: () {
LoginType.loginType = _flag; LoginType.loginType = _flag;
locator<GAnalytics>().loginRegistration.login_start(method: type);
Navigator.of(_context).push(FadePage(page: Login())); Navigator.of(_context).push(FadePage(page: Login()));
}, },
child: Container( child: Container(

@ -4,6 +4,7 @@ import 'dart:io';
import 'package:diplomaticquarterapp/config/config.dart'; import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/core/service/client/base_app_client.dart'; import 'package:diplomaticquarterapp/core/service/client/base_app_client.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart'; import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/uitl/PlatformBridge.dart'; import 'package:diplomaticquarterapp/uitl/PlatformBridge.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart'; import 'package:diplomaticquarterapp/uitl/utils.dart';
@ -17,14 +18,26 @@ import 'package:wifi/wifi.dart';
import 'gif_loader_dialog_utils.dart'; import 'gif_loader_dialog_utils.dart';
class HMGNetworkConnectivity { class HMGNetworkConnectivity {
final _platformBridge = PlatformBridge.shared();
final BuildContext context; final BuildContext context;
final Function callBack; Function callBack;
final String SSID = "HMG-MobileApp"; final String GUEST_SSID = "HMG-MobileApp";
final String PATIENT_SSID = "GUEST-POC";
HMGNetworkConnectivity(this.context, this.callBack); HMGNetworkConnectivity(this.context);
start(){
checkAndConnectIfNoInternet();
}
void checkAndConnectIfNoInternet() async { void checkAndConnectIfNoInternet() async {
// getMyWifiCredentials((username, password){
// print("");
// });
//
// return;
String pingUrl = "$BASE_URL$PING_SERVICE"; String pingUrl = "$BASE_URL$PING_SERVICE";
// pingUrl = "https://captive.apple.com"; // pingUrl = "https://captive.apple.com";
@ -32,7 +45,7 @@ class HMGNetworkConnectivity {
log(error.toString()); log(error.toString());
}); });
bool alreadyConnected = ssid == SSID; bool alreadyConnected = ssid == GUEST_SSID;
BaseAppClient().simpleGet(pingUrl, onSuccess: (dynamic response, int statusCode) { BaseAppClient().simpleGet(pingUrl, onSuccess: (dynamic response, int statusCode) {
log("Having internet with status code: $statusCode"); log("Having internet with status code: $statusCode");
@ -40,12 +53,12 @@ class HMGNetworkConnectivity {
if (alreadyConnected) if (alreadyConnected)
showFailDailog(TranslationBase.of(context).failedToAccessHmgServices); showFailDailog(TranslationBase.of(context).failedToAccessHmgServices);
else { else {
confirmFromUser(); confirmFromUser(connectForLocalAccess);
} }
}); });
} }
void confirmFromUser() { void confirmFromUser(VoidCallback confirmCallback) {
TranslationBase translator = TranslationBase.of(context); TranslationBase translator = TranslationBase.of(context);
void doIt() { void doIt() {
@ -54,8 +67,8 @@ class HMGNetworkConnectivity {
confirmMessage: translator.wantToConnectWithHmgNetwork, confirmMessage: translator.wantToConnectWithHmgNetwork,
okText: translator.yes, okText: translator.yes,
okFunction: () { okFunction: () {
ConfirmDialog.closeAlertDialog(context); // ConfirmDialog.closeAlertDialog(context);
callBack(); confirmCallback();
}, },
cancelText: translator.no, cancelText: translator.no,
cancelFunction: () { cancelFunction: () {
@ -64,8 +77,8 @@ class HMGNetworkConnectivity {
} }
if (Platform.isAndroid) if (Platform.isAndroid)
Wifi.list(SSID).then((value) { Wifi.list(GUEST_SSID).then((value) {
if (!value.indexWhere((element) => element.ssid == SSID).isNegative) doIt(); if (!value.indexWhere((element) => element.ssid == GUEST_SSID).isNegative) doIt();
}); });
else else
doIt(); doIt();
@ -82,6 +95,40 @@ class HMGNetworkConnectivity {
}).showAlertDialog(context); }).showAlertDialog(context);
} }
connectForLocalAccess(){
GifLoaderDialogUtils.showMyDialog(context);
_platformBridge.connectHMGGuestWifi(GUEST_SSID).then((value) async{
if(value == 0){
GifLoaderDialogUtils.hideDialog(context);
}else{
getPatientWifiCredentials((username, password) async{
final result = await _platformBridge.connectHMGInternetWifi(PATIENT_SSID, username, password).catchError((err) => print(err.toString()));
GifLoaderDialogUtils.hideDialog(context);
if(result == 1){
// Success
}
});
}
});
}
getPatientWifiCredentials(Function(String username, String password) successCallback){
final body = <String, dynamic>{"PatientID" : "1231755"};
locator<BaseAppClient>().post(WIFI_CREDENTIALS, body:body, onSuccess: (dynamic response, int statusCode){
print(response);
var data = response["Hmg_SMS_Get_By_ProjectID_And_PatientIDList"];
if(data is List && data.first != null){
final username = data.first['UserName'];
final password = data.first['Password'];
if(username != null && password != null && username.isNotEmpty && password.isNotEmpty){
successCallback(username, password);
}
}
}, onFailure: (String error, int statusCode){
print(error);
}, bypassConnectionCheck: true);
}
// void next() { // void next() {
// if (Platform.isIOS) { // if (Platform.isIOS) {
// confirmFromUser_iOS(); // confirmFromUser_iOS();

@ -92,18 +92,18 @@ class PlatformBridge {
static const ASK_DRAW_OVER_APPS_PERMISSION = "askDrawOverAppsPermission"; static const ASK_DRAW_OVER_APPS_PERMISSION = "askDrawOverAppsPermission";
static const GET_INTENT = "getIntent"; static const GET_INTENT = "getIntent";
Future<Object> connectHMGInternetWifi(String patientId) { Future<Object> connectHMGInternetWifi(String ssid, username, password) {
try { try {
return platform.invokeMethod(hmg_internet_wifi_connect_method, [patientId]); return platform.invokeMethod(hmg_internet_wifi_connect_method, [ssid, username,password]);
} on PlatformException catch (e) { } on PlatformException catch (e) {
print(e); print(e);
return Future.error(e); return Future.error(e);
} }
} }
Future<Object> connectHMGGuestWifi() { Future<Object> connectHMGGuestWifi(String ssid) {
try { try {
return platform.invokeMethod(hmg_guest_wifi_connect_method); return platform.invokeMethod(hmg_guest_wifi_connect_method, ssid);
} on PlatformException catch (e) { } on PlatformException catch (e) {
print(e); print(e);
return Future.error(e); return Future.error(e);

@ -68,7 +68,10 @@ class Utils {
} }
/// Check The Internet Connection /// Check The Internet Connection
static Future<bool> checkConnection() async { static Future<bool> checkConnection({bool bypassConnectionCheck = false}) async {
if(bypassConnectionCheck)
return true;
ConnectivityResult connectivityResult = await (Connectivity().checkConnectivity()); ConnectivityResult connectivityResult = await (Connectivity().checkConnectivity());
if ((connectivityResult == ConnectivityResult.mobile) || (connectivityResult == ConnectivityResult.wifi)) { if ((connectivityResult == ConnectivityResult.mobile) || (connectivityResult == ConnectivityResult.wifi)) {
return true; return true;
@ -498,9 +501,9 @@ class Utils {
if (projectViewModel.isLogin && userData_ != null || true) { if (projectViewModel.isLogin && userData_ != null || true) {
String patientID = userData_.patientID.toString(); String patientID = userData_.patientID.toString();
GifLoaderDialogUtils.showMyDialog(context); GifLoaderDialogUtils.showMyDialog(context);
projectViewModel.platformBridge().connectHMGInternetWifi(patientID).then((value) => {GifLoaderDialogUtils.hideDialog(context)}).catchError((err) { // projectViewModel.platformBridge().connectHMGInternetWifi(patientID).then((value) => {GifLoaderDialogUtils.hideDialog(context)}).catchError((err) {
print(err.toString()); // print(err.toString());
}); // });
} else { } else {
AlertDialogBox( AlertDialogBox(
context: context, context: context,

@ -24,6 +24,7 @@ import 'package:diplomaticquarterapp/services/family_files/family_files_provider
import 'package:diplomaticquarterapp/theme/colors.dart'; import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/theme/theme_notifier.dart'; import 'package:diplomaticquarterapp/theme/theme_notifier.dart';
import 'package:diplomaticquarterapp/theme/theme_value.dart'; import 'package:diplomaticquarterapp/theme/theme_value.dart';
import 'package:diplomaticquarterapp/uitl/HMGNetworkConnectivity.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart'; import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
@ -400,7 +401,6 @@ class _AppDrawerState extends State<AppDrawer> {
child: DrawerItem(TranslationBase.of(context).logout, SvgPicture.asset("assets/images/new/logout.svg"), child: DrawerItem(TranslationBase.of(context).logout, SvgPicture.asset("assets/images/new/logout.svg"),
isImageIcon: true, bottomLine: false, letterSpacing: -0.84, fontSize: 14, projectProvider: projectProvider), isImageIcon: true, bottomLine: false, letterSpacing: -0.84, fontSize: 14, projectProvider: projectProvider),
onTap: () { onTap: () {
locator<GAnalytics>().hamburgerMenu.logMenuItemClick('logout');
logout(); logout();
}, },
) )
@ -433,15 +433,8 @@ class _AppDrawerState extends State<AppDrawer> {
onTap: () { onTap: () {
// Navigator.push(context, FadePage(page: CallPage())); // Navigator.push(context, FadePage(page: CallPage()));
locator<GAnalytics>().hamburgerMenu.logMenuItemClick('cloud solution logo tap'); locator<GAnalytics>().hamburgerMenu.logMenuItemClick('cloud solution logo tap');
String patientID = '2001273';
GifLoaderDialogUtils.showMyDialog(context); GifLoaderDialogUtils.showMyDialog(context);
projectProvider HMGNetworkConnectivity(context).start();
.platformBridge()
.connectHMGInternetWifi(patientID)
.then((value) => {GifLoaderDialogUtils.hideDialog(context)})
.catchError((err) {
print(err.toString());
});
}, },
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
@ -517,12 +510,14 @@ class _AppDrawerState extends State<AppDrawer> {
await sharedPref.remove(APPOINTMENT_HISTORY_MEDICAL); await sharedPref.remove(APPOINTMENT_HISTORY_MEDICAL);
this.user = null; this.user = null;
Navigator.of(context).pushNamed(HOME); Navigator.of(context).pushNamed(HOME);
locator<GAnalytics>().hamburgerMenu.logMenuItemClick('logout');
}, },
cancelFunction: () => {}); cancelFunction: () => {});
dialog.showAlertDialog(context); dialog.showAlertDialog(context);
} }
login() async { login() async {
locator<GAnalytics>().hamburgerMenu.logMenuItemClick('login');
var data = await sharedPref.getObject(IMEI_USER_DATA); var data = await sharedPref.getObject(IMEI_USER_DATA);
sharedPref.remove(REGISTER_DATA_FOR_LOGIIN); sharedPref.remove(REGISTER_DATA_FOR_LOGIIN);

Loading…
Cancel
Save