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, String mime) {
477 final DownloadableFile file;
478 if (path.startsWith("/")) {
479 file = new DownloadableFile(path);
480 } else {
481 if (mime != null && mime.startsWith("image/")) {
482 file = new DownloadableFile(getConversationsDirectory("Images") + path);
483 } else if (mime != null && mime.startsWith("video/")) {
484 file = new DownloadableFile(getConversationsDirectory("Videos") + path);
485 } else {
486 file = new DownloadableFile(getConversationsDirectory("Files") + path);
487 }
488 }
489 return file;
490 }
491
492 public DownloadableFile getFile(Message message, boolean decrypted) {
493 final boolean encrypted = !decrypted
494 && (message.getEncryption() == Message.ENCRYPTION_PGP
495 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
496 String path = message.getRelativeFilePath();
497 if (path == null) {
498 path = message.getUuid();
499 }
500 final DownloadableFile file = getFileForPath(path, message.getMimeType());
501 if (encrypted) {
502 return new DownloadableFile(getConversationsDirectory("Files") + file.getName() + ".pgp");
503 } else {
504 return file;
505 }
506 }
507
508 public List<Attachment> convertToAttachments(List<DatabaseBackend.FilePath> relativeFilePaths) {
509 List<Attachment> attachments = new ArrayList<>();
510 for(DatabaseBackend.FilePath relativeFilePath : relativeFilePaths) {
511 final String mime = MimeUtils.guessMimeTypeFromExtension(MimeUtils.extractRelevantExtension(relativeFilePath.path));
512 Log.d(Config.LOGTAG,"mime="+mime);
513 File file = getFileForPath(relativeFilePath.path, mime);
514 if (file.exists()) {
515 attachments.add(Attachment.of(relativeFilePath.uuid, file,mime));
516 } else {
517 Log.d(Config.LOGTAG,"file "+file.getAbsolutePath()+" doesnt exist");
518 }
519 }
520 return attachments;
521 }
522
523 private String getConversationsDirectory(final String type) {
524 return getConversationsDirectory(mXmppConnectionService, type);
525 }
526
527 private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
528 int w = originalBitmap.getWidth();
529 int h = originalBitmap.getHeight();
530 if (w <= 0 || h <= 0) {
531 throw new IOException("Decoded bitmap reported bounds smaller 0");
532 } else if (Math.max(w, h) > size) {
533 int scalledW;
534 int scalledH;
535 if (w <= h) {
536 scalledW = Math.max((int) (w / ((double) h / size)), 1);
537 scalledH = size;
538 } else {
539 scalledW = size;
540 scalledH = Math.max((int) (h / ((double) w / size)), 1);
541 }
542 final Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
543 if (!originalBitmap.isRecycled()) {
544 originalBitmap.recycle();
545 }
546 return result;
547 } else {
548 return originalBitmap;
549 }
550 }
551
552 public boolean useImageAsIs(Uri uri) {
553 String path = getOriginalPath(uri);
554 if (path == null || isPathBlacklisted(path)) {
555 return false;
556 }
557 File file = new File(path);
558 long size = file.length();
559 if (size == 0 || size >= mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize)) {
560 return false;
561 }
562 BitmapFactory.Options options = new BitmapFactory.Options();
563 options.inJustDecodeBounds = true;
564 try {
565 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options);
566 if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
567 return false;
568 }
569 return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
570 } catch (FileNotFoundException e) {
571 return false;
572 }
573 }
574
575 public String getOriginalPath(Uri uri) {
576 return FileUtils.getPath(mXmppConnectionService, uri);
577 }
578
579 private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
580 Log.d(Config.LOGTAG, "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
581 file.getParentFile().mkdirs();
582 OutputStream os = null;
583 InputStream is = null;
584 try {
585 file.createNewFile();
586 os = new FileOutputStream(file);
587 is = mXmppConnectionService.getContentResolver().openInputStream(uri);
588 byte[] buffer = new byte[1024];
589 int length;
590 while ((length = is.read(buffer)) > 0) {
591 try {
592 os.write(buffer, 0, length);
593 } catch (IOException e) {
594 throw new FileWriterException();
595 }
596 }
597 try {
598 os.flush();
599 } catch (IOException e) {
600 throw new FileWriterException();
601 }
602 } catch (FileNotFoundException e) {
603 throw new FileCopyException(R.string.error_file_not_found);
604 } catch (FileWriterException e) {
605 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
606 } catch (IOException e) {
607 e.printStackTrace();
608 throw new FileCopyException(R.string.error_io_exception);
609 } finally {
610 close(os);
611 close(is);
612 }
613 }
614
615 public void copyFileToPrivateStorage(Message message, Uri uri, String type) throws FileCopyException {
616 String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
617 Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
618 String extension = MimeUtils.guessExtensionFromMimeType(mime);
619 if (extension == null) {
620 Log.d(Config.LOGTAG, "extension from mime type was null");
621 extension = getExtensionFromUri(uri);
622 }
623 if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
624 extension = "oga";
625 }
626 message.setRelativeFilePath(message.getUuid() + "." + extension);
627 copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
628 }
629
630 private String getExtensionFromUri(Uri uri) {
631 String[] projection = {MediaStore.MediaColumns.DATA};
632 String filename = null;
633 Cursor cursor;
634 try {
635 cursor = mXmppConnectionService.getContentResolver().query(uri, projection, null, null, null);
636 } catch (IllegalArgumentException e) {
637 cursor = null;
638 }
639 if (cursor != null) {
640 try {
641 if (cursor.moveToFirst()) {
642 filename = cursor.getString(0);
643 }
644 } catch (Exception e) {
645 filename = null;
646 } finally {
647 cursor.close();
648 }
649 }
650 if (filename == null) {
651 final List<String> segments = uri.getPathSegments();
652 if (segments.size() > 0) {
653 filename = segments.get(segments.size() - 1);
654 }
655 }
656 int pos = filename == null ? -1 : filename.lastIndexOf('.');
657 return pos > 0 ? filename.substring(pos + 1) : null;
658 }
659
660 private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException {
661 file.getParentFile().mkdirs();
662 InputStream is = null;
663 OutputStream os = null;
664 try {
665 if (!file.exists() && !file.createNewFile()) {
666 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
667 }
668 is = mXmppConnectionService.getContentResolver().openInputStream(image);
669 if (is == null) {
670 throw new FileCopyException(R.string.error_not_an_image_file);
671 }
672 Bitmap originalBitmap;
673 BitmapFactory.Options options = new BitmapFactory.Options();
674 int inSampleSize = (int) Math.pow(2, sampleSize);
675 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
676 options.inSampleSize = inSampleSize;
677 originalBitmap = BitmapFactory.decodeStream(is, null, options);
678 is.close();
679 if (originalBitmap == null) {
680 throw new FileCopyException(R.string.error_not_an_image_file);
681 }
682 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
683 int rotation = getRotation(image);
684 scaledBitmap = rotate(scaledBitmap, rotation);
685 boolean targetSizeReached = false;
686 int quality = Config.IMAGE_QUALITY;
687 final int imageMaxSize = mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize);
688 while (!targetSizeReached) {
689 os = new FileOutputStream(file);
690 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
691 if (!success) {
692 throw new FileCopyException(R.string.error_compressing_image);
693 }
694 os.flush();
695 targetSizeReached = file.length() <= imageMaxSize || quality <= 50;
696 quality -= 5;
697 }
698 scaledBitmap.recycle();
699 } catch (FileNotFoundException e) {
700 throw new FileCopyException(R.string.error_file_not_found);
701 } catch (IOException e) {
702 e.printStackTrace();
703 throw new FileCopyException(R.string.error_io_exception);
704 } catch (SecurityException e) {
705 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
706 } catch (OutOfMemoryError e) {
707 ++sampleSize;
708 if (sampleSize <= 3) {
709 copyImageToPrivateStorage(file, image, sampleSize);
710 } else {
711 throw new FileCopyException(R.string.error_out_of_memory);
712 }
713 } finally {
714 close(os);
715 close(is);
716 }
717 }
718
719 public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException {
720 Log.d(Config.LOGTAG, "copy image (" + image.toString() + ") to private storage " + file.getAbsolutePath());
721 copyImageToPrivateStorage(file, image, 0);
722 }
723
724 public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException {
725 switch (Config.IMAGE_FORMAT) {
726 case JPEG:
727 message.setRelativeFilePath(message.getUuid() + ".jpg");
728 break;
729 case PNG:
730 message.setRelativeFilePath(message.getUuid() + ".png");
731 break;
732 case WEBP:
733 message.setRelativeFilePath(message.getUuid() + ".webp");
734 break;
735 }
736 copyImageToPrivateStorage(getFile(message), image);
737 updateFileParams(message);
738 }
739
740 public boolean unusualBounds(Uri image) {
741 try {
742 BitmapFactory.Options options = new BitmapFactory.Options();
743 options.inJustDecodeBounds = true;
744 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
745 float ratio = (float) options.outHeight / options.outWidth;
746 return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
747 } catch (Exception e) {
748 return false;
749 }
750 }
751
752 private int getRotation(File file) {
753 return getRotation(Uri.parse("file://" + file.getAbsolutePath()));
754 }
755
756 private int getRotation(Uri image) {
757 InputStream is = null;
758 try {
759 is = mXmppConnectionService.getContentResolver().openInputStream(image);
760 return ExifHelper.getOrientation(is);
761 } catch (FileNotFoundException e) {
762 return 0;
763 } finally {
764 close(is);
765 }
766 }
767
768 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
769 final String uuid = message.getUuid();
770 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
771 Bitmap thumbnail = cache.get(uuid);
772 if ((thumbnail == null) && (!cacheOnly)) {
773 synchronized (THUMBNAIL_LOCK) {
774 thumbnail = cache.get(uuid);
775 if (thumbnail != null) {
776 return thumbnail;
777 }
778 DownloadableFile file = getFile(message);
779 final String mime = file.getMimeType();
780 if (mime.startsWith("video/")) {
781 thumbnail = getVideoPreview(file, size);
782 } else {
783 Bitmap fullsize = getFullsizeImagePreview(file, size);
784 if (fullsize == null) {
785 throw new FileNotFoundException();
786 }
787 thumbnail = resize(fullsize, size);
788 thumbnail = rotate(thumbnail, getRotation(file));
789 if (mime.equals("image/gif")) {
790 Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
791 drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
792 thumbnail.recycle();
793 thumbnail = withGifOverlay;
794 }
795 }
796 cache.put(uuid, thumbnail);
797 }
798 }
799 return thumbnail;
800 }
801
802 private Bitmap getFullsizeImagePreview(File file, int size) {
803 BitmapFactory.Options options = new BitmapFactory.Options();
804 options.inSampleSize = calcSampleSize(file, size);
805 try {
806 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
807 } catch (OutOfMemoryError e) {
808 options.inSampleSize *= 2;
809 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
810 }
811 }
812
813 private void drawOverlay(Bitmap bitmap, int resource, float factor) {
814 Bitmap overlay = BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
815 Canvas canvas = new Canvas(bitmap);
816 float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
817 Log.d(Config.LOGTAG, "target size overlay: " + targetSize + " overlay bitmap size was " + overlay.getHeight());
818 float left = (canvas.getWidth() - targetSize) / 2.0f;
819 float top = (canvas.getHeight() - targetSize) / 2.0f;
820 RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
821 canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
822 }
823
824 /**
825 * https://stackoverflow.com/a/3943023/210897
826 */
827 private boolean paintOverlayBlack(final Bitmap bitmap) {
828 final int h = bitmap.getHeight();
829 final int w = bitmap.getWidth();
830 int record = 0;
831 for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
832 for (int x = Math.round(w * IGNORE_PADDING); x < w - Math.round(w * IGNORE_PADDING); ++x) {
833 int pixel = bitmap.getPixel(x, y);
834 if ((Color.red(pixel) * 0.299 + Color.green(pixel) * 0.587 + Color.blue(pixel) * 0.114) > 186) {
835 --record;
836 } else {
837 ++record;
838 }
839 }
840 }
841 return record < 0;
842 }
843
844 private Bitmap cropCenterSquareVideo(Uri uri, int size) {
845 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
846 Bitmap frame;
847 try {
848 metadataRetriever.setDataSource(mXmppConnectionService, uri);
849 frame = metadataRetriever.getFrameAtTime(0);
850 metadataRetriever.release();
851 return cropCenterSquare(frame, size);
852 } catch (Exception e) {
853 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
854 frame.eraseColor(0xff000000);
855 return frame;
856 }
857 }
858
859 private Bitmap getVideoPreview(File file, int size) {
860 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
861 Bitmap frame;
862 try {
863 metadataRetriever.setDataSource(file.getAbsolutePath());
864 frame = metadataRetriever.getFrameAtTime(0);
865 metadataRetriever.release();
866 frame = resize(frame, size);
867 } catch (IOException | RuntimeException e) {
868 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
869 frame.eraseColor(0xff000000);
870 }
871 drawOverlay(frame, paintOverlayBlack(frame) ? R.drawable.play_video_black : R.drawable.play_video_white, 0.75f);
872 return frame;
873 }
874
875 public Uri getTakePhotoUri() {
876 File file;
877 if (Config.ONLY_INTERNAL_STORAGE) {
878 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
879 } else {
880 file = new File(getTakePhotoPath() + "IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
881 }
882 file.getParentFile().mkdirs();
883 return getUriForFile(mXmppConnectionService, file);
884 }
885
886 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
887
888 final Avatar uncompressAvatar = getUncompressedAvatar(image);
889 if (uncompressAvatar != null && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
890 return uncompressAvatar;
891 }
892 if (uncompressAvatar != null) {
893 Log.d(Config.LOGTAG, "uncompressed avatar exceeded char limit by " + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
894 }
895
896 Bitmap bm = cropCenterSquare(image, size);
897 if (bm == null) {
898 return null;
899 }
900 if (hasAlpha(bm)) {
901 Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
902 bm.recycle();
903 bm = cropCenterSquare(image, 96);
904 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
905 }
906 return getPepAvatar(bm, format, 100);
907 }
908
909 private Avatar getUncompressedAvatar(Uri uri) {
910 Bitmap bitmap = null;
911 try {
912 bitmap = BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
913 return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
914 } catch (Exception e) {
915 return null;
916 } finally {
917 if (bitmap != null) {
918 bitmap.recycle();
919 }
920 }
921 }
922
923 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
924 try {
925 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
926 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
927 MessageDigest digest = MessageDigest.getInstance("SHA-1");
928 DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest);
929 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
930 return null;
931 }
932 mDigestOutputStream.flush();
933 mDigestOutputStream.close();
934 long chars = mByteArrayOutputStream.size();
935 if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) {
936 int q = quality - 2;
937 Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q);
938 return getPepAvatar(bitmap, format, q);
939 }
940 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
941 final Avatar avatar = new Avatar();
942 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
943 avatar.image = new String(mByteArrayOutputStream.toByteArray());
944 if (format.equals(Bitmap.CompressFormat.WEBP)) {
945 avatar.type = "image/webp";
946 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
947 avatar.type = "image/jpeg";
948 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
949 avatar.type = "image/png";
950 }
951 avatar.width = bitmap.getWidth();
952 avatar.height = bitmap.getHeight();
953 return avatar;
954 } catch (OutOfMemoryError e) {
955 Log.d(Config.LOGTAG,"unable to convert avatar to base64 due to low memory");
956 return null;
957 } catch (Exception e) {
958 return null;
959 }
960 }
961
962 public Avatar getStoredPepAvatar(String hash) {
963 if (hash == null) {
964 return null;
965 }
966 Avatar avatar = new Avatar();
967 File file = new File(getAvatarPath(hash));
968 FileInputStream is = null;
969 try {
970 avatar.size = file.length();
971 BitmapFactory.Options options = new BitmapFactory.Options();
972 options.inJustDecodeBounds = true;
973 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
974 is = new FileInputStream(file);
975 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
976 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
977 MessageDigest digest = MessageDigest.getInstance("SHA-1");
978 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
979 byte[] buffer = new byte[4096];
980 int length;
981 while ((length = is.read(buffer)) > 0) {
982 os.write(buffer, 0, length);
983 }
984 os.flush();
985 os.close();
986 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
987 avatar.image = new String(mByteArrayOutputStream.toByteArray());
988 avatar.height = options.outHeight;
989 avatar.width = options.outWidth;
990 avatar.type = options.outMimeType;
991 return avatar;
992 } catch (NoSuchAlgorithmException | IOException e) {
993 return null;
994 } finally {
995 close(is);
996 }
997 }
998
999 public boolean isAvatarCached(Avatar avatar) {
1000 File file = new File(getAvatarPath(avatar.getFilename()));
1001 return file.exists();
1002 }
1003
1004 public boolean save(final Avatar avatar) {
1005 File file;
1006 if (isAvatarCached(avatar)) {
1007 file = new File(getAvatarPath(avatar.getFilename()));
1008 avatar.size = file.length();
1009 } else {
1010 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString());
1011 if (file.getParentFile().mkdirs()) {
1012 Log.d(Config.LOGTAG, "created cache directory");
1013 }
1014 OutputStream os = null;
1015 try {
1016 if (!file.createNewFile()) {
1017 Log.d(Config.LOGTAG, "unable to create temporary file " + file.getAbsolutePath());
1018 }
1019 os = new FileOutputStream(file);
1020 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1021 digest.reset();
1022 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1023 final byte[] bytes = avatar.getImageAsBytes();
1024 mDigestOutputStream.write(bytes);
1025 mDigestOutputStream.flush();
1026 mDigestOutputStream.close();
1027 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1028 if (sha1sum.equals(avatar.sha1sum)) {
1029 File outputFile = new File(getAvatarPath(avatar.getFilename()));
1030 if (outputFile.getParentFile().mkdirs()) {
1031 Log.d(Config.LOGTAG, "created avatar directory");
1032 }
1033 String filename = getAvatarPath(avatar.getFilename());
1034 if (!file.renameTo(new File(filename))) {
1035 Log.d(Config.LOGTAG, "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1036 return false;
1037 }
1038 } else {
1039 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1040 if (!file.delete()) {
1041 Log.d(Config.LOGTAG, "unable to delete temporary file");
1042 }
1043 return false;
1044 }
1045 avatar.size = bytes.length;
1046 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1047 return false;
1048 } finally {
1049 close(os);
1050 }
1051 }
1052 return true;
1053 }
1054
1055 private String getAvatarPath(String avatar) {
1056 return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/avatars/" + avatar;
1057 }
1058
1059 public Uri getAvatarUri(String avatar) {
1060 return Uri.parse("file:" + getAvatarPath(avatar));
1061 }
1062
1063 public Bitmap cropCenterSquare(Uri image, int size) {
1064 if (image == null) {
1065 return null;
1066 }
1067 InputStream is = null;
1068 try {
1069 BitmapFactory.Options options = new BitmapFactory.Options();
1070 options.inSampleSize = calcSampleSize(image, size);
1071 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1072 if (is == null) {
1073 return null;
1074 }
1075 Bitmap input = BitmapFactory.decodeStream(is, null, options);
1076 if (input == null) {
1077 return null;
1078 } else {
1079 input = rotate(input, getRotation(image));
1080 return cropCenterSquare(input, size);
1081 }
1082 } catch (FileNotFoundException | SecurityException e) {
1083 Log.d(Config.LOGTAG,"unable to open file "+image.toString(), e);
1084 return null;
1085 } finally {
1086 close(is);
1087 }
1088 }
1089
1090 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1091 if (image == null) {
1092 return null;
1093 }
1094 InputStream is = null;
1095 try {
1096 BitmapFactory.Options options = new BitmapFactory.Options();
1097 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1098 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1099 if (is == null) {
1100 return null;
1101 }
1102 Bitmap source = BitmapFactory.decodeStream(is, null, options);
1103 if (source == null) {
1104 return null;
1105 }
1106 int sourceWidth = source.getWidth();
1107 int sourceHeight = source.getHeight();
1108 float xScale = (float) newWidth / sourceWidth;
1109 float yScale = (float) newHeight / sourceHeight;
1110 float scale = Math.max(xScale, yScale);
1111 float scaledWidth = scale * sourceWidth;
1112 float scaledHeight = scale * sourceHeight;
1113 float left = (newWidth - scaledWidth) / 2;
1114 float top = (newHeight - scaledHeight) / 2;
1115
1116 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1117 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1118 Canvas canvas = new Canvas(dest);
1119 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1120 if (source.isRecycled()) {
1121 source.recycle();
1122 }
1123 return dest;
1124 } catch (SecurityException e) {
1125 return null; //android 6.0 with revoked permissions for example
1126 } catch (FileNotFoundException e) {
1127 return null;
1128 } finally {
1129 close(is);
1130 }
1131 }
1132
1133 public Bitmap cropCenterSquare(Bitmap input, int size) {
1134 int w = input.getWidth();
1135 int h = input.getHeight();
1136
1137 float scale = Math.max((float) size / h, (float) size / w);
1138
1139 float outWidth = scale * w;
1140 float outHeight = scale * h;
1141 float left = (size - outWidth) / 2;
1142 float top = (size - outHeight) / 2;
1143 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1144
1145 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1146 Canvas canvas = new Canvas(output);
1147 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1148 if (!input.isRecycled()) {
1149 input.recycle();
1150 }
1151 return output;
1152 }
1153
1154 private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
1155 BitmapFactory.Options options = new BitmapFactory.Options();
1156 options.inJustDecodeBounds = true;
1157 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
1158 return calcSampleSize(options, size);
1159 }
1160
1161 public void updateFileParams(Message message) {
1162 updateFileParams(message, null);
1163 }
1164
1165 public void updateFileParams(Message message, URL url) {
1166 DownloadableFile file = getFile(message);
1167 final String mime = file.getMimeType();
1168 boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
1169 boolean video = mime != null && mime.startsWith("video/");
1170 boolean audio = mime != null && mime.startsWith("audio/");
1171 final StringBuilder body = new StringBuilder();
1172 if (url != null) {
1173 body.append(url.toString());
1174 }
1175 body.append('|').append(file.getSize());
1176 if (image || video) {
1177 try {
1178 Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
1179 if (dimensions.valid()) {
1180 body.append('|').append(dimensions.width).append('|').append(dimensions.height);
1181 }
1182 } catch (NotAVideoFile notAVideoFile) {
1183 Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file");
1184 //fall threw
1185 }
1186 } else if (audio) {
1187 body.append("|0|0|").append(getMediaRuntime(file));
1188 }
1189 message.setBody(body.toString());
1190 }
1191
1192 public int getMediaRuntime(Uri uri) {
1193 try {
1194 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1195 mediaMetadataRetriever.setDataSource(mXmppConnectionService, uri);
1196 return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1197 } catch (RuntimeException e) {
1198 return 0;
1199 }
1200 }
1201
1202 private int getMediaRuntime(File file) {
1203 try {
1204 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1205 mediaMetadataRetriever.setDataSource(file.toString());
1206 return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1207 } catch (RuntimeException e) {
1208 return 0;
1209 }
1210 }
1211
1212 private Dimensions getImageDimensions(File file) {
1213 BitmapFactory.Options options = new BitmapFactory.Options();
1214 options.inJustDecodeBounds = true;
1215 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1216 int rotation = getRotation(file);
1217 boolean rotated = rotation == 90 || rotation == 270;
1218 int imageHeight = rotated ? options.outWidth : options.outHeight;
1219 int imageWidth = rotated ? options.outHeight : options.outWidth;
1220 return new Dimensions(imageHeight, imageWidth);
1221 }
1222
1223 private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1224 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1225 try {
1226 metadataRetriever.setDataSource(file.getAbsolutePath());
1227 } catch (RuntimeException e) {
1228 throw new NotAVideoFile(e);
1229 }
1230 return getVideoDimensions(metadataRetriever);
1231 }
1232
1233 public Bitmap getAvatar(String avatar, int size) {
1234 if (avatar == null) {
1235 return null;
1236 }
1237 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1238 if (bm == null) {
1239 return null;
1240 }
1241 return bm;
1242 }
1243
1244 public boolean isFileAvailable(Message message) {
1245 return getFile(message).exists();
1246 }
1247
1248 private static class Dimensions {
1249 public final int width;
1250 public final int height;
1251
1252 Dimensions(int height, int width) {
1253 this.width = width;
1254 this.height = height;
1255 }
1256
1257 public int getMin() {
1258 return Math.min(width, height);
1259 }
1260
1261 public boolean valid() {
1262 return width > 0 && height > 0;
1263 }
1264 }
1265
1266 private static class NotAVideoFile extends Exception {
1267 public NotAVideoFile(Throwable t) {
1268 super(t);
1269 }
1270
1271 public NotAVideoFile() {
1272 super();
1273 }
1274 }
1275
1276 public class FileCopyException extends Exception {
1277 private static final long serialVersionUID = -1010013599132881427L;
1278 private int resId;
1279
1280 public FileCopyException(int resId) {
1281 this.resId = resId;
1282 }
1283
1284 public int getResId() {
1285 return resId;
1286 }
1287 }
1288}