package com.example.medionndoctorapproval
import android.annotation.SuppressLint
import android.content.ContentValues.TAG
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.os.Parcelable
import android.os.StrictMode
import android.provider.MediaStore
import android.util.Base64
import android.util.Log
import android.view.View
import android.webkit.*
import android.widget.Toast
import androidx.core.app.ActivityCompat
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.lang.ref.WeakReference
import java.text.SimpleDateFormat
import java.util.Date
class MainActivity : AppCompatActivity() {
private val permissions =
arrayOf("android.permission.CAMERA", "android.permission.RECORD_AUDIO", "android.permission.MODIFY_AUDIO_SETTINGS")
private val permissionsAll = 1
private lateinit var webView: WebView // Declare webView as a global variable
private var mFilePathCallback: ValueCallback<Array<Uri>>? = null
private var mCameraPhotoPath: String? = null
private val INPUT_FILE_REQUEST_CODE = 1
private val FILECHOOSER_RESULTCODE = 1
private var mUploadMessage: ValueCallback<Uri?>? = null
private var mCapturedImageURI: Uri? = null
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data)
return
}
var results: Array<Uri>? = null
// Check that the response is a good one
if (resultCode == RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = arrayOf(Uri.parse(mCameraPhotoPath))
}
} else {
val dataString = data.dataString
if (dataString != null) {
results = arrayOf(Uri.parse(dataString))
}
}
}
mFilePathCallback!!.onReceiveValue(results)
mFilePathCallback = null
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data)
return
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage) {
return
}
var result: Uri? = null
try {
if (resultCode != RESULT_OK) {
result = null
} else {
// retrieve from the private variable if the intent is null
result = if (data == null) mCapturedImageURI else data.data
}
} catch (e: Exception) {
Toast.makeText(
applicationContext, "activity :$e",
Toast.LENGTH_LONG
).show()
}
mUploadMessage!!.onReceiveValue(result)
mUploadMessage = null
}
}
return
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webView = (findViewById(R.id.webView))
//if (Utils.hasPermissions(this, permissions)) {
joinVideo(findViewById(R.id.webView))
//}
// else {
// ActivityCompat.requestPermissions(this, permissions, permissionsAll)
// }
}
@SuppressLint("SetJavaScriptEnabled")
private fun joinVideo(webView: WebView) {
webView.run {
scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
setLayerType(WebView.LAYER_TYPE_HARDWARE, null)
val webSettings = webView.settings
webSettings.setDomStorageEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setSupportMultipleWindows(true);
webSettings.setMixedContentMode(0);
webSettings.javaScriptEnabled = true
webSettings.allowFileAccess = true
webSettings.loadWithOverviewMode = true
webSettings.javaScriptCanOpenWindowsAutomatically = true
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH)
webSettings.loadsImagesAutomatically = true
webSettings.mediaPlaybackRequiresUserGesture = false
webView.loadUrl("http://103.30.72.57/MedionnMobileApp/Pages/login.aspx")
webView.webViewClient = (WebClient(this@MainActivity))
webView.webChromeClient = MyChromeClient()
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
CookieManager.getInstance().setAcceptCookie(true);
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
webView.setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimeType, contentLength ->
if (url.startsWith("data:")) { //when url is base64 encoded data
val path = createAndSaveFileFromBase64Url(url)
val builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
return@DownloadListener
}
})
}
}
inner class MyChromeClient() : WebChromeClient() {
override fun onPermissionRequest(request: PermissionRequest?) {
request?.let { it.grant(it.resources) }
}
// For Android 5.0
override fun onShowFileChooser(
view: WebView,
filePath: ValueCallback<Array<Uri>>,
fileChooserParams: FileChooserParams
): Boolean {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback!!.onReceiveValue(null)
}
mFilePathCallback = filePath
var takePictureIntent: Intent? = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePictureIntent!!.resolveActivity(packageManager) != null) {
// Create the File where the photo should go
var photoFile: File? = null
try {
photoFile = createImageFile()
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath)
} catch (ex: IOException) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex)
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.absolutePath
takePictureIntent.putExtra(
MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile)
)
} else {
takePictureIntent = null
}
}
val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE)
contentSelectionIntent.type = "image/*"
val intentArray: Array<Intent?>
if (takePictureIntent != null) {
intentArray = arrayOf(takePictureIntent)
} else
{
intentArray = arrayOfNulls(0)
}
val chooserIntent = Intent(Intent.ACTION_CHOOSER)
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser")
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray)
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE)
return true
}
@JvmOverloads
fun openFileChooser(uploadMsg: ValueCallback<Uri?>?, acceptType: String? = "") {
mUploadMessage = uploadMsg
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
val imageStorageDir = File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
), "AndroidExampleFolder"
)
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs()
}
// Create camera captured image file path and name
val file = File(
imageStorageDir.toString() + File.separator + "IMG_"
+ System.currentTimeMillis().toString() + ".jpg"
)
mCapturedImageURI = Uri.fromFile(file)
// Camera capture image intent
val captureIntent = Intent(
MediaStore.ACTION_IMAGE_CAPTURE
)
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI)
val i = Intent(Intent.ACTION_GET_CONTENT)
i.addCategory(Intent.CATEGORY_OPENABLE)
i.type = "image/*"
// Create file chooser intent
val chooserIntent = Intent.createChooser(i, "Image Chooser")
// Set camera intent to file chooser
chooserIntent.putExtra(
Intent.EXTRA_INITIAL_INTENTS, arrayOf<Parcelable>(captureIntent)
)
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE)
}
//openFileChooser for other Android versions
fun openFileChooser(
uploadMsg: ValueCallback<Uri?>?,
acceptType: String?,
capture: String?
) {
openFileChooser(uploadMsg, acceptType)
}
}
@Throws(IOException::class)
private fun createImageFile(): File {
// Create an image file name
val timeStamp =
SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val imageFileName = "JPEG_" + timeStamp + "_"
val storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
)
return File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
)
}
fun createAndSaveFileFromBase64Url(url: String): String {
val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
val filetype = url.substring(url.indexOf("/") + 1, url.indexOf(";"))
val filename = System.currentTimeMillis().toString() + "." + filetype
val file = File(path, filename)
try {
if (!path.exists()) path.mkdirs()
if (!file.exists()) file.createNewFile()
val base64EncodedString = url.substring(url.indexOf(",") + 1)
val decodedBytes = Base64.decode(base64EncodedString, Base64.DEFAULT)
val os: OutputStream = FileOutputStream(file)
os.write(decodedBytes)
os.close()
} catch (e: IOException) {
Log.w("ExternalStorage", "Error writing $file", e)
Toast.makeText(applicationContext, "", Toast.LENGTH_LONG).show()
}
return file.toString()
}
fun showLog(message: String?) {
Log.i(KEY_TAG, "$message")
}
// class MyChromeClient : WebChromeClient() {
//
// override fun onPermissionRequest(request: PermissionRequest?) {
// request?.let { it.grant(it.resources) }
// }
//
////code for adding attachment
//
//
// }
class WebClient(activity: MainActivity) : WebViewClient() {
private val reference = WeakReference(activity)
override fun onLoadResource(view: WebView?, url: String?) {
super.onLoadResource(view, url)
reference.get()?.showLog("onLoadResource $url")
}
override fun onPageFinished(view: WebView?, url: String?) {
if(url.equals("https://his-mobile-vv.c-care.mu")) {
println("Exit")
// i want to jump on MyAppointmentFragment in this method
//with bundle.putString("type", "Teleconsultation")
}
super.onPageFinished(view, url)
reference.get()?.showLog("onPageFinished $url")
println(url)
}
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// Do nothing here to prevent reloading WebView on orientation change
}
override fun onBackPressed() {
// val builder = AlertDialog.Builder(this)
// builder.setTitle("Kindly Logout From The Video Conference !")
// builder.setMessage("")
// builder.show()
// builder.setCancelable(true)
// Toast.makeText(this, "Please Press Exit From Video ", Toast.LENGTH_LONG).show()
webView.destroy()
super.onBackPressed()
}
companion object {
const val KEY_TAG = "MainActivity"
}
}