Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update ImageDownloaderPlugin.kt to handle all cases in when #143

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.ko2ic.imagedownloader

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DownloadManager
import android.content.ContentValues
Expand All @@ -20,30 +19,36 @@ import androidx.core.content.FileProvider
import com.ko2ic.imagedownloader.ImageDownloaderPlugin.TemporaryDatabase.Companion.COLUMNS
import com.ko2ic.imagedownloader.ImageDownloaderPlugin.TemporaryDatabase.Companion.TABLE_NAME
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.PluginRegistry.Registrar
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;

import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.net.URLConnection
import java.text.SimpleDateFormat
import java.util.*


class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
companion object {
@JvmStatic
fun registerWith(registrar: Registrar) {
val activity = registrar.activity() ?: return
val context = registrar.context()
val context = registrar.context() ?: return
val applicationContext = context.applicationContext
val pluginInstance = ImageDownloaderPlugin()
pluginInstance.setup(
registrar.messenger(), applicationContext, activity, registrar, null
registrar.messenger(),
applicationContext,
activity,
registrar,
null
)
}

Expand Down Expand Up @@ -174,8 +179,8 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {

private fun open(call: MethodCall, result: MethodChannel.Result) {

val path =
call.argument<String>("path") ?: throw IllegalArgumentException("path is required.")
val path = call.argument<String>("path")
?: throw IllegalArgumentException("path is required.")

val file = File(path)
val intent = Intent(Intent.ACTION_VIEW)
Expand All @@ -186,7 +191,9 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
if (Build.VERSION.SDK_INT >= 24) {
val uri = applicationContext?.let {
FileProvider.getUriForFile(
it, "${applicationContext?.packageName}.image_downloader.provider", file
it,
"${applicationContext?.packageName}.image_downloader.provider",
file
)
}
intent.setDataAndType(uri, mimeType)
Expand Down Expand Up @@ -228,7 +235,6 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
return data.mimeType
}

@SuppressLint("Range")
private fun findFileData(imageId: String, context: Context): FileData {

if (inPublicDir) {
Expand Down Expand Up @@ -259,14 +265,16 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
null,
null,
null
).use {
it.moveToFirst()
val path = it.getString(it.getColumnIndex(MediaStore.Images.Media.DATA))
val name = it.getString(it.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME))
val size = it.getInt(it.getColumnIndex(MediaStore.Images.Media.SIZE))
val mimeType = it.getString(it.getColumnIndex(MediaStore.Images.Media.MIME_TYPE))
FileData(path = path, name = name, byteSize = size, mimeType = mimeType)
}
)
.use {
it.moveToFirst()
val path = it.getString(it.getColumnIndex(MediaStore.Images.Media.DATA))
val name = it.getString(it.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME))
val size = it.getInt(it.getColumnIndex(MediaStore.Images.Media.SIZE))
val mimeType =
it.getString(it.getColumnIndex(MediaStore.Images.Media.MIME_TYPE))
FileData(path = path, name = name, byteSize = size, mimeType = mimeType)
}
}
}

Expand All @@ -275,13 +283,14 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
private val result: MethodChannel.Result,
private val channel: MethodChannel,
private val context: Context
) : ImageDownloaderPermissionListener.Callback {
) :
ImageDownloaderPermissionListener.Callback {

var downloader: Downloader? = null

override fun granted() {
val url =
call.argument<String>("url") ?: throw IllegalArgumentException("url is required.")
val url = call.argument<String>("url")
?: throw IllegalArgumentException("url is required.")

val headers: Map<String, String>? = call.argument<Map<String, String>>("headers")

Expand All @@ -290,7 +299,8 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
val directoryType = call.argument<String>("directory") ?: "DIRECTORY_DOWNLOADS"
val subDirectory = call.argument<String>("subDirectory")
val tempSubDirectory = subDirectory ?: SimpleDateFormat(
"yyyy-MM-dd.HH.mm.sss", Locale.getDefault()
"yyyy-MM-dd.HH.mm.sss",
Locale.getDefault()
).format(Date())

val directory = convertToDirectory(directoryType)
Expand Down Expand Up @@ -334,7 +344,7 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
channel.invokeMethod("onProgressUpdate", args)
}
}
else -> throw AssertionError()
else -> print("I don't know anything about it")
}

}, onError = {
Expand All @@ -355,8 +365,8 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
)
} else {
val stream = BufferedInputStream(FileInputStream(file))
val mimeType =
outputMimeType ?: URLConnection.guessContentTypeFromStream(stream)
val mimeType = outputMimeType
?: URLConnection.guessContentTypeFromStream(stream)

val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType)

