-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathCreateThumbnailModule.java
More file actions
235 lines (207 loc) · 9.03 KB
/
Copy pathCreateThumbnailModule.java
File metadata and controls
235 lines (207 loc) · 9.03 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package com.reactlibrary.createthumbnail;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.webkit.URLUtil;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class CreateThumbnailModule extends ReactContextBaseJavaModule {
private final Executor executor = Executors.newSingleThreadExecutor();
private final Handler handler = new Handler(Looper.getMainLooper());
private final ReactApplicationContext reactContext;
public CreateThumbnailModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
@Override
public String getName() {
return "CreateThumbnail";
}
@ReactMethod
public void create(ReadableMap options, Promise promise) {
executor.execute(() -> {
try {
ReadableMap data = processData(options);
handler.post(() -> {
promise.resolve(data);
});
} catch (Exception e) {
handler.post(() -> {
promise.reject("CreateThumbnail_ERROR", e);
});
}
});
}
private ReadableMap processData(ReadableMap options) throws IOException {
String format = options.hasKey("format") ? options.getString("format") : "jpeg";
String cacheName = options.hasKey("cacheName") ? options.getString("cacheName") : "";
String thumbnailDir = reactContext.getApplicationContext().getCacheDir().getAbsolutePath() + "/thumbnails";
File cacheDir = createDirIfNotExists(thumbnailDir);
if (!TextUtils.isEmpty(cacheName)) {
File file = new File(thumbnailDir, cacheName + "." + format);
if (file.exists()) {
WritableMap map = Arguments.createMap();
map.putString("path", "file://" + file.getAbsolutePath());
Bitmap image = BitmapFactory.decodeFile(file.getAbsolutePath());
map.putDouble("size", image.getByteCount());
map.putString("mime", "image/" + format);
map.putDouble("width", image.getWidth());
map.putDouble("height", image.getHeight());
return map;
}
}
String filePath = options.hasKey("url") ? options.getString("url") : "";
int dirSize = options.hasKey("dirSize") ? options.getInt("dirSize") : 100;
int timeStamp = options.hasKey("timeStamp") ? options.getInt("timeStamp") : 0;
int maxWidth = options.hasKey("maxWidth") ? options.getInt("maxWidth") : 512;
int maxHeight = options.hasKey("maxHeight") ? options.getInt("maxHeight") : 512;
boolean onlySyncedFrames = options.hasKey("onlySyncedFrames") ? options.getBoolean("onlySyncedFrames") : true;
HashMap headers = options.hasKey("headers") ? options.getMap("headers").toHashMap() : new HashMap<String, String>();
String fileName = TextUtils.isEmpty(cacheName) ? ("thumb-" + UUID.randomUUID().toString()) : cacheName + "." + format;
OutputStream fOut = null;
File file = new File(cacheDir, fileName);
Context context = reactContext;
Bitmap image = getBitmapAtTime(context, filePath, timeStamp, maxWidth, maxHeight, onlySyncedFrames, headers);
file.createNewFile();
fOut = new FileOutputStream(file);
// 100 means no compression, the lower you go, the stronger the compression
if (format.equals("png")) {
image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
} else {
image.compress(Bitmap.CompressFormat.JPEG, 90, fOut);
}
fOut.flush();
fOut.close();
long cacheDirSize = (long) dirSize * 1024 * 1024;
long newSize = image.getByteCount() + getDirSize(cacheDir);
// free up some cached data if size of cache dir exceeds CACHE_DIR_MAX_SIZE
if (newSize > cacheDirSize) {
cleanDir(cacheDir, cacheDirSize / 2);
}
WritableMap map = Arguments.createMap();
map.putString("path", "file://" + file.getAbsolutePath());
map.putDouble("size", image.getByteCount());
map.putString("mime", "image/" + format);
map.putDouble("width", image.getWidth());
map.putDouble("height", image.getHeight());
return map;
}
// delete previously added files one by one untill requred space is available
private static void cleanDir(File dir, long bytes) {
long bytesDeleted = 0;
File[] files = dir.listFiles();
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
for (File file : files) {
bytesDeleted += file.length();
file.delete();
if (bytesDeleted >= bytes) {
break;
}
}
}
private static File createDirIfNotExists(String path) {
File dir = new File(path);
if (dir.exists()) {
return dir;
}
try {
dir.mkdirs();
// Add .nomedia to hide the thumbnail directory from gallery
File noMedia = new File(path, ".nomedia");
noMedia.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return dir;
}
private static Bitmap getBitmapAtTime(Context context, String filePath, int time, int maxWidth, int maxHeight, boolean onlySyncedFrames, Map headers) throws IOException, IllegalStateException {
if (TextUtils.isEmpty(filePath)) {
throw new IllegalStateException("Video url is empty");
}
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
if (URLUtil.isFileUrl(filePath)) {
String decodedPath;
try {
decodedPath = URLDecoder.decode(filePath, "UTF-8");
} catch (UnsupportedEncodingException e) {
decodedPath = filePath;
}
retriever.setDataSource(decodedPath.replace("file://", ""));
} else if (filePath.contains("content://")) {
retriever.setDataSource(context, Uri.parse(filePath));
} else {
if (VERSION.SDK_INT < 14) {
throw new IllegalStateException("Remote videos aren't supported on sdk_version < 14");
}
HashMap<String, String> stringHeaders = new HashMap<>();
if (headers != null) {
for (Object key : headers.keySet()) {
Object value = headers.get(key);
if (key != null && value != null) {
stringHeaders.put(String.valueOf(key), String.valueOf(value));
}
}
}
retriever.setDataSource(filePath, stringHeaders);
}
Bitmap image;
if (Build.VERSION.SDK_INT >= 27) {
image = retriever.getScaledFrameAtTime(time * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC, maxWidth, maxHeight);
} else {
// If on versions lower than API 27, use other methods to get frames
image = retriever.getFrameAtTime(time * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
if (image != null) {
image = Bitmap.createScaledBitmap(image, maxWidth, maxHeight, true);
}
}
if (image == null) {
throw new IllegalStateException("File doesn't exist or not supported");
}
return image;
} catch (RuntimeException e) {
throw new IllegalStateException("Failed to create thumbnail for: " + filePath, e);
} finally {
try {
retriever.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static long getDirSize(File dir) {
long size = 0;
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile()) {
size += file.length();
}
}
return size;
}
}