|
| 1 | +package com.reactnativecompressor.Utils |
| 2 | + |
| 3 | +import android.content.Context |
| 4 | +import android.graphics.Bitmap |
| 5 | +import android.graphics.BitmapFactory |
| 6 | +import android.media.MediaMetadataRetriever |
| 7 | +import android.net.Uri |
| 8 | +import android.os.Build |
| 9 | +import android.text.TextUtils |
| 10 | +import android.webkit.URLUtil |
| 11 | +import androidx.annotation.RequiresApi |
| 12 | +import com.facebook.react.bridge.Arguments |
| 13 | +import com.facebook.react.bridge.GuardedResultAsyncTask |
| 14 | +import com.facebook.react.bridge.Promise |
| 15 | +import com.facebook.react.bridge.ReactApplicationContext |
| 16 | +import com.facebook.react.bridge.ReactContext |
| 17 | +import com.facebook.react.bridge.ReactMethod |
| 18 | +import com.facebook.react.bridge.ReadableMap |
| 19 | +import java.io.File |
| 20 | +import java.io.FileOutputStream |
| 21 | +import java.io.IOException |
| 22 | +import java.io.OutputStream |
| 23 | +import java.io.UnsupportedEncodingException |
| 24 | +import java.lang.ref.WeakReference |
| 25 | +import java.net.URLDecoder |
| 26 | +import java.util.UUID |
| 27 | + |
| 28 | + |
| 29 | +class CreateVideoThumbnail(private val reactContext: ReactApplicationContext) { |
| 30 | + @ReactMethod |
| 31 | + fun create(fileUrl:String,options: ReadableMap, promise: Promise) { |
| 32 | + ProcessDataTask(reactContext,fileUrl, promise, options).execute() |
| 33 | + } |
| 34 | + |
| 35 | + private class ProcessDataTask(reactContext: ReactContext,private val filePath:String, private val promise: Promise, private val options: ReadableMap) : GuardedResultAsyncTask<ReadableMap?>(reactContext.exceptionHandler) { |
| 36 | + private val weakContext: WeakReference<Context> |
| 37 | + |
| 38 | + init { |
| 39 | + weakContext = WeakReference(reactContext.applicationContext) |
| 40 | + } |
| 41 | + |
| 42 | + @RequiresApi(Build.VERSION_CODES.N) |
| 43 | + override fun doInBackgroundGuarded(): ReadableMap? { |
| 44 | + val format = "jpeg" |
| 45 | + val cacheName = if (options.hasKey("cacheName")) options.getString("cacheName") else "" |
| 46 | + val thumbnailDir = weakContext.get()!!.applicationContext.cacheDir.absolutePath + "/thumbnails" |
| 47 | + val cacheDir = createDirIfNotExists(thumbnailDir) |
| 48 | + if (!TextUtils.isEmpty(cacheName)) { |
| 49 | + val file = File(thumbnailDir, "$cacheName.$format") |
| 50 | + if (file.exists()) { |
| 51 | + val map = Arguments.createMap() |
| 52 | + map.putString("path", "file://" + file.absolutePath) |
| 53 | + val image = BitmapFactory.decodeFile(file.absolutePath) |
| 54 | + map.putDouble("size", image.byteCount.toDouble()) |
| 55 | + map.putString("mime", "image/$format") |
| 56 | + map.putDouble("width", image.width.toDouble()) |
| 57 | + map.putDouble("height", image.height.toDouble()) |
| 58 | + return map |
| 59 | + } |
| 60 | + } |
| 61 | + val headers: Map<String, String> = if (options.hasKey("headers")) options.getMap("headers")!!.toHashMap() as Map<String, String> else HashMap<String, String>() |
| 62 | + val fileName = if (TextUtils.isEmpty(cacheName)) "thumb-" + UUID.randomUUID().toString() else "$cacheName.$format" |
| 63 | + var fOut: OutputStream? = null |
| 64 | + try { |
| 65 | + val file = File(cacheDir, fileName) |
| 66 | + val context = weakContext.get() |
| 67 | + val image = getBitmapAtTime(context, filePath, 0, headers) |
| 68 | + file.createNewFile() |
| 69 | + fOut = FileOutputStream(file) |
| 70 | + |
| 71 | + // 100 means no compression, the lower you go, the stronger the compression |
| 72 | + image.compress(Bitmap.CompressFormat.JPEG, 90, fOut) |
| 73 | + fOut.flush() |
| 74 | + fOut.close() |
| 75 | + |
| 76 | + val map = Arguments.createMap() |
| 77 | + map.putString("path", "file://" + file.absolutePath) |
| 78 | + map.putDouble("size", image.byteCount.toDouble()) |
| 79 | + map.putString("mime", "image/$format") |
| 80 | + map.putDouble("width", image.width.toDouble()) |
| 81 | + map.putDouble("height", image.height.toDouble()) |
| 82 | + return map |
| 83 | + } catch (e: Exception) { |
| 84 | + promise.reject("CreateVideoThumbnail_ERROR", e) |
| 85 | + } |
| 86 | + return null |
| 87 | + } |
| 88 | + |
| 89 | + override fun onPostExecuteGuarded(readableArray: ReadableMap?) { |
| 90 | + promise.resolve(readableArray) |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + companion object { |
| 95 | + // delete previously added files one by one untill requred space is available |
| 96 | + fun clearCache(cacheDir: String?,promise:Promise, reactContext: ReactApplicationContext) { |
| 97 | + val cacheDirectory=cacheDir?.takeIf { it.isNotEmpty() } ?:"/thumbnails" |
| 98 | + val thumbnailDir: String = reactContext.getApplicationContext().getCacheDir().getAbsolutePath() + cacheDirectory |
| 99 | + val thumbnailDirFile = createDirIfNotExists(thumbnailDir) |
| 100 | + |
| 101 | + if (thumbnailDirFile != null) { |
| 102 | + val files = thumbnailDirFile.listFiles() |
| 103 | + |
| 104 | + // Loop through the files and delete them |
| 105 | + if (files != null) { |
| 106 | + for (file in files) { |
| 107 | + if (file.isFile) { |
| 108 | + file.delete() |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | + promise.resolve("done") |
| 114 | + } |
| 115 | + |
| 116 | + private fun createDirIfNotExists(path: String): File { |
| 117 | + val dir = File(path) |
| 118 | + if (dir.exists()) { |
| 119 | + return dir |
| 120 | + } |
| 121 | + try { |
| 122 | + dir.mkdirs() |
| 123 | + // Add .nomedia to hide the thumbnail directory from gallery |
| 124 | + val noMedia = File(path, ".nomedia") |
| 125 | + noMedia.createNewFile() |
| 126 | + } catch (e: IOException) { |
| 127 | + e.printStackTrace() |
| 128 | + } |
| 129 | + return dir |
| 130 | + } |
| 131 | + |
| 132 | + private fun getBitmapAtTime(context: Context?, filePath: String?, time: Int, headers: Map<String, String>): Bitmap { |
| 133 | + val retriever = MediaMetadataRetriever() |
| 134 | + if (URLUtil.isFileUrl(filePath)) { |
| 135 | + val decodedPath: String? |
| 136 | + decodedPath = try { |
| 137 | + URLDecoder.decode(filePath, "UTF-8") |
| 138 | + } catch (e: UnsupportedEncodingException) { |
| 139 | + filePath |
| 140 | + } |
| 141 | + retriever.setDataSource(decodedPath!!.replace("file://", "")) |
| 142 | + } else if (filePath!!.contains("content://")) { |
| 143 | + retriever.setDataSource(context, Uri.parse(filePath)) |
| 144 | + } else { |
| 145 | + check(Build.VERSION.SDK_INT >= 14) { "Remote videos aren't supported on sdk_version < 14" } |
| 146 | + retriever.setDataSource(filePath, headers) |
| 147 | + } |
| 148 | + val image = retriever.getFrameAtTime((time * 1000).toLong(), MediaMetadataRetriever.OPTION_CLOSEST_SYNC) |
| 149 | + try { |
| 150 | + retriever.release() |
| 151 | + } catch (e: IOException) { |
| 152 | + throw RuntimeException(e) |
| 153 | + } |
| 154 | + checkNotNull(image) { "File doesn't exist or not supported" } |
| 155 | + return image |
| 156 | + } |
| 157 | + } |
| 158 | +} |
0 commit comments