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