Expand All @@ -373,8 +383,9 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
}

file.renameTo(newFile)
val newMimeType = mimeType ?: MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(newFile.extension) ?: ""
val newMimeType = mimeType
?: MimeTypeMap.getSingleton().getMimeTypeFromExtension(newFile.extension)
?: ""
val imageId = saveToDatabase(newFile, mimeType ?: newMimeType, inPublicDir)

result.success(imageId)
Expand All @@ -396,7 +407,6 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
}
}

@SuppressLint("Range")
private fun saveToDatabase(file: File, mimeType: String, inPublicDir: Boolean): String {
val path = file.absolutePath
val name = file.name
Expand All @@ -410,7 +420,8 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
if (inPublicDir) {

context.contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
contentValues
)
return context.contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
Expand All @@ -426,7 +437,9 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
} else {
val db = TemporaryDatabase(context)
val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz0123456789"
val id = (1..20).map { allowedChars.random() }.joinToString("")
val id = (1..20)
.map { allowedChars.random() }
.joinToString("")
contentValues.put(MediaStore.Images.Media._ID, id)
db.writableDatabase.insert(TABLE_NAME, null, contentValues)
return id
Expand All @@ -435,7 +448,10 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {
}

private data class FileData(
val path: String, val name: String, val byteSize: Int, val mimeType: String
val path: String,
val name: String,
val byteSize: Int,
val mimeType: String
)

class TemporaryDatabase(context: Context) :
Expand All @@ -444,18 +460,24 @@ class ImageDownloaderPlugin : FlutterPlugin, ActivityAware, MethodCallHandler {

companion object {

val COLUMNS = arrayOf(
MediaStore.Images.Media._ID,
MediaStore.Images.Media.MIME_TYPE,
MediaStore.Images.Media.DATA,
MediaStore.Images.ImageColumns.DISPLAY_NAME,
MediaStore.Images.ImageColumns.SIZE
)
val COLUMNS =
arrayOf(
MediaStore.Images.Media._ID,
MediaStore.Images.Media.MIME_TYPE,
MediaStore.Images.Media.DATA,
MediaStore.Images.ImageColumns.DISPLAY_NAME,
MediaStore.Images.ImageColumns.SIZE
)

private const val DATABASE_VERSION = 1
const val TABLE_NAME = "image_downloader_temporary"
private const val DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" + MediaStore.Images.Media._ID + " TEXT, " + MediaStore.Images.Media.MIME_TYPE + " TEXT, " + MediaStore.Images.Media.DATA + " TEXT, " + MediaStore.Images.ImageColumns.DISPLAY_NAME + " TEXT, " + MediaStore.Images.ImageColumns.SIZE + " INTEGER" + ");"
private const val DICTIONARY_TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " (" +
MediaStore.Images.Media._ID + " TEXT, " +
MediaStore.Images.Media.MIME_TYPE + " TEXT, " +
MediaStore.Images.Media.DATA + " TEXT, " +
MediaStore.Images.ImageColumns.DISPLAY_NAME + " TEXT, " +
MediaStore.Images.ImageColumns.SIZE + " INTEGER" +
");"
}

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
Expand Down