aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/kotlin/com/pitchedapps/frost/contracts/FileChooser.kt
blob: 5b2cfa4946ff14524c9a78314644ac87852b3fe5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.pitchedapps.frost.contracts

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import ca.allanwang.kau.permissions.PERMISSION_READ_EXTERNAL_STORAGE
import ca.allanwang.kau.permissions.kauRequestPermissions
import com.pitchedapps.frost.utils.L

/**
 * Created by Allan Wang on 2017-07-04.
 */
const val FILE_CHOOSER_REQUEST = 67

interface FileChooserActivityContract {
    fun openFileChooser(filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: WebChromeClient.FileChooserParams)
}

interface FileChooserContract {
    var filePathCallback: ValueCallback<Array<Uri>>?
    fun openFileChooser(activity: Activity, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: WebChromeClient.FileChooserParams)
    fun onActivityResultWeb(requestCode: Int, resultCode: Int, intent: Intent?): Boolean
}

class FileChooserDelegate : FileChooserContract {

    override var filePathCallback: ValueCallback<Array<Uri>>? = null

    override fun openFileChooser(activity: Activity, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: WebChromeClient.FileChooserParams) {
        activity.kauRequestPermissions(PERMISSION_READ_EXTERNAL_STORAGE) {
            granted, _ ->
            if (!granted) return@kauRequestPermissions
            val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE)
            contentSelectionIntent.type = fileChooserParams.acceptTypes?.joinToString(separator = "|") ?: "*/*"
            activity.startActivityForResult(contentSelectionIntent, FILE_CHOOSER_REQUEST)
            this.filePathCallback?.onReceiveValue(null)
            this.filePathCallback = filePathCallback
        }
    }

    override fun onActivityResultWeb(requestCode: Int, resultCode: Int, intent: Intent?): Boolean {
        L.d("On activity results web $requestCode")
        if (requestCode != FILE_CHOOSER_REQUEST) return false
        var results: Uri? = null

        if (resultCode == Activity.RESULT_OK && intent != null) results = Uri.parse(intent.dataString)
        L.d("Callback received; ${filePathCallback != null}")
        filePathCallback?.onReceiveValue(if (results == null) null else arrayOf(results))
        filePathCallback = null
        return true
    }

}