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