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