1package eu.siacs.conversations.persistance;
2
3import android.annotation.TargetApi;
4import android.content.ContentResolver;
5import android.content.Context;
6import android.content.Intent;
7import android.database.Cursor;
8import android.graphics.Bitmap;
9import android.graphics.BitmapFactory;
10import android.graphics.Canvas;
11import android.graphics.Color;
12import android.graphics.Matrix;
13import android.graphics.Paint;
14import android.graphics.RectF;
15import android.media.MediaMetadataRetriever;
16import android.media.MediaScannerConnection;
17import android.net.Uri;
18import android.os.Build;
19import android.os.Environment;
20import android.os.ParcelFileDescriptor;
21import android.provider.MediaStore;
22import android.provider.OpenableColumns;
23import android.support.annotation.RequiresApi;
24import android.support.v4.content.FileProvider;
25import android.system.Os;
26import android.system.StructStat;
27import android.util.Base64;
28import android.util.Base64OutputStream;
29import android.util.Log;
30import android.util.LruCache;
31
32import java.io.ByteArrayOutputStream;
33import java.io.Closeable;
34import java.io.File;
35import java.io.FileDescriptor;
36import java.io.FileInputStream;
37import java.io.FileNotFoundException;
38import java.io.FileOutputStream;
39import java.io.IOException;
40import java.io.InputStream;
41import java.io.OutputStream;
42import java.net.Socket;
43import java.net.URL;
44import java.security.DigestOutputStream;
45import java.security.MessageDigest;
46import java.security.NoSuchAlgorithmException;
47import java.text.SimpleDateFormat;
48import java.util.ArrayList;
49import java.util.Date;
50import java.util.List;
51import java.util.Locale;
52import java.util.UUID;
53
54import eu.siacs.conversations.Config;
55import eu.siacs.conversations.R;
56import eu.siacs.conversations.entities.DownloadableFile;
57import eu.siacs.conversations.entities.Message;
58import eu.siacs.conversations.services.XmppConnectionService;
59import eu.siacs.conversations.ui.RecordingActivity;
60import eu.siacs.conversations.ui.util.Attachment;
61import eu.siacs.conversations.utils.CryptoHelper;
62import eu.siacs.conversations.utils.ExifHelper;
63import eu.siacs.conversations.utils.FileUtils;
64import eu.siacs.conversations.utils.FileWriterException;
65import eu.siacs.conversations.utils.MimeUtils;
66import eu.siacs.conversations.xmpp.pep.Avatar;
67
68public class FileBackend {
69
70 private static final Object THUMBNAIL_LOCK = new Object();
71
72 private static final SimpleDateFormat IMAGE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
73
74 private static final String FILE_PROVIDER = ".files";
75
76 private XmppConnectionService mXmppConnectionService;
77
78 private static final float IGNORE_PADDING = 0.15f;
79
80 public FileBackend(XmppConnectionService service) {
81 this.mXmppConnectionService = service;
82 }
83
84 private static boolean isInDirectoryThatShouldNotBeScanned(Context context, File file) {
85 return isInDirectoryThatShouldNotBeScanned(context, file.getAbsolutePath());
86 }
87
88 public static boolean isInDirectoryThatShouldNotBeScanned(Context context, String path) {
89 for (String type : new String[]{RecordingActivity.STORAGE_DIRECTORY_TYPE_NAME, "Files"}) {
90 if (path.startsWith(getConversationsDirectory(context, type))) {
91 return true;
92 }
93 }
94 return false;
95 }
96
97 public static long getFileSize(Context context, Uri uri) {
98 try {
99 final Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
100 if (cursor != null && cursor.moveToFirst()) {
101 long size = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
102 cursor.close();
103 return size;
104 } else {
105 return -1;
106 }
107 } catch (Exception e) {
108 return -1;
109 }
110 }
111
112 public static boolean allFilesUnderSize(Context context, List<Attachment> attachments, long max) {
113 if (max <= 0) {
114 Log.d(Config.LOGTAG, "server did not report max file size for http upload");
115 return true; //exception to be compatible with HTTP Upload < v0.2
116 }
117 for (Attachment attachment : attachments) {
118 if (attachment.getType() != Attachment.Type.FILE) {
119 continue;
120 }
121 String mime = attachment.getMime();
122 if (mime != null && mime.startsWith("video/")) {
123 try {
124 Dimensions dimensions = FileBackend.getVideoDimensions(context, attachment.getUri());
125 if (dimensions.getMin() > 720) {
126 Log.d(Config.LOGTAG, "do not consider video file with min width larger than 720 for size check");
127 continue;
128 }
129 } catch (NotAVideoFile notAVideoFile) {
130 //ignore and fall through
131 }
132 }
133 if (FileBackend.getFileSize(context, attachment.getUri()) > max) {
134 Log.d(Config.LOGTAG, "not all files are under " + max + " bytes. suggesting falling back to jingle");
135 return false;
136 }
137 }
138 return true;
139 }
140
141 public static String getConversationsDirectory(Context context, final String type) {
142 if (Config.ONLY_INTERNAL_STORAGE) {
143 return context.getFilesDir().getAbsolutePath() + "/" + type + "/";
144 } else {
145 return getAppMediaDirectory(context) + context.getString(R.string.app_name) + " " + type + "/";
146 }
147 }
148
149 public static String getAppMediaDirectory(Context context) {
150 return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + context.getString(R.string.app_name) + "/Media/";
151 }
152
153 public static String getConversationsLogsDirectory() {
154 return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Conversations/";
155 }
156
157 private static Bitmap rotate(Bitmap bitmap, int degree) {
158 if (degree == 0) {
159 return bitmap;
160 }
161 int w = bitmap.getWidth();
162 int h = bitmap.getHeight();
163 Matrix mtx = new Matrix();
164 mtx.postRotate(degree);
165 Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
166 if (bitmap != null && !bitmap.isRecycled()) {
167 bitmap.recycle();
168 }
169 return result;
170 }
171
172 public static boolean isPathBlacklisted(String path) {
173 final String androidDataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/";
174 return path.startsWith(androidDataPath);
175 }
176
177 private static Paint createAntiAliasingPaint() {
178 Paint paint = new Paint();
179 paint.setAntiAlias(true);
180 paint.setFilterBitmap(true);
181 paint.setDither(true);
182 return paint;
183 }
184
185 private static String getTakePhotoPath() {
186 return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
187 }
188
189 public static Uri getUriForFile(Context context, File file) {
190 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
191 try {
192 return FileProvider.getUriForFile(context, getAuthority(context), file);
193 } catch (IllegalArgumentException e) {
194 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
195 throw new SecurityException(e);
196 } else {
197 return Uri.fromFile(file);
198 }
199 }
200 } else {
201 return Uri.fromFile(file);
202 }
203 }
204
205 public static String getAuthority(Context context) {
206 return context.getPackageName() + FILE_PROVIDER;
207 }
208
209 private static boolean hasAlpha(final Bitmap bitmap) {
210 for (int x = 0; x < bitmap.getWidth(); ++x) {
211 for (int y = 0; y < bitmap.getWidth(); ++y) {
212 if (Color.alpha(bitmap.getPixel(x, y)) < 255) {
213 return true;
214 }
215 }
216 }
217 return false;
218 }
219
220 private static int calcSampleSize(File image, int size) {
221 BitmapFactory.Options options = new BitmapFactory.Options();
222 options.inJustDecodeBounds = true;
223 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
224 return calcSampleSize(options, size);
225 }
226
227
228 private static int calcSampleSize(BitmapFactory.Options options, int size) {
229 int height = options.outHeight;
230 int width = options.outWidth;
231 int inSampleSize = 1;
232
233 if (height > size || width > size) {
234 int halfHeight = height / 2;
235 int halfWidth = width / 2;
236
237 while ((halfHeight / inSampleSize) > size
238 && (halfWidth / inSampleSize) > size) {
239 inSampleSize *= 2;
240 }
241 }
242 return inSampleSize;
243 }
244
245 public Bitmap getPreviewForUri(Attachment attachment, int size, boolean cacheOnly) {
246 final String key = "attachment_"+attachment.getUuid().toString()+"_"+String.valueOf(size);
247 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
248 Bitmap bitmap = cache.get(key);
249 if (bitmap != null || cacheOnly) {
250 return bitmap;
251 }
252 if (attachment.getMime() != null && attachment.getMime().startsWith("video/")) {
253 bitmap = cropCenterSquareVideo(attachment.getUri(), size);
254 drawOverlay(bitmap, paintOverlayBlack(bitmap) ? R.drawable.play_video_black : R.drawable.play_video_white, 0.75f);
255 } else {
256 bitmap = cropCenterSquare(attachment.getUri(), size);
257 if (bitmap != null && "image/gif".equals(attachment.getMime())) {
258 Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
259 drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
260 bitmap.recycle();
261 bitmap = withGifOverlay;
262 }
263 }
264 if (bitmap != null) {
265 cache.put(key, bitmap);
266 }
267 return bitmap;
268 }
269
270 private static Dimensions getVideoDimensions(Context context, Uri uri) throws NotAVideoFile {
271 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
272 try {
273 mediaMetadataRetriever.setDataSource(context, uri);
274 } catch (RuntimeException e) {
275 throw new NotAVideoFile(e);
276 }
277 return getVideoDimensions(mediaMetadataRetriever);
278 }
279
280 private static Dimensions getVideoDimensionsOfFrame(MediaMetadataRetriever mediaMetadataRetriever) {
281 Bitmap bitmap = null;
282 try {
283 bitmap = mediaMetadataRetriever.getFrameAtTime();
284 return new Dimensions(bitmap.getHeight(), bitmap.getWidth());
285 } catch (Exception e) {
286 return null;
287 } finally {
288 if (bitmap != null) {
289 bitmap.recycle();
290 ;
291 }
292 }
293 }
294
295 private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever) throws NotAVideoFile {
296 String hasVideo = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
297 if (hasVideo == null) {
298 throw new NotAVideoFile();
299 }
300 Dimensions dimensions = getVideoDimensionsOfFrame(metadataRetriever);
301 if (dimensions != null) {
302 return dimensions;
303 }
304 final int rotation;
305 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
306 rotation = extractRotationFromMediaRetriever(metadataRetriever);
307 } else {
308 rotation = 0;
309 }
310 boolean rotated = rotation == 90 || rotation == 270;
311 int height;
312 try {
313 String h = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
314 height = Integer.parseInt(h);
315 } catch (Exception e) {
316 height = -1;
317 }
318 int width;
319 try {
320 String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
321 width = Integer.parseInt(w);
322 } catch (Exception e) {
323 width = -1;
324 }
325 metadataRetriever.release();
326 Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
327 return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
328 }
329
330 @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
331 private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
332 String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
333 try {
334 return Integer.parseInt(r);
335 } catch (Exception e) {
336 return 0;
337 }
338 }
339
340 public static void close(Closeable stream) {
341 if (stream != null) {
342 try {
343 stream.close();
344 } catch (IOException e) {
345 }
346 }
347 }
348
349 public static void close(Socket socket) {
350 if (socket != null) {
351 try {
352 socket.close();
353 } catch (IOException e) {
354 }
355 }
356 }
357
358 public static boolean weOwnFile(Context context, Uri uri) {
359 if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
360 return false;
361 } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
362 return fileIsInFilesDir(context, uri);
363 } else {
364 return weOwnFileLollipop(uri);
365 }
366 }
367
368 /**
369 * This is more than hacky but probably way better than doing nothing
370 * Further 'optimizations' might contain to get the parents of CacheDir and NoBackupDir
371 * and check against those as well
372 */
373 private static boolean fileIsInFilesDir(Context context, Uri uri) {
374 try {
375 final String haystack = context.getFilesDir().getParentFile().getCanonicalPath();
376 final String needle = new File(uri.getPath()).getCanonicalPath();
377 return needle.startsWith(haystack);
378 } catch (IOException e) {
379 return false;
380 }
381 }
382
383 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
384 private static boolean weOwnFileLollipop(Uri uri) {
385 try {
386 File file = new File(uri.getPath());
387 FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor();
388 StructStat st = Os.fstat(fd);
389 return st.st_uid == android.os.Process.myUid();
390 } catch (FileNotFoundException e) {
391 return false;
392 } catch (Exception e) {
393 return true;
394 }
395 }
396
397 private void createNoMedia(File diretory) {
398 final File noMedia = new File(diretory, ".nomedia");
399 if (!noMedia.exists()) {
400 try {
401 if (!noMedia.createNewFile()) {
402 Log.d(Config.LOGTAG, "created nomedia file " + noMedia.getAbsolutePath());
403 }
404 } catch (Exception e) {
405 Log.d(Config.LOGTAG, "could not create nomedia file");
406 }
407 }
408 }
409
410 public static Uri getMediaUri(Context context, File file) {
411 final String filePath = file.getAbsolutePath();
412 final Cursor cursor = context.getContentResolver().query(
413 MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
414 new String[] { MediaStore.Images.Media._ID },
415 MediaStore.Images.Media.DATA + "=? ",
416 new String[] { filePath }, null);
417 if (cursor != null && cursor.moveToFirst()) {
418 final int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
419 cursor.close();
420 return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
421 } else {
422 return null;
423 }
424 }
425
426 public void updateMediaScanner(File file) {
427 updateMediaScanner(file, null);
428 }
429
430 public void updateMediaScanner(File file, final Runnable callback) {
431 if (!isInDirectoryThatShouldNotBeScanned(mXmppConnectionService, file)) {
432 MediaScannerConnection.scanFile(mXmppConnectionService, new String[]{file.getAbsolutePath()}, null, new MediaScannerConnection.MediaScannerConnectionClient() {
433 @Override
434 public void onMediaScannerConnected() {
435
436 }
437
438 @Override
439 public void onScanCompleted(String path, Uri uri) {
440 if (callback != null && file.getAbsolutePath().equals(path)) {
441 callback.run();
442 } else {
443 Log.d(Config.LOGTAG,"media scanner scanned wrong file");
444 if (callback != null) {
445 callback.run();
446 }
447 }
448 }
449 });
450 return;
451 /*Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
452 intent.setData(Uri.fromFile(file));
453 mXmppConnectionService.sendBroadcast(intent);*/
454 } else if (file.getAbsolutePath().startsWith(getAppMediaDirectory(mXmppConnectionService))) {
455 createNoMedia(file.getParentFile());
456 }
457 if (callback != null) {
458 callback.run();
459 }
460 }
461
462 public boolean deleteFile(Message message) {
463 File file = getFile(message);
464 if (file.delete()) {
465 updateMediaScanner(file);
466 return true;
467 } else {
468 return false;
469 }
470 }
471
472 public DownloadableFile getFile(Message message) {
473 return getFile(message, true);
474 }
475
476 public DownloadableFile getFileForPath(String path) {
477 return getFileForPath(path,MimeUtils.guessMimeTypeFromExtension(MimeUtils.extractRelevantExtension(path)));
478 }
479
480 public DownloadableFile getFileForPath(String path, String mime) {
481 final DownloadableFile file;
482 if (path.startsWith("/")) {
483 file = new DownloadableFile(path);
484 } else {
485 if (mime != null && mime.startsWith("image/")) {
486 file = new DownloadableFile(getConversationsDirectory("Images") + path);
487 } else if (mime != null && mime.startsWith("video/")) {
488 file = new DownloadableFile(getConversationsDirectory("Videos") + path);
489 } else {
490 file = new DownloadableFile(getConversationsDirectory("Files") + path);
491 }
492 }
493 return file;
494 }
495
496 public boolean isInternalFile(final File file) {
497 final File internalFile = getFileForPath(file.getName());
498 return file.getAbsolutePath().equals(internalFile.getAbsolutePath());
499 }
500
501 public DownloadableFile getFile(Message message, boolean decrypted) {
502 final boolean encrypted = !decrypted
503 && (message.getEncryption() == Message.ENCRYPTION_PGP
504 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
505 String path = message.getRelativeFilePath();
506 if (path == null) {
507 path = message.getUuid();
508 }
509 final DownloadableFile file = getFileForPath(path, message.getMimeType());
510 if (encrypted) {
511 return new DownloadableFile(getConversationsDirectory("Files") + file.getName() + ".pgp");
512 } else {
513 return file;
514 }
515 }
516
517 public List<Attachment> convertToAttachments(List<DatabaseBackend.FilePath> relativeFilePaths) {
518 List<Attachment> attachments = new ArrayList<>();
519 for(DatabaseBackend.FilePath relativeFilePath : relativeFilePaths) {
520 final String mime = MimeUtils.guessMimeTypeFromExtension(MimeUtils.extractRelevantExtension(relativeFilePath.path));
521 final File file = getFileForPath(relativeFilePath.path, mime);
522 attachments.add(Attachment.of(relativeFilePath.uuid, file, mime));
523 }
524 return attachments;
525 }
526
527 private String getConversationsDirectory(final String type) {
528 return getConversationsDirectory(mXmppConnectionService, type);
529 }
530
531 private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
532 int w = originalBitmap.getWidth();
533 int h = originalBitmap.getHeight();
534 if (w <= 0 || h <= 0) {
535 throw new IOException("Decoded bitmap reported bounds smaller 0");
536 } else if (Math.max(w, h) > size) {
537 int scalledW;
538 int scalledH;
539 if (w <= h) {
540 scalledW = Math.max((int) (w / ((double) h / size)), 1);
541 scalledH = size;
542 } else {
543 scalledW = size;
544 scalledH = Math.max((int) (h / ((double) w / size)), 1);
545 }
546 final Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
547 if (!originalBitmap.isRecycled()) {
548 originalBitmap.recycle();
549 }
550 return result;
551 } else {
552 return originalBitmap;
553 }
554 }
555
556 public boolean useImageAsIs(Uri uri) {
557 String path = getOriginalPath(uri);
558 if (path == null || isPathBlacklisted(path)) {
559 return false;
560 }
561 File file = new File(path);
562 long size = file.length();
563 if (size == 0 || size >= mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize)) {
564 return false;
565 }
566 BitmapFactory.Options options = new BitmapFactory.Options();
567 options.inJustDecodeBounds = true;
568 try {
569 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options);
570 if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
571 return false;
572 }
573 return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
574 } catch (FileNotFoundException e) {
575 return false;
576 }
577 }
578
579 public String getOriginalPath(Uri uri) {
580 return FileUtils.getPath(mXmppConnectionService, uri);
581 }
582
583 private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
584 Log.d(Config.LOGTAG, "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
585 file.getParentFile().mkdirs();
586 OutputStream os = null;
587 InputStream is = null;
588 try {
589 file.createNewFile();
590 os = new FileOutputStream(file);
591 is = mXmppConnectionService.getContentResolver().openInputStream(uri);
592 byte[] buffer = new byte[1024];
593 int length;
594 while ((length = is.read(buffer)) > 0) {
595 try {
596 os.write(buffer, 0, length);
597 } catch (IOException e) {
598 throw new FileWriterException();
599 }
600 }
601 try {
602 os.flush();
603 } catch (IOException e) {
604 throw new FileWriterException();
605 }
606 } catch (FileNotFoundException e) {
607 throw new FileCopyException(R.string.error_file_not_found);
608 } catch (FileWriterException e) {
609 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
610 } catch (IOException e) {
611 e.printStackTrace();
612 throw new FileCopyException(R.string.error_io_exception);
613 } finally {
614 close(os);
615 close(is);
616 }
617 }
618
619 public void copyFileToPrivateStorage(Message message, Uri uri, String type) throws FileCopyException {
620 String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
621 Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
622 String extension = MimeUtils.guessExtensionFromMimeType(mime);
623 if (extension == null) {
624 Log.d(Config.LOGTAG, "extension from mime type was null");
625 extension = getExtensionFromUri(uri);
626 }
627 if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
628 extension = "oga";
629 }
630 message.setRelativeFilePath(message.getUuid() + "." + extension);
631 copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
632 }
633
634 private String getExtensionFromUri(Uri uri) {
635 String[] projection = {MediaStore.MediaColumns.DATA};
636 String filename = null;
637 Cursor cursor;
638 try {
639 cursor = mXmppConnectionService.getContentResolver().query(uri, projection, null, null, null);
640 } catch (IllegalArgumentException e) {
641 cursor = null;
642 }
643 if (cursor != null) {
644 try {
645 if (cursor.moveToFirst()) {
646 filename = cursor.getString(0);
647 }
648 } catch (Exception e) {
649 filename = null;
650 } finally {
651 cursor.close();
652 }
653 }
654 if (filename == null) {
655 final List<String> segments = uri.getPathSegments();
656 if (segments.size() > 0) {
657 filename = segments.get(segments.size() - 1);
658 }
659 }
660 int pos = filename == null ? -1 : filename.lastIndexOf('.');
661 return pos > 0 ? filename.substring(pos + 1) : null;
662 }
663
664 private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException {
665 file.getParentFile().mkdirs();
666 InputStream is = null;
667 OutputStream os = null;
668 try {
669 if (!file.exists() && !file.createNewFile()) {
670 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
671 }
672 is = mXmppConnectionService.getContentResolver().openInputStream(image);
673 if (is == null) {
674 throw new FileCopyException(R.string.error_not_an_image_file);
675 }
676 Bitmap originalBitmap;
677 BitmapFactory.Options options = new BitmapFactory.Options();
678 int inSampleSize = (int) Math.pow(2, sampleSize);
679 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
680 options.inSampleSize = inSampleSize;
681 originalBitmap = BitmapFactory.decodeStream(is, null, options);
682 is.close();
683 if (originalBitmap == null) {
684 throw new FileCopyException(R.string.error_not_an_image_file);
685 }
686 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
687 int rotation = getRotation(image);
688 scaledBitmap = rotate(scaledBitmap, rotation);
689 boolean targetSizeReached = false;
690 int quality = Config.IMAGE_QUALITY;
691 final int imageMaxSize = mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize);
692 while (!targetSizeReached) {
693 os = new FileOutputStream(file);
694 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
695 if (!success) {
696 throw new FileCopyException(R.string.error_compressing_image);
697 }
698 os.flush();
699 targetSizeReached = file.length() <= imageMaxSize || quality <= 50;
700 quality -= 5;
701 }
702 scaledBitmap.recycle();
703 } catch (FileNotFoundException e) {
704 throw new FileCopyException(R.string.error_file_not_found);
705 } catch (IOException e) {
706 e.printStackTrace();
707 throw new FileCopyException(R.string.error_io_exception);
708 } catch (SecurityException e) {
709 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
710 } catch (OutOfMemoryError e) {
711 ++sampleSize;
712 if (sampleSize <= 3) {
713 copyImageToPrivateStorage(file, image, sampleSize);
714 } else {
715 throw new FileCopyException(R.string.error_out_of_memory);
716 }
717 } finally {
718 close(os);
719 close(is);
720 }
721 }
722
723 public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException {
724 Log.d(Config.LOGTAG, "copy image (" + image.toString() + ") to private storage " + file.getAbsolutePath());
725 copyImageToPrivateStorage(file, image, 0);
726 }
727
728 public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException {
729 switch (Config.IMAGE_FORMAT) {
730 case JPEG:
731 message.setRelativeFilePath(message.getUuid() + ".jpg");
732 break;
733 case PNG:
734 message.setRelativeFilePath(message.getUuid() + ".png");
735 break;
736 case WEBP:
737 message.setRelativeFilePath(message.getUuid() + ".webp");
738 break;
739 }
740 copyImageToPrivateStorage(getFile(message), image);
741 updateFileParams(message);
742 }
743
744 public boolean unusualBounds(Uri image) {
745 try {
746 BitmapFactory.Options options = new BitmapFactory.Options();
747 options.inJustDecodeBounds = true;
748 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
749 float ratio = (float) options.outHeight / options.outWidth;
750 return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
751 } catch (Exception e) {
752 return false;
753 }
754 }
755
756 private int getRotation(File file) {
757 return getRotation(Uri.parse("file://" + file.getAbsolutePath()));
758 }
759
760 private int getRotation(Uri image) {
761 InputStream is = null;
762 try {
763 is = mXmppConnectionService.getContentResolver().openInputStream(image);
764 return ExifHelper.getOrientation(is);
765 } catch (FileNotFoundException e) {
766 return 0;
767 } finally {
768 close(is);
769 }
770 }
771
772 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
773 final String uuid = message.getUuid();
774 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
775 Bitmap thumbnail = cache.get(uuid);
776 if ((thumbnail == null) && (!cacheOnly)) {
777 synchronized (THUMBNAIL_LOCK) {
778 thumbnail = cache.get(uuid);
779 if (thumbnail != null) {
780 return thumbnail;
781 }
782 DownloadableFile file = getFile(message);
783 final String mime = file.getMimeType();
784 if (mime.startsWith("video/")) {
785 thumbnail = getVideoPreview(file, size);
786 } else {
787 Bitmap fullsize = getFullsizeImagePreview(file, size);
788 if (fullsize == null) {
789 throw new FileNotFoundException();
790 }
791 thumbnail = resize(fullsize, size);
792 thumbnail = rotate(thumbnail, getRotation(file));
793 if (mime.equals("image/gif")) {
794 Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
795 drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
796 thumbnail.recycle();
797 thumbnail = withGifOverlay;
798 }
799 }
800 cache.put(uuid, thumbnail);
801 }
802 }
803 return thumbnail;
804 }
805
806 private Bitmap getFullsizeImagePreview(File file, int size) {
807 BitmapFactory.Options options = new BitmapFactory.Options();
808 options.inSampleSize = calcSampleSize(file, size);
809 try {
810 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
811 } catch (OutOfMemoryError e) {
812 options.inSampleSize *= 2;
813 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
814 }
815 }
816
817 private void drawOverlay(Bitmap bitmap, int resource, float factor) {
818 Bitmap overlay = BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
819 Canvas canvas = new Canvas(bitmap);
820 float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
821 Log.d(Config.LOGTAG, "target size overlay: " + targetSize + " overlay bitmap size was " + overlay.getHeight());
822 float left = (canvas.getWidth() - targetSize) / 2.0f;
823 float top = (canvas.getHeight() - targetSize) / 2.0f;
824 RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
825 canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
826 }
827
828 /**
829 * https://stackoverflow.com/a/3943023/210897
830 */
831 private boolean paintOverlayBlack(final Bitmap bitmap) {
832 final int h = bitmap.getHeight();
833 final int w = bitmap.getWidth();
834 int record = 0;
835 for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
836 for (int x = Math.round(w * IGNORE_PADDING); x < w - Math.round(w * IGNORE_PADDING); ++x) {
837 int pixel = bitmap.getPixel(x, y);
838 if ((Color.red(pixel) * 0.299 + Color.green(pixel) * 0.587 + Color.blue(pixel) * 0.114) > 186) {
839 --record;
840 } else {
841 ++record;
842 }
843 }
844 }
845 return record < 0;
846 }
847
848 private Bitmap cropCenterSquareVideo(Uri uri, int size) {
849 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
850 Bitmap frame;
851 try {
852 metadataRetriever.setDataSource(mXmppConnectionService, uri);
853 frame = metadataRetriever.getFrameAtTime(0);
854 metadataRetriever.release();
855 return cropCenterSquare(frame, size);
856 } catch (Exception e) {
857 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
858 frame.eraseColor(0xff000000);
859 return frame;
860 }
861 }
862
863 private Bitmap getVideoPreview(File file, int size) {
864 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
865 Bitmap frame;
866 try {
867 metadataRetriever.setDataSource(file.getAbsolutePath());
868 frame = metadataRetriever.getFrameAtTime(0);
869 metadataRetriever.release();
870 frame = resize(frame, size);
871 } catch (IOException | RuntimeException e) {
872 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
873 frame.eraseColor(0xff000000);
874 }
875 drawOverlay(frame, paintOverlayBlack(frame) ? R.drawable.play_video_black : R.drawable.play_video_white, 0.75f);
876 return frame;
877 }
878
879 public Uri getTakePhotoUri() {
880 File file;
881 if (Config.ONLY_INTERNAL_STORAGE) {
882 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
883 } else {
884 file = new File(getTakePhotoPath() + "IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
885 }
886 file.getParentFile().mkdirs();
887 return getUriForFile(mXmppConnectionService, file);
888 }
889
890 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
891
892 final Avatar uncompressAvatar = getUncompressedAvatar(image);
893 if (uncompressAvatar != null && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
894 return uncompressAvatar;
895 }
896 if (uncompressAvatar != null) {
897 Log.d(Config.LOGTAG, "uncompressed avatar exceeded char limit by " + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
898 }
899
900 Bitmap bm = cropCenterSquare(image, size);
901 if (bm == null) {
902 return null;
903 }
904 if (hasAlpha(bm)) {
905 Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
906 bm.recycle();
907 bm = cropCenterSquare(image, 96);
908 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
909 }
910 return getPepAvatar(bm, format, 100);
911 }
912
913 private Avatar getUncompressedAvatar(Uri uri) {
914 Bitmap bitmap = null;
915 try {
916 bitmap = BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
917 return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
918 } catch (Exception e) {
919 return null;
920 } finally {
921 if (bitmap != null) {
922 bitmap.recycle();
923 }
924 }
925 }
926
927 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
928 try {
929 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
930 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
931 MessageDigest digest = MessageDigest.getInstance("SHA-1");
932 DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest);
933 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
934 return null;
935 }
936 mDigestOutputStream.flush();
937 mDigestOutputStream.close();
938 long chars = mByteArrayOutputStream.size();
939 if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) {
940 int q = quality - 2;
941 Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q);
942 return getPepAvatar(bitmap, format, q);
943 }
944 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
945 final Avatar avatar = new Avatar();
946 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
947 avatar.image = new String(mByteArrayOutputStream.toByteArray());
948 if (format.equals(Bitmap.CompressFormat.WEBP)) {
949 avatar.type = "image/webp";
950 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
951 avatar.type = "image/jpeg";
952 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
953 avatar.type = "image/png";
954 }
955 avatar.width = bitmap.getWidth();
956 avatar.height = bitmap.getHeight();
957 return avatar;
958 } catch (OutOfMemoryError e) {
959 Log.d(Config.LOGTAG,"unable to convert avatar to base64 due to low memory");
960 return null;
961 } catch (Exception e) {
962 return null;
963 }
964 }
965
966 public Avatar getStoredPepAvatar(String hash) {
967 if (hash == null) {
968 return null;
969 }
970 Avatar avatar = new Avatar();
971 File file = new File(getAvatarPath(hash));
972 FileInputStream is = null;
973 try {
974 avatar.size = file.length();
975 BitmapFactory.Options options = new BitmapFactory.Options();
976 options.inJustDecodeBounds = true;
977 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
978 is = new FileInputStream(file);
979 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
980 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
981 MessageDigest digest = MessageDigest.getInstance("SHA-1");
982 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
983 byte[] buffer = new byte[4096];
984 int length;
985 while ((length = is.read(buffer)) > 0) {
986 os.write(buffer, 0, length);
987 }
988 os.flush();
989 os.close();
990 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
991 avatar.image = new String(mByteArrayOutputStream.toByteArray());
992 avatar.height = options.outHeight;
993 avatar.width = options.outWidth;
994 avatar.type = options.outMimeType;
995 return avatar;
996 } catch (NoSuchAlgorithmException | IOException e) {
997 return null;
998 } finally {
999 close(is);
1000 }
1001 }
1002
1003 public boolean isAvatarCached(Avatar avatar) {
1004 File file = new File(getAvatarPath(avatar.getFilename()));
1005 return file.exists();
1006 }
1007
1008 public boolean save(final Avatar avatar) {
1009 File file;
1010 if (isAvatarCached(avatar)) {
1011 file = new File(getAvatarPath(avatar.getFilename()));
1012 avatar.size = file.length();
1013 } else {
1014 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString());
1015 if (file.getParentFile().mkdirs()) {
1016 Log.d(Config.LOGTAG, "created cache directory");
1017 }
1018 OutputStream os = null;
1019 try {
1020 if (!file.createNewFile()) {
1021 Log.d(Config.LOGTAG, "unable to create temporary file " + file.getAbsolutePath());
1022 }
1023 os = new FileOutputStream(file);
1024 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1025 digest.reset();
1026 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1027 final byte[] bytes = avatar.getImageAsBytes();
1028 mDigestOutputStream.write(bytes);
1029 mDigestOutputStream.flush();
1030 mDigestOutputStream.close();
1031 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1032 if (sha1sum.equals(avatar.sha1sum)) {
1033 File outputFile = new File(getAvatarPath(avatar.getFilename()));
1034 if (outputFile.getParentFile().mkdirs()) {
1035 Log.d(Config.LOGTAG, "created avatar directory");
1036 }
1037 String filename = getAvatarPath(avatar.getFilename());
1038 if (!file.renameTo(new File(filename))) {
1039 Log.d(Config.LOGTAG, "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1040 return false;
1041 }
1042 } else {
1043 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1044 if (!file.delete()) {
1045 Log.d(Config.LOGTAG, "unable to delete temporary file");
1046 }
1047 return false;
1048 }
1049 avatar.size = bytes.length;
1050 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1051 return false;
1052 } finally {
1053 close(os);
1054 }
1055 }
1056 return true;
1057 }
1058
1059 private String getAvatarPath(String avatar) {
1060 return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/avatars/" + avatar;
1061 }
1062
1063 public Uri getAvatarUri(String avatar) {
1064 return Uri.parse("file:" + getAvatarPath(avatar));
1065 }
1066
1067 public Bitmap cropCenterSquare(Uri image, int size) {
1068 if (image == null) {
1069 return null;
1070 }
1071 InputStream is = null;
1072 try {
1073 BitmapFactory.Options options = new BitmapFactory.Options();
1074 options.inSampleSize = calcSampleSize(image, size);
1075 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1076 if (is == null) {
1077 return null;
1078 }
1079 Bitmap input = BitmapFactory.decodeStream(is, null, options);
1080 if (input == null) {
1081 return null;
1082 } else {
1083 input = rotate(input, getRotation(image));
1084 return cropCenterSquare(input, size);
1085 }
1086 } catch (FileNotFoundException | SecurityException e) {
1087 Log.d(Config.LOGTAG,"unable to open file "+image.toString(), e);
1088 return null;
1089 } finally {
1090 close(is);
1091 }
1092 }
1093
1094 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1095 if (image == null) {
1096 return null;
1097 }
1098 InputStream is = null;
1099 try {
1100 BitmapFactory.Options options = new BitmapFactory.Options();
1101 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1102 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1103 if (is == null) {
1104 return null;
1105 }
1106 Bitmap source = BitmapFactory.decodeStream(is, null, options);
1107 if (source == null) {
1108 return null;
1109 }
1110 int sourceWidth = source.getWidth();
1111 int sourceHeight = source.getHeight();
1112 float xScale = (float) newWidth / sourceWidth;
1113 float yScale = (float) newHeight / sourceHeight;
1114 float scale = Math.max(xScale, yScale);
1115 float scaledWidth = scale * sourceWidth;
1116 float scaledHeight = scale * sourceHeight;
1117 float left = (newWidth - scaledWidth) / 2;
1118 float top = (newHeight - scaledHeight) / 2;
1119
1120 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1121 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1122 Canvas canvas = new Canvas(dest);
1123 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1124 if (source.isRecycled()) {
1125 source.recycle();
1126 }
1127 return dest;
1128 } catch (SecurityException e) {
1129 return null; //android 6.0 with revoked permissions for example
1130 } catch (FileNotFoundException e) {
1131 return null;
1132 } finally {
1133 close(is);
1134 }
1135 }
1136
1137 public Bitmap cropCenterSquare(Bitmap input, int size) {
1138 int w = input.getWidth();
1139 int h = input.getHeight();
1140
1141 float scale = Math.max((float) size / h, (float) size / w);
1142
1143 float outWidth = scale * w;
1144 float outHeight = scale * h;
1145 float left = (size - outWidth) / 2;
1146 float top = (size - outHeight) / 2;
1147 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1148
1149 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1150 Canvas canvas = new Canvas(output);
1151 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1152 if (!input.isRecycled()) {
1153 input.recycle();
1154 }
1155 return output;
1156 }
1157
1158 private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
1159 BitmapFactory.Options options = new BitmapFactory.Options();
1160 options.inJustDecodeBounds = true;
1161 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
1162 return calcSampleSize(options, size);
1163 }
1164
1165 public void updateFileParams(Message message) {
1166 updateFileParams(message, null);
1167 }
1168
1169 public void updateFileParams(Message message, URL url) {
1170 DownloadableFile file = getFile(message);
1171 final String mime = file.getMimeType();
1172 final boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
1173 final boolean video = mime != null && mime.startsWith("video/");
1174 final boolean audio = mime != null && mime.startsWith("audio/");
1175 final StringBuilder body = new StringBuilder();
1176 if (url != null) {
1177 body.append(url.toString());
1178 }
1179 body.append('|').append(file.getSize());
1180 if (image || video) {
1181 try {
1182 Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
1183 if (dimensions.valid()) {
1184 body.append('|').append(dimensions.width).append('|').append(dimensions.height);
1185 }
1186 } catch (NotAVideoFile notAVideoFile) {
1187 Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file");
1188 //fall threw
1189 }
1190 } else if (audio) {
1191 body.append("|0|0|").append(getMediaRuntime(file));
1192 }
1193 message.setBody(body.toString());
1194 message.setDeleted(false);
1195 message.setType(image ? Message.TYPE_IMAGE : Message.TYPE_FILE);
1196 }
1197
1198
1199 private int getMediaRuntime(File file) {
1200 try {
1201 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1202 mediaMetadataRetriever.setDataSource(file.toString());
1203 return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1204 } catch (RuntimeException e) {
1205 return 0;
1206 }
1207 }
1208
1209 private Dimensions getImageDimensions(File file) {
1210 BitmapFactory.Options options = new BitmapFactory.Options();
1211 options.inJustDecodeBounds = true;
1212 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1213 int rotation = getRotation(file);
1214 boolean rotated = rotation == 90 || rotation == 270;
1215 int imageHeight = rotated ? options.outWidth : options.outHeight;
1216 int imageWidth = rotated ? options.outHeight : options.outWidth;
1217 return new Dimensions(imageHeight, imageWidth);
1218 }
1219
1220 private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1221 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1222 try {
1223 metadataRetriever.setDataSource(file.getAbsolutePath());
1224 } catch (RuntimeException e) {
1225 throw new NotAVideoFile(e);
1226 }
1227 return getVideoDimensions(metadataRetriever);
1228 }
1229
1230 public Bitmap getAvatar(String avatar, int size) {
1231 if (avatar == null) {
1232 return null;
1233 }
1234 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1235 if (bm == null) {
1236 return null;
1237 }
1238 return bm;
1239 }
1240
1241 public boolean isFileAvailable(Message message) {
1242 return getFile(message).exists();
1243 }
1244
1245 private static class Dimensions {
1246 public final int width;
1247 public final int height;
1248
1249 Dimensions(int height, int width) {
1250 this.width = width;
1251 this.height = height;
1252 }
1253
1254 public int getMin() {
1255 return Math.min(width, height);
1256 }
1257
1258 public boolean valid() {
1259 return width > 0 && height > 0;
1260 }
1261 }
1262
1263 private static class NotAVideoFile extends Exception {
1264 public NotAVideoFile(Throwable t) {
1265 super(t);
1266 }
1267
1268 public NotAVideoFile() {
1269 super();
1270 }
1271 }
1272
1273 public class FileCopyException extends Exception {
1274 private static final long serialVersionUID = -1010013599132881427L;
1275 private int resId;
1276
1277 public FileCopyException(int resId) {
1278 this.resId = resId;
1279 }
1280
1281 public int getResId() {
1282 return resId;
1283 }
1284 }
1285}