1package eu.siacs.conversations.persistance;
2
3import android.content.ContentResolver;
4import android.content.Context;
5import android.database.Cursor;
6import android.graphics.Bitmap;
7import android.graphics.BitmapFactory;
8import android.graphics.Canvas;
9import android.graphics.Color;
10import android.graphics.Matrix;
11import android.graphics.Paint;
12import android.graphics.RectF;
13import android.graphics.pdf.PdfRenderer;
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.system.Os;
23import android.system.StructStat;
24import android.util.Base64;
25import android.util.Base64OutputStream;
26import android.util.DisplayMetrics;
27import android.util.Log;
28import android.util.LruCache;
29
30import androidx.annotation.RequiresApi;
31import androidx.annotation.StringRes;
32import androidx.core.content.FileProvider;
33import androidx.exifinterface.media.ExifInterface;
34
35import com.google.common.base.Strings;
36import com.google.common.collect.ImmutableList;
37import com.google.common.io.ByteStreams;
38
39import java.io.ByteArrayOutputStream;
40import java.io.Closeable;
41import java.io.File;
42import java.io.FileDescriptor;
43import java.io.FileInputStream;
44import java.io.FileNotFoundException;
45import java.io.FileOutputStream;
46import java.io.IOException;
47import java.io.InputStream;
48import java.io.OutputStream;
49import java.net.ServerSocket;
50import java.net.Socket;
51import java.security.DigestOutputStream;
52import java.security.MessageDigest;
53import java.security.NoSuchAlgorithmException;
54import java.text.SimpleDateFormat;
55import java.util.ArrayList;
56import java.util.Date;
57import java.util.List;
58import java.util.Locale;
59import java.util.UUID;
60
61import eu.siacs.conversations.Config;
62import eu.siacs.conversations.R;
63import eu.siacs.conversations.entities.DownloadableFile;
64import eu.siacs.conversations.entities.Message;
65import eu.siacs.conversations.services.AttachFileToConversationRunnable;
66import eu.siacs.conversations.services.XmppConnectionService;
67import eu.siacs.conversations.ui.adapter.MediaAdapter;
68import eu.siacs.conversations.ui.util.Attachment;
69import eu.siacs.conversations.utils.CryptoHelper;
70import eu.siacs.conversations.utils.FileUtils;
71import eu.siacs.conversations.utils.FileWriterException;
72import eu.siacs.conversations.utils.MimeUtils;
73import eu.siacs.conversations.xmpp.pep.Avatar;
74
75public class FileBackend {
76
77 private static final Object THUMBNAIL_LOCK = new Object();
78
79 private static final SimpleDateFormat IMAGE_DATE_FORMAT =
80 new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
81
82 private static final String FILE_PROVIDER = ".files";
83 private static final float IGNORE_PADDING = 0.15f;
84 private final XmppConnectionService mXmppConnectionService;
85
86 private static final List<String> STORAGE_TYPES;
87
88 static {
89 final ImmutableList.Builder<String> builder =
90 new ImmutableList.Builder<String>()
91 .add(
92 Environment.DIRECTORY_DOWNLOADS,
93 Environment.DIRECTORY_PICTURES,
94 Environment.DIRECTORY_MOVIES,
95 Environment.DIRECTORY_DOCUMENTS);
96 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
97 builder.add(Environment.DIRECTORY_RECORDINGS);
98 }
99 STORAGE_TYPES = builder.build();
100 }
101
102 public FileBackend(XmppConnectionService service) {
103 this.mXmppConnectionService = service;
104 }
105
106 public static long getFileSize(Context context, Uri uri) {
107 try (final Cursor cursor =
108 context.getContentResolver().query(uri, null, null, null, null)) {
109 if (cursor != null && cursor.moveToFirst()) {
110 final int index = cursor.getColumnIndex(OpenableColumns.SIZE);
111 if (index == -1) {
112 return -1;
113 }
114 return cursor.getLong(index);
115 }
116 return -1;
117 } catch (final Exception ignored) {
118 return -1;
119 }
120 }
121
122 public static boolean allFilesUnderSize(
123 Context context, List<Attachment> attachments, long max) {
124 final boolean compressVideo =
125 !AttachFileToConversationRunnable.getVideoCompression(context)
126 .equals("uncompressed");
127 if (max <= 0) {
128 Log.d(Config.LOGTAG, "server did not report max file size for http upload");
129 return true; // exception to be compatible with HTTP Upload < v0.2
130 }
131 for (Attachment attachment : attachments) {
132 if (attachment.getType() != Attachment.Type.FILE) {
133 continue;
134 }
135 String mime = attachment.getMime();
136 if (mime != null && mime.startsWith("video/") && compressVideo) {
137 try {
138 Dimensions dimensions =
139 FileBackend.getVideoDimensions(context, attachment.getUri());
140 if (dimensions.getMin() > 720) {
141 Log.d(
142 Config.LOGTAG,
143 "do not consider video file with min width larger than 720 for size check");
144 continue;
145 }
146 } catch (final IOException | NotAVideoFile e) {
147 // ignore and fall through
148 }
149 }
150 if (FileBackend.getFileSize(context, attachment.getUri()) > max) {
151 Log.d(
152 Config.LOGTAG,
153 "not all files are under "
154 + max
155 + " bytes. suggesting falling back to jingle");
156 return false;
157 }
158 }
159 return true;
160 }
161
162 public static File getBackupDirectory(final Context context) {
163 final File conversationsDownloadDirectory =
164 new File(
165 Environment.getExternalStoragePublicDirectory(
166 Environment.DIRECTORY_DOWNLOADS),
167 context.getString(R.string.app_name));
168 return new File(conversationsDownloadDirectory, "Backup");
169 }
170
171 public static File getLegacyBackupDirectory(final String app) {
172 final File appDirectory = new File(Environment.getExternalStorageDirectory(), app);
173 return new File(appDirectory, "Backup");
174 }
175
176 private static Bitmap rotate(final Bitmap bitmap, final int degree) {
177 if (degree == 0) {
178 return bitmap;
179 }
180 final int w = bitmap.getWidth();
181 final int h = bitmap.getHeight();
182 final Matrix matrix = new Matrix();
183 matrix.postRotate(degree);
184 final Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
185 if (!bitmap.isRecycled()) {
186 bitmap.recycle();
187 }
188 return result;
189 }
190
191 public static boolean isPathBlacklisted(String path) {
192 final String androidDataPath =
193 Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/";
194 return path.startsWith(androidDataPath);
195 }
196
197 private static Paint createAntiAliasingPaint() {
198 Paint paint = new Paint();
199 paint.setAntiAlias(true);
200 paint.setFilterBitmap(true);
201 paint.setDither(true);
202 return paint;
203 }
204
205 public static Uri getUriForUri(Context context, Uri uri) {
206 if ("file".equals(uri.getScheme())) {
207 return getUriForFile(context, new File(uri.getPath()));
208 } else {
209 return uri;
210 }
211 }
212
213 public static Uri getUriForFile(Context context, File file) {
214 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
215 try {
216 return FileProvider.getUriForFile(context, getAuthority(context), file);
217 } catch (IllegalArgumentException e) {
218 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
219 throw new SecurityException(e);
220 } else {
221 return Uri.fromFile(file);
222 }
223 }
224 } else {
225 return Uri.fromFile(file);
226 }
227 }
228
229 public static String getAuthority(Context context) {
230 return context.getPackageName() + FILE_PROVIDER;
231 }
232
233 private static boolean hasAlpha(final Bitmap bitmap) {
234 final int w = bitmap.getWidth();
235 final int h = bitmap.getHeight();
236 final int yStep = Math.max(1, w / 100);
237 final int xStep = Math.max(1, h / 100);
238 for (int x = 0; x < w; x += xStep) {
239 for (int y = 0; y < h; y += yStep) {
240 if (Color.alpha(bitmap.getPixel(x, y)) < 255) {
241 return true;
242 }
243 }
244 }
245 return false;
246 }
247
248 private static int calcSampleSize(File image, int size) {
249 BitmapFactory.Options options = new BitmapFactory.Options();
250 options.inJustDecodeBounds = true;
251 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
252 return calcSampleSize(options, size);
253 }
254
255 private static int calcSampleSize(BitmapFactory.Options options, int size) {
256 int height = options.outHeight;
257 int width = options.outWidth;
258 int inSampleSize = 1;
259
260 if (height > size || width > size) {
261 int halfHeight = height / 2;
262 int halfWidth = width / 2;
263
264 while ((halfHeight / inSampleSize) > size && (halfWidth / inSampleSize) > size) {
265 inSampleSize *= 2;
266 }
267 }
268 return inSampleSize;
269 }
270
271 private static Dimensions getVideoDimensions(Context context, Uri uri) throws NotAVideoFile, IOException {
272 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
273 try {
274 mediaMetadataRetriever.setDataSource(context, uri);
275 } catch (RuntimeException e) {
276 throw new NotAVideoFile(e);
277 }
278 return getVideoDimensions(mediaMetadataRetriever);
279 }
280
281 private static Dimensions getVideoDimensionsOfFrame(
282 MediaMetadataRetriever mediaMetadataRetriever) {
283 Bitmap bitmap = null;
284 try {
285 bitmap = mediaMetadataRetriever.getFrameAtTime();
286 return new Dimensions(bitmap.getHeight(), bitmap.getWidth());
287 } catch (Exception e) {
288 return null;
289 } finally {
290 if (bitmap != null) {
291 bitmap.recycle();
292 }
293 }
294 }
295
296 private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever)
297 throws NotAVideoFile, IOException {
298 String hasVideo =
299 metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
300 if (hasVideo == null) {
301 throw new NotAVideoFile();
302 }
303 Dimensions dimensions = getVideoDimensionsOfFrame(metadataRetriever);
304 if (dimensions != null) {
305 return dimensions;
306 }
307 final int rotation = extractRotationFromMediaRetriever(metadataRetriever);
308 boolean rotated = rotation == 90 || rotation == 270;
309 int height;
310 try {
311 String h =
312 metadataRetriever.extractMetadata(
313 MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
314 height = Integer.parseInt(h);
315 } catch (Exception e) {
316 height = -1;
317 }
318 int width;
319 try {
320 String w =
321 metadataRetriever.extractMetadata(
322 MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
323 width = Integer.parseInt(w);
324 } catch (Exception e) {
325 width = -1;
326 }
327 metadataRetriever.release();
328 Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
329 return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
330 }
331
332 private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
333 String r =
334 metadataRetriever.extractMetadata(
335 MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
336 try {
337 return Integer.parseInt(r);
338 } catch (Exception e) {
339 return 0;
340 }
341 }
342
343 public static void close(final Closeable stream) {
344 if (stream != null) {
345 try {
346 stream.close();
347 } catch (Exception e) {
348 Log.d(Config.LOGTAG, "unable to close stream", e);
349 }
350 }
351 }
352
353 public static void close(final Socket socket) {
354 if (socket != null) {
355 try {
356 socket.close();
357 } catch (IOException e) {
358 Log.d(Config.LOGTAG, "unable to close socket", e);
359 }
360 }
361 }
362
363 public static void close(final ServerSocket socket) {
364 if (socket != null) {
365 try {
366 socket.close();
367 } catch (IOException e) {
368 Log.d(Config.LOGTAG, "unable to close server socket", e);
369 }
370 }
371 }
372
373 public static boolean dangerousFile(final Uri uri) {
374 if (uri == null || Strings.isNullOrEmpty(uri.getScheme())) {
375 return true;
376 }
377 if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
378 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
379 // On Android 7 (and apps that target 7) it is now longer possible to share files
380 // with a file scheme. By now you should probably not be running apps that target
381 // anything less than 7 any more
382 return true;
383 } else {
384 return isFileOwnedByProcess(uri);
385 }
386 }
387 return false;
388 }
389
390 private static boolean isFileOwnedByProcess(final Uri uri) {
391 final String path = uri.getPath();
392 if (path == null) {
393 return true;
394 }
395 try (final var pfd =
396 ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY)) {
397 final FileDescriptor fd = pfd.getFileDescriptor();
398 final StructStat st = Os.fstat(fd);
399 return st.st_uid == android.os.Process.myUid();
400 } catch (final Exception e) {
401 // when in doubt. better safe than sorry
402 return true;
403 }
404 }
405
406 public static Uri getMediaUri(Context context, File file) {
407 final String filePath = file.getAbsolutePath();
408 try (final Cursor cursor =
409 context.getContentResolver()
410 .query(
411 MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
412 new String[] {MediaStore.Images.Media._ID},
413 MediaStore.Images.Media.DATA + "=? ",
414 new String[] {filePath},
415 null)) {
416 if (cursor != null && cursor.moveToFirst()) {
417 final int id =
418 cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
419 return Uri.withAppendedPath(
420 MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
421 } else {
422 return null;
423 }
424 } catch (final Exception e) {
425 return null;
426 }
427 }
428
429 public static void updateFileParams(Message message, String url, long size) {
430 final StringBuilder body = new StringBuilder();
431 body.append(url).append('|').append(size);
432 message.setBody(body.toString());
433 }
434
435 public Bitmap getPreviewForUri(Attachment attachment, int size, boolean cacheOnly) {
436 final String key = "attachment_" + attachment.getUuid().toString() + "_" + size;
437 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
438 Bitmap bitmap = cache.get(key);
439 if (bitmap != null || cacheOnly) {
440 return bitmap;
441 }
442 final String mime = attachment.getMime();
443 if ("application/pdf".equals(mime)) {
444 bitmap = cropCenterSquarePdf(attachment.getUri(), size);
445 drawOverlay(
446 bitmap,
447 paintOverlayBlackPdf(bitmap)
448 ? R.drawable.open_pdf_black
449 : R.drawable.open_pdf_white,
450 0.75f);
451 } else if (mime != null && mime.startsWith("video/")) {
452 bitmap = cropCenterSquareVideo(attachment.getUri(), size);
453 drawOverlay(
454 bitmap,
455 paintOverlayBlack(bitmap)
456 ? R.drawable.play_video_black
457 : R.drawable.play_video_white,
458 0.75f);
459 } else {
460 bitmap = cropCenterSquare(attachment.getUri(), size);
461 if (bitmap != null && "image/gif".equals(mime)) {
462 Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
463 drawOverlay(
464 withGifOverlay,
465 paintOverlayBlack(withGifOverlay)
466 ? R.drawable.play_gif_black
467 : R.drawable.play_gif_white,
468 1.0f);
469 bitmap.recycle();
470 bitmap = withGifOverlay;
471 }
472 }
473 if (bitmap != null) {
474 cache.put(key, bitmap);
475 }
476 return bitmap;
477 }
478
479 public void updateMediaScanner(File file) {
480 updateMediaScanner(file, null);
481 }
482
483 public void updateMediaScanner(File file, final Runnable callback) {
484 MediaScannerConnection.scanFile(
485 mXmppConnectionService,
486 new String[] {file.getAbsolutePath()},
487 null,
488 new MediaScannerConnection.MediaScannerConnectionClient() {
489 @Override
490 public void onMediaScannerConnected() {}
491
492 @Override
493 public void onScanCompleted(String path, Uri uri) {
494 if (callback != null && file.getAbsolutePath().equals(path)) {
495 callback.run();
496 } else {
497 Log.d(Config.LOGTAG, "media scanner scanned wrong file");
498 if (callback != null) {
499 callback.run();
500 }
501 }
502 }
503 });
504 }
505
506 public boolean deleteFile(Message message) {
507 File file = getFile(message);
508 if (file.delete()) {
509 updateMediaScanner(file);
510 return true;
511 } else {
512 return false;
513 }
514 }
515
516 public DownloadableFile getFile(Message message) {
517 return getFile(message, true);
518 }
519
520 public DownloadableFile getFileForPath(String path) {
521 return getFileForPath(
522 path,
523 MimeUtils.guessMimeTypeFromExtension(MimeUtils.extractRelevantExtension(path)));
524 }
525
526 private DownloadableFile getFileForPath(final String path, final String mime) {
527 if (path.startsWith("/")) {
528 return new DownloadableFile(path);
529 } else {
530 return getLegacyFileForFilename(path, mime);
531 }
532 }
533
534 public DownloadableFile getLegacyFileForFilename(final String filename, final String mime) {
535 if (Strings.isNullOrEmpty(mime)) {
536 return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
537 } else if (mime.startsWith("image/")) {
538 return new DownloadableFile(getLegacyStorageLocation("Images"), filename);
539 } else if (mime.startsWith("video/")) {
540 return new DownloadableFile(getLegacyStorageLocation("Videos"), filename);
541 } else {
542 return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
543 }
544 }
545
546 public boolean isInternalFile(final File file) {
547 final File internalFile = getFileForPath(file.getName());
548 return file.getAbsolutePath().equals(internalFile.getAbsolutePath());
549 }
550
551 public DownloadableFile getFile(Message message, boolean decrypted) {
552 final boolean encrypted =
553 !decrypted
554 && (message.getEncryption() == Message.ENCRYPTION_PGP
555 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
556 String path = message.getRelativeFilePath();
557 if (path == null) {
558 path = message.getUuid();
559 }
560 final DownloadableFile file = getFileForPath(path, message.getMimeType());
561 if (encrypted) {
562 return new DownloadableFile(
563 mXmppConnectionService.getCacheDir(),
564 String.format("%s.%s", file.getName(), "pgp"));
565 } else {
566 return file;
567 }
568 }
569
570 public List<Attachment> convertToAttachments(List<DatabaseBackend.FilePath> relativeFilePaths) {
571 final List<Attachment> attachments = new ArrayList<>();
572 for (final DatabaseBackend.FilePath relativeFilePath : relativeFilePaths) {
573 final String mime =
574 MimeUtils.guessMimeTypeFromExtension(
575 MimeUtils.extractRelevantExtension(relativeFilePath.path));
576 final File file = getFileForPath(relativeFilePath.path, mime);
577 attachments.add(Attachment.of(relativeFilePath.uuid, file, mime));
578 }
579 return attachments;
580 }
581
582 private File getLegacyStorageLocation(final String type) {
583 if (Config.ONLY_INTERNAL_STORAGE) {
584 return new File(mXmppConnectionService.getFilesDir(), type);
585 } else {
586 final File appDirectory =
587 new File(
588 Environment.getExternalStorageDirectory(),
589 mXmppConnectionService.getString(R.string.app_name));
590 final File appMediaDirectory = new File(appDirectory, "Media");
591 final String locationName =
592 String.format(
593 "%s %s", mXmppConnectionService.getString(R.string.app_name), type);
594 return new File(appMediaDirectory, locationName);
595 }
596 }
597
598 private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
599 int w = originalBitmap.getWidth();
600 int h = originalBitmap.getHeight();
601 if (w <= 0 || h <= 0) {
602 throw new IOException("Decoded bitmap reported bounds smaller 0");
603 } else if (Math.max(w, h) > size) {
604 int scalledW;
605 int scalledH;
606 if (w <= h) {
607 scalledW = Math.max((int) (w / ((double) h / size)), 1);
608 scalledH = size;
609 } else {
610 scalledW = size;
611 scalledH = Math.max((int) (h / ((double) w / size)), 1);
612 }
613 final Bitmap result =
614 Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
615 if (!originalBitmap.isRecycled()) {
616 originalBitmap.recycle();
617 }
618 return result;
619 } else {
620 return originalBitmap;
621 }
622 }
623
624 public boolean useImageAsIs(final Uri uri) {
625 final String path = getOriginalPath(uri);
626 if (path == null || isPathBlacklisted(path)) {
627 return false;
628 }
629 final File file = new File(path);
630 long size = file.length();
631 if (size == 0
632 || size
633 >= mXmppConnectionService
634 .getResources()
635 .getInteger(R.integer.auto_accept_filesize)) {
636 return false;
637 }
638 BitmapFactory.Options options = new BitmapFactory.Options();
639 options.inJustDecodeBounds = true;
640 try {
641 final InputStream inputStream =
642 mXmppConnectionService.getContentResolver().openInputStream(uri);
643 BitmapFactory.decodeStream(inputStream, null, options);
644 close(inputStream);
645 if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
646 return false;
647 }
648 return (options.outWidth <= Config.IMAGE_SIZE
649 && options.outHeight <= Config.IMAGE_SIZE
650 && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
651 } catch (FileNotFoundException e) {
652 Log.d(Config.LOGTAG, "unable to get image dimensions", e);
653 return false;
654 }
655 }
656
657 public String getOriginalPath(final Uri uri) {
658 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
659 // On Android 11+ we don’t have access to the original file
660 return null;
661 } else {
662 return FileUtils.getPath(mXmppConnectionService, uri);
663 }
664 }
665
666 private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
667 Log.d(
668 Config.LOGTAG,
669 "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
670 file.getParentFile().mkdirs();
671 try {
672 file.createNewFile();
673 } catch (IOException e) {
674 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
675 }
676 try (final OutputStream os = new FileOutputStream(file);
677 final InputStream is =
678 mXmppConnectionService.getContentResolver().openInputStream(uri)) {
679 if (is == null) {
680 throw new FileCopyException(R.string.error_file_not_found);
681 }
682 try {
683 ByteStreams.copy(is, os);
684 } catch (IOException e) {
685 throw new FileWriterException(file);
686 }
687 try {
688 os.flush();
689 } catch (IOException e) {
690 throw new FileWriterException(file);
691 }
692 } catch (final FileNotFoundException e) {
693 cleanup(file);
694 throw new FileCopyException(R.string.error_file_not_found);
695 } catch (final FileWriterException e) {
696 cleanup(file);
697 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
698 } catch (final SecurityException | IllegalStateException e) {
699 cleanup(file);
700 throw new FileCopyException(R.string.error_security_exception);
701 } catch (final IOException e) {
702 cleanup(file);
703 throw new FileCopyException(R.string.error_io_exception);
704 }
705 }
706
707 public void copyFileToPrivateStorage(Message message, Uri uri, String type)
708 throws FileCopyException {
709 String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
710 Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
711 String extension = MimeUtils.guessExtensionFromMimeType(mime);
712 if (extension == null) {
713 Log.d(Config.LOGTAG, "extension from mime type was null");
714 extension = getExtensionFromUri(uri);
715 }
716 if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
717 extension = "oga";
718 }
719 setupRelativeFilePath(message, String.format("%s.%s", message.getUuid(), extension));
720 copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
721 }
722
723 private String getExtensionFromUri(final Uri uri) {
724 final String[] projection = {MediaStore.MediaColumns.DATA};
725 String filename = null;
726 try (final Cursor cursor =
727 mXmppConnectionService
728 .getContentResolver()
729 .query(uri, projection, null, null, null)) {
730 if (cursor != null && cursor.moveToFirst()) {
731 filename = cursor.getString(0);
732 }
733 } catch (final Exception e) {
734 filename = null;
735 }
736 if (filename == null) {
737 final List<String> segments = uri.getPathSegments();
738 if (segments.size() > 0) {
739 filename = segments.get(segments.size() - 1);
740 }
741 }
742 final int pos = filename == null ? -1 : filename.lastIndexOf('.');
743 return pos > 0 ? filename.substring(pos + 1) : null;
744 }
745
746 private void copyImageToPrivateStorage(File file, Uri image, int sampleSize)
747 throws FileCopyException, ImageCompressionException {
748 final File parent = file.getParentFile();
749 if (parent != null && parent.mkdirs()) {
750 Log.d(Config.LOGTAG, "created parent directory");
751 }
752 InputStream is = null;
753 OutputStream os = null;
754 try {
755 if (!file.exists() && !file.createNewFile()) {
756 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
757 }
758 is = mXmppConnectionService.getContentResolver().openInputStream(image);
759 if (is == null) {
760 throw new FileCopyException(R.string.error_not_an_image_file);
761 }
762 final Bitmap originalBitmap;
763 final BitmapFactory.Options options = new BitmapFactory.Options();
764 final int inSampleSize = (int) Math.pow(2, sampleSize);
765 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
766 options.inSampleSize = inSampleSize;
767 originalBitmap = BitmapFactory.decodeStream(is, null, options);
768 is.close();
769 if (originalBitmap == null) {
770 throw new ImageCompressionException("Source file was not an image");
771 }
772 if (!"image/jpeg".equals(options.outMimeType) && hasAlpha(originalBitmap)) {
773 originalBitmap.recycle();
774 throw new ImageCompressionException("Source file had alpha channel");
775 }
776 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
777 final int rotation = getRotation(image);
778 scaledBitmap = rotate(scaledBitmap, rotation);
779 boolean targetSizeReached = false;
780 int quality = Config.IMAGE_QUALITY;
781 final int imageMaxSize =
782 mXmppConnectionService
783 .getResources()
784 .getInteger(R.integer.auto_accept_filesize);
785 while (!targetSizeReached) {
786 os = new FileOutputStream(file);
787 Log.d(Config.LOGTAG, "compressing image with quality " + quality);
788 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
789 if (!success) {
790 throw new FileCopyException(R.string.error_compressing_image);
791 }
792 os.flush();
793 final long fileSize = file.length();
794 Log.d(Config.LOGTAG, "achieved file size of " + fileSize);
795 targetSizeReached = fileSize <= imageMaxSize || quality <= 50;
796 quality -= 5;
797 }
798 scaledBitmap.recycle();
799 } catch (final FileNotFoundException e) {
800 cleanup(file);
801 throw new FileCopyException(R.string.error_file_not_found);
802 } catch (final IOException e) {
803 cleanup(file);
804 throw new FileCopyException(R.string.error_io_exception);
805 } catch (SecurityException e) {
806 cleanup(file);
807 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
808 } catch (final OutOfMemoryError e) {
809 ++sampleSize;
810 if (sampleSize <= 3) {
811 copyImageToPrivateStorage(file, image, sampleSize);
812 } else {
813 throw new FileCopyException(R.string.error_out_of_memory);
814 }
815 } finally {
816 close(os);
817 close(is);
818 }
819 }
820
821 private static void cleanup(final File file) {
822 try {
823 file.delete();
824 } catch (Exception e) {
825
826 }
827 }
828
829 public void copyImageToPrivateStorage(File file, Uri image)
830 throws FileCopyException, ImageCompressionException {
831 Log.d(
832 Config.LOGTAG,
833 "copy image ("
834 + image.toString()
835 + ") to private storage "
836 + file.getAbsolutePath());
837 copyImageToPrivateStorage(file, image, 0);
838 }
839
840 public void copyImageToPrivateStorage(Message message, Uri image)
841 throws FileCopyException, ImageCompressionException {
842 final String filename;
843 switch (Config.IMAGE_FORMAT) {
844 case JPEG:
845 filename = String.format("%s.%s", message.getUuid(), "jpg");
846 break;
847 case PNG:
848 filename = String.format("%s.%s", message.getUuid(), "png");
849 break;
850 case WEBP:
851 filename = String.format("%s.%s", message.getUuid(), "webp");
852 break;
853 default:
854 throw new IllegalStateException("Unknown image format");
855 }
856 setupRelativeFilePath(message, filename);
857 copyImageToPrivateStorage(getFile(message), image);
858 updateFileParams(message);
859 }
860
861 public void setupRelativeFilePath(final Message message, final String filename) {
862 final String extension = MimeUtils.extractRelevantExtension(filename);
863 final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
864 setupRelativeFilePath(message, filename, mime);
865 }
866
867 public File getStorageLocation(final String filename, final String mime) {
868 final File parentDirectory;
869 if (Strings.isNullOrEmpty(mime)) {
870 parentDirectory =
871 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
872 } else if (mime.startsWith("image/")) {
873 parentDirectory =
874 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
875 } else if (mime.startsWith("video/")) {
876 parentDirectory =
877 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
878 } else if (MediaAdapter.DOCUMENT_MIMES.contains(mime)) {
879 parentDirectory =
880 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
881 } else {
882 parentDirectory =
883 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
884 }
885 final File appDirectory =
886 new File(parentDirectory, mXmppConnectionService.getString(R.string.app_name));
887 return new File(appDirectory, filename);
888 }
889
890 public static boolean inConversationsDirectory(final Context context, String path) {
891 final File fileDirectory = new File(path).getParentFile();
892 for (final String type : STORAGE_TYPES) {
893 final File typeDirectory =
894 new File(
895 Environment.getExternalStoragePublicDirectory(type),
896 context.getString(R.string.app_name));
897 if (typeDirectory.equals(fileDirectory)) {
898 return true;
899 }
900 }
901 return false;
902 }
903
904 public void setupRelativeFilePath(
905 final Message message, final String filename, final String mime) {
906 final File file = getStorageLocation(filename, mime);
907 message.setRelativeFilePath(file.getAbsolutePath());
908 }
909
910 public boolean unusualBounds(final Uri image) {
911 try {
912 final BitmapFactory.Options options = new BitmapFactory.Options();
913 options.inJustDecodeBounds = true;
914 final InputStream inputStream =
915 mXmppConnectionService.getContentResolver().openInputStream(image);
916 BitmapFactory.decodeStream(inputStream, null, options);
917 close(inputStream);
918 float ratio = (float) options.outHeight / options.outWidth;
919 return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
920 } catch (final Exception e) {
921 Log.w(Config.LOGTAG, "unable to detect image bounds", e);
922 return false;
923 }
924 }
925
926 private int getRotation(final File file) {
927 try (final InputStream inputStream = new FileInputStream(file)) {
928 return getRotation(inputStream);
929 } catch (Exception e) {
930 return 0;
931 }
932 }
933
934 private int getRotation(final Uri image) {
935 try (final InputStream is =
936 mXmppConnectionService.getContentResolver().openInputStream(image)) {
937 return is == null ? 0 : getRotation(is);
938 } catch (final Exception e) {
939 return 0;
940 }
941 }
942
943 private static int getRotation(final InputStream inputStream) throws IOException {
944 final ExifInterface exif = new ExifInterface(inputStream);
945 final int orientation =
946 exif.getAttributeInt(
947 ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
948 switch (orientation) {
949 case ExifInterface.ORIENTATION_ROTATE_180:
950 return 180;
951 case ExifInterface.ORIENTATION_ROTATE_90:
952 return 90;
953 case ExifInterface.ORIENTATION_ROTATE_270:
954 return 270;
955 default:
956 return 0;
957 }
958 }
959
960 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
961 final String uuid = message.getUuid();
962 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
963 Bitmap thumbnail = cache.get(uuid);
964 if ((thumbnail == null) && (!cacheOnly)) {
965 synchronized (THUMBNAIL_LOCK) {
966 thumbnail = cache.get(uuid);
967 if (thumbnail != null) {
968 return thumbnail;
969 }
970 DownloadableFile file = getFile(message);
971 final String mime = file.getMimeType();
972 if ("application/pdf".equals(mime)) {
973 thumbnail = getPdfDocumentPreview(file, size);
974 } else if (mime.startsWith("video/")) {
975 thumbnail = getVideoPreview(file, size);
976 } else {
977 final Bitmap fullSize = getFullSizeImagePreview(file, size);
978 if (fullSize == null) {
979 throw new FileNotFoundException();
980 }
981 thumbnail = resize(fullSize, size);
982 thumbnail = rotate(thumbnail, getRotation(file));
983 if (mime.equals("image/gif")) {
984 Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
985 drawOverlay(
986 withGifOverlay,
987 paintOverlayBlack(withGifOverlay)
988 ? R.drawable.play_gif_black
989 : R.drawable.play_gif_white,
990 1.0f);
991 thumbnail.recycle();
992 thumbnail = withGifOverlay;
993 }
994 }
995 cache.put(uuid, thumbnail);
996 }
997 }
998 return thumbnail;
999 }
1000
1001 private Bitmap getFullSizeImagePreview(File file, int size) {
1002 BitmapFactory.Options options = new BitmapFactory.Options();
1003 options.inSampleSize = calcSampleSize(file, size);
1004 try {
1005 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1006 } catch (OutOfMemoryError e) {
1007 options.inSampleSize *= 2;
1008 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1009 }
1010 }
1011
1012 private void drawOverlay(Bitmap bitmap, int resource, float factor) {
1013 Bitmap overlay =
1014 BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
1015 Canvas canvas = new Canvas(bitmap);
1016 float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
1017 Log.d(
1018 Config.LOGTAG,
1019 "target size overlay: "
1020 + targetSize
1021 + " overlay bitmap size was "
1022 + overlay.getHeight());
1023 float left = (canvas.getWidth() - targetSize) / 2.0f;
1024 float top = (canvas.getHeight() - targetSize) / 2.0f;
1025 RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
1026 canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
1027 }
1028
1029 /** https://stackoverflow.com/a/3943023/210897 */
1030 private boolean paintOverlayBlack(final Bitmap bitmap) {
1031 final int h = bitmap.getHeight();
1032 final int w = bitmap.getWidth();
1033 int record = 0;
1034 for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
1035 for (int x = Math.round(w * IGNORE_PADDING);
1036 x < w - Math.round(w * IGNORE_PADDING);
1037 ++x) {
1038 int pixel = bitmap.getPixel(x, y);
1039 if ((Color.red(pixel) * 0.299
1040 + Color.green(pixel) * 0.587
1041 + Color.blue(pixel) * 0.114)
1042 > 186) {
1043 --record;
1044 } else {
1045 ++record;
1046 }
1047 }
1048 }
1049 return record < 0;
1050 }
1051
1052 private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1053 final int h = bitmap.getHeight();
1054 final int w = bitmap.getWidth();
1055 int white = 0;
1056 for (int y = 0; y < h; ++y) {
1057 for (int x = 0; x < w; ++x) {
1058 int pixel = bitmap.getPixel(x, y);
1059 if ((Color.red(pixel) * 0.299
1060 + Color.green(pixel) * 0.587
1061 + Color.blue(pixel) * 0.114)
1062 > 186) {
1063 white++;
1064 }
1065 }
1066 }
1067 return white > (h * w * 0.4f);
1068 }
1069
1070 private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1071 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1072 Bitmap frame;
1073 try {
1074 metadataRetriever.setDataSource(mXmppConnectionService, uri);
1075 frame = metadataRetriever.getFrameAtTime(0);
1076 metadataRetriever.release();
1077 return cropCenterSquare(frame, size);
1078 } catch (Exception e) {
1079 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1080 frame.eraseColor(0xff000000);
1081 return frame;
1082 }
1083 }
1084
1085 private Bitmap getVideoPreview(final File file, final int size) {
1086 final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1087 Bitmap frame;
1088 try {
1089 metadataRetriever.setDataSource(file.getAbsolutePath());
1090 frame = metadataRetriever.getFrameAtTime(0);
1091 metadataRetriever.release();
1092 frame = resize(frame, size);
1093 } catch (IOException | RuntimeException e) {
1094 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1095 frame.eraseColor(0xff000000);
1096 }
1097 drawOverlay(
1098 frame,
1099 paintOverlayBlack(frame)
1100 ? R.drawable.play_video_black
1101 : R.drawable.play_video_white,
1102 0.75f);
1103 return frame;
1104 }
1105
1106 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1107 private Bitmap getPdfDocumentPreview(final File file, final int size) {
1108 try {
1109 final ParcelFileDescriptor fileDescriptor =
1110 ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1111 final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1112 drawOverlay(
1113 rendered,
1114 paintOverlayBlackPdf(rendered)
1115 ? R.drawable.open_pdf_black
1116 : R.drawable.open_pdf_white,
1117 0.75f);
1118 return rendered;
1119 } catch (final IOException | SecurityException e) {
1120 Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1121 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1122 placeholder.eraseColor(0xff000000);
1123 return placeholder;
1124 }
1125 }
1126
1127 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1128 private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1129 try {
1130 ParcelFileDescriptor fileDescriptor =
1131 mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1132 final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1133 return cropCenterSquare(bitmap, size);
1134 } catch (Exception e) {
1135 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1136 placeholder.eraseColor(0xff000000);
1137 return placeholder;
1138 }
1139 }
1140
1141 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1142 private Bitmap renderPdfDocument(
1143 ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1144 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1145 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1146 final Dimensions dimensions =
1147 scalePdfDimensions(
1148 new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1149 final Bitmap rendered =
1150 Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1151 rendered.eraseColor(0xffffffff);
1152 page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1153 page.close();
1154 pdfRenderer.close();
1155 fileDescriptor.close();
1156 return rendered;
1157 }
1158
1159 public Uri getTakePhotoUri() {
1160 final String filename =
1161 String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1162 final File directory;
1163 if (Config.ONLY_INTERNAL_STORAGE) {
1164 directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1165 } else {
1166 directory =
1167 new File(
1168 Environment.getExternalStoragePublicDirectory(
1169 Environment.DIRECTORY_DCIM),
1170 "Camera");
1171 }
1172 final File file = new File(directory, filename);
1173 file.getParentFile().mkdirs();
1174 return getUriForFile(mXmppConnectionService, file);
1175 }
1176
1177 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
1178
1179 final Avatar uncompressAvatar = getUncompressedAvatar(image);
1180 if (uncompressAvatar != null
1181 && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
1182 return uncompressAvatar;
1183 }
1184 if (uncompressAvatar != null) {
1185 Log.d(
1186 Config.LOGTAG,
1187 "uncompressed avatar exceeded char limit by "
1188 + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
1189 }
1190
1191 Bitmap bm = cropCenterSquare(image, size);
1192 if (bm == null) {
1193 return null;
1194 }
1195 if (hasAlpha(bm)) {
1196 Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1197 bm.recycle();
1198 bm = cropCenterSquare(image, 96);
1199 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1200 }
1201 return getPepAvatar(bm, format, 100);
1202 }
1203
1204 private Avatar getUncompressedAvatar(Uri uri) {
1205 Bitmap bitmap = null;
1206 try {
1207 bitmap =
1208 BitmapFactory.decodeStream(
1209 mXmppConnectionService.getContentResolver().openInputStream(uri));
1210 return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
1211 } catch (Exception e) {
1212 return null;
1213 } finally {
1214 if (bitmap != null) {
1215 bitmap.recycle();
1216 }
1217 }
1218 }
1219
1220 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1221 try {
1222 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1223 Base64OutputStream mBase64OutputStream =
1224 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1225 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1226 DigestOutputStream mDigestOutputStream =
1227 new DigestOutputStream(mBase64OutputStream, digest);
1228 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1229 return null;
1230 }
1231 mDigestOutputStream.flush();
1232 mDigestOutputStream.close();
1233 long chars = mByteArrayOutputStream.size();
1234 if (format != Bitmap.CompressFormat.PNG
1235 && quality >= 50
1236 && chars >= Config.AVATAR_CHAR_LIMIT) {
1237 int q = quality - 2;
1238 Log.d(
1239 Config.LOGTAG,
1240 "avatar char length was " + chars + " reducing quality to " + q);
1241 return getPepAvatar(bitmap, format, q);
1242 }
1243 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1244 final Avatar avatar = new Avatar();
1245 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1246 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1247 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1248 avatar.type = "image/webp";
1249 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1250 avatar.type = "image/jpeg";
1251 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1252 avatar.type = "image/png";
1253 }
1254 avatar.width = bitmap.getWidth();
1255 avatar.height = bitmap.getHeight();
1256 return avatar;
1257 } catch (OutOfMemoryError e) {
1258 Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1259 return null;
1260 } catch (Exception e) {
1261 return null;
1262 }
1263 }
1264
1265 public Avatar getStoredPepAvatar(String hash) {
1266 if (hash == null) {
1267 return null;
1268 }
1269 Avatar avatar = new Avatar();
1270 final File file = getAvatarFile(hash);
1271 FileInputStream is = null;
1272 try {
1273 avatar.size = file.length();
1274 BitmapFactory.Options options = new BitmapFactory.Options();
1275 options.inJustDecodeBounds = true;
1276 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1277 is = new FileInputStream(file);
1278 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1279 Base64OutputStream mBase64OutputStream =
1280 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1281 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1282 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1283 byte[] buffer = new byte[4096];
1284 int length;
1285 while ((length = is.read(buffer)) > 0) {
1286 os.write(buffer, 0, length);
1287 }
1288 os.flush();
1289 os.close();
1290 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1291 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1292 avatar.height = options.outHeight;
1293 avatar.width = options.outWidth;
1294 avatar.type = options.outMimeType;
1295 return avatar;
1296 } catch (NoSuchAlgorithmException | IOException e) {
1297 return null;
1298 } finally {
1299 close(is);
1300 }
1301 }
1302
1303 public boolean isAvatarCached(Avatar avatar) {
1304 final File file = getAvatarFile(avatar.getFilename());
1305 return file.exists();
1306 }
1307
1308 public boolean save(final Avatar avatar) {
1309 File file;
1310 if (isAvatarCached(avatar)) {
1311 file = getAvatarFile(avatar.getFilename());
1312 avatar.size = file.length();
1313 } else {
1314 file =
1315 new File(
1316 mXmppConnectionService.getCacheDir().getAbsolutePath()
1317 + "/"
1318 + UUID.randomUUID().toString());
1319 if (file.getParentFile().mkdirs()) {
1320 Log.d(Config.LOGTAG, "created cache directory");
1321 }
1322 OutputStream os = null;
1323 try {
1324 if (!file.createNewFile()) {
1325 Log.d(
1326 Config.LOGTAG,
1327 "unable to create temporary file " + file.getAbsolutePath());
1328 }
1329 os = new FileOutputStream(file);
1330 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1331 digest.reset();
1332 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1333 final byte[] bytes = avatar.getImageAsBytes();
1334 mDigestOutputStream.write(bytes);
1335 mDigestOutputStream.flush();
1336 mDigestOutputStream.close();
1337 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1338 if (sha1sum.equals(avatar.sha1sum)) {
1339 final File outputFile = getAvatarFile(avatar.getFilename());
1340 if (outputFile.getParentFile().mkdirs()) {
1341 Log.d(Config.LOGTAG, "created avatar directory");
1342 }
1343 final File avatarFile = getAvatarFile(avatar.getFilename());
1344 if (!file.renameTo(avatarFile)) {
1345 Log.d(
1346 Config.LOGTAG,
1347 "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1348 return false;
1349 }
1350 } else {
1351 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1352 if (!file.delete()) {
1353 Log.d(Config.LOGTAG, "unable to delete temporary file");
1354 }
1355 return false;
1356 }
1357 avatar.size = bytes.length;
1358 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1359 return false;
1360 } finally {
1361 close(os);
1362 }
1363 }
1364 return true;
1365 }
1366
1367 public void deleteHistoricAvatarPath() {
1368 delete(getHistoricAvatarPath());
1369 }
1370
1371 private void delete(final File file) {
1372 if (file.isDirectory()) {
1373 final File[] files = file.listFiles();
1374 if (files != null) {
1375 for (final File f : files) {
1376 delete(f);
1377 }
1378 }
1379 }
1380 if (file.delete()) {
1381 Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1382 }
1383 }
1384
1385 private File getHistoricAvatarPath() {
1386 return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1387 }
1388
1389 private File getAvatarFile(String avatar) {
1390 return new File(mXmppConnectionService.getCacheDir(), "/avatars/" + avatar);
1391 }
1392
1393 public Uri getAvatarUri(String avatar) {
1394 return Uri.fromFile(getAvatarFile(avatar));
1395 }
1396
1397 public Bitmap cropCenterSquare(Uri image, int size) {
1398 if (image == null) {
1399 return null;
1400 }
1401 InputStream is = null;
1402 try {
1403 BitmapFactory.Options options = new BitmapFactory.Options();
1404 options.inSampleSize = calcSampleSize(image, size);
1405 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1406 if (is == null) {
1407 return null;
1408 }
1409 Bitmap input = BitmapFactory.decodeStream(is, null, options);
1410 if (input == null) {
1411 return null;
1412 } else {
1413 input = rotate(input, getRotation(image));
1414 return cropCenterSquare(input, size);
1415 }
1416 } catch (FileNotFoundException | SecurityException e) {
1417 Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1418 return null;
1419 } finally {
1420 close(is);
1421 }
1422 }
1423
1424 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1425 if (image == null) {
1426 return null;
1427 }
1428 InputStream is = null;
1429 try {
1430 BitmapFactory.Options options = new BitmapFactory.Options();
1431 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1432 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1433 if (is == null) {
1434 return null;
1435 }
1436 Bitmap source = BitmapFactory.decodeStream(is, null, options);
1437 if (source == null) {
1438 return null;
1439 }
1440 int sourceWidth = source.getWidth();
1441 int sourceHeight = source.getHeight();
1442 float xScale = (float) newWidth / sourceWidth;
1443 float yScale = (float) newHeight / sourceHeight;
1444 float scale = Math.max(xScale, yScale);
1445 float scaledWidth = scale * sourceWidth;
1446 float scaledHeight = scale * sourceHeight;
1447 float left = (newWidth - scaledWidth) / 2;
1448 float top = (newHeight - scaledHeight) / 2;
1449
1450 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1451 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1452 Canvas canvas = new Canvas(dest);
1453 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1454 if (source.isRecycled()) {
1455 source.recycle();
1456 }
1457 return dest;
1458 } catch (SecurityException e) {
1459 return null; // android 6.0 with revoked permissions for example
1460 } catch (FileNotFoundException e) {
1461 return null;
1462 } finally {
1463 close(is);
1464 }
1465 }
1466
1467 public Bitmap cropCenterSquare(Bitmap input, int size) {
1468 int w = input.getWidth();
1469 int h = input.getHeight();
1470
1471 float scale = Math.max((float) size / h, (float) size / w);
1472
1473 float outWidth = scale * w;
1474 float outHeight = scale * h;
1475 float left = (size - outWidth) / 2;
1476 float top = (size - outHeight) / 2;
1477 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1478
1479 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1480 Canvas canvas = new Canvas(output);
1481 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1482 if (!input.isRecycled()) {
1483 input.recycle();
1484 }
1485 return output;
1486 }
1487
1488 private int calcSampleSize(Uri image, int size)
1489 throws FileNotFoundException, SecurityException {
1490 final BitmapFactory.Options options = new BitmapFactory.Options();
1491 options.inJustDecodeBounds = true;
1492 final InputStream inputStream =
1493 mXmppConnectionService.getContentResolver().openInputStream(image);
1494 BitmapFactory.decodeStream(inputStream, null, options);
1495 close(inputStream);
1496 return calcSampleSize(options, size);
1497 }
1498
1499 public void updateFileParams(Message message) {
1500 updateFileParams(message, null);
1501 }
1502
1503 public void updateFileParams(final Message message, final String url) {
1504 final boolean encrypted =
1505 message.getEncryption() == Message.ENCRYPTION_PGP
1506 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED;
1507 final DownloadableFile file = getFile(message);
1508 final String mime = file.getMimeType();
1509 final boolean image =
1510 message.getType() == Message.TYPE_IMAGE
1511 || (mime != null && mime.startsWith("image/"));
1512 final boolean privateMessage = message.isPrivateMessage();
1513 final StringBuilder body = new StringBuilder();
1514 if (url != null) {
1515 body.append(url);
1516 }
1517 if (encrypted && !file.exists()) {
1518 Log.d(Config.LOGTAG, "skipping updateFileParams because file is encrypted");
1519 final DownloadableFile encryptedFile = getFile(message, false);
1520 body.append('|').append(encryptedFile.getSize());
1521 } else {
1522 Log.d(Config.LOGTAG, "running updateFileParams");
1523 final boolean ambiguous = MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime);
1524 final boolean video = mime != null && mime.startsWith("video/");
1525 final boolean audio = mime != null && mime.startsWith("audio/");
1526 final boolean pdf = "application/pdf".equals(mime);
1527 body.append('|').append(file.getSize());
1528 if (ambiguous) {
1529 try {
1530 final Dimensions dimensions = getVideoDimensions(file);
1531 if (dimensions.valid()) {
1532 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is video");
1533 body.append('|')
1534 .append(dimensions.width)
1535 .append('|')
1536 .append(dimensions.height);
1537 } else {
1538 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1539 body.append("|0|0|").append(getMediaRuntime(file));
1540 }
1541 } catch (final IOException | NotAVideoFile e) {
1542 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1543 body.append("|0|0|").append(getMediaRuntime(file));
1544 }
1545 } else if (image || video || pdf) {
1546 try {
1547 final Dimensions dimensions;
1548 if (video) {
1549 dimensions = getVideoDimensions(file);
1550 } else if (pdf) {
1551 dimensions = getPdfDocumentDimensions(file);
1552 } else {
1553 dimensions = getImageDimensions(file);
1554 }
1555 if (dimensions.valid()) {
1556 body.append('|')
1557 .append(dimensions.width)
1558 .append('|')
1559 .append(dimensions.height);
1560 }
1561 } catch (final IOException | NotAVideoFile notAVideoFile) {
1562 Log.d(
1563 Config.LOGTAG,
1564 "file with mime type " + file.getMimeType() + " was not a video file");
1565 // fall threw
1566 }
1567 } else if (audio) {
1568 body.append("|0|0|").append(getMediaRuntime(file));
1569 }
1570 }
1571 message.setBody(body.toString());
1572 message.setDeleted(false);
1573 message.setType(
1574 privateMessage
1575 ? Message.TYPE_PRIVATE_FILE
1576 : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1577 }
1578
1579 private int getMediaRuntime(final File file) {
1580 try {
1581 final MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1582 mediaMetadataRetriever.setDataSource(file.toString());
1583 final String value =
1584 mediaMetadataRetriever.extractMetadata(
1585 MediaMetadataRetriever.METADATA_KEY_DURATION);
1586 if (Strings.isNullOrEmpty(value)) {
1587 return 0;
1588 }
1589 return Integer.parseInt(value);
1590 } catch (final Exception e) {
1591 return 0;
1592 }
1593 }
1594
1595 private Dimensions getImageDimensions(File file) {
1596 final BitmapFactory.Options options = new BitmapFactory.Options();
1597 options.inJustDecodeBounds = true;
1598 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1599 final int rotation = getRotation(file);
1600 final boolean rotated = rotation == 90 || rotation == 270;
1601 final int imageHeight = rotated ? options.outWidth : options.outHeight;
1602 final int imageWidth = rotated ? options.outHeight : options.outWidth;
1603 return new Dimensions(imageHeight, imageWidth);
1604 }
1605
1606 private Dimensions getVideoDimensions(final File file) throws NotAVideoFile, IOException {
1607 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1608 try {
1609 metadataRetriever.setDataSource(file.getAbsolutePath());
1610 } catch (RuntimeException e) {
1611 throw new NotAVideoFile(e);
1612 }
1613 return getVideoDimensions(metadataRetriever);
1614 }
1615
1616 private Dimensions getPdfDocumentDimensions(final File file) {
1617 final ParcelFileDescriptor fileDescriptor;
1618 try {
1619 fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1620 if (fileDescriptor == null) {
1621 return new Dimensions(0, 0);
1622 }
1623 } catch (final FileNotFoundException e) {
1624 return new Dimensions(0, 0);
1625 }
1626 try {
1627 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1628 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1629 final int height = page.getHeight();
1630 final int width = page.getWidth();
1631 page.close();
1632 pdfRenderer.close();
1633 return scalePdfDimensions(new Dimensions(height, width));
1634 } catch (final IOException | SecurityException e) {
1635 Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1636 return new Dimensions(0, 0);
1637 }
1638 }
1639
1640 private Dimensions scalePdfDimensions(Dimensions in) {
1641 final DisplayMetrics displayMetrics =
1642 mXmppConnectionService.getResources().getDisplayMetrics();
1643 final int target = (int) (displayMetrics.density * 288);
1644 return scalePdfDimensions(in, target, true);
1645 }
1646
1647 private static Dimensions scalePdfDimensions(
1648 final Dimensions in, final int target, final boolean fit) {
1649 final int w, h;
1650 if (fit == (in.width <= in.height)) {
1651 w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1652 h = target;
1653 } else {
1654 w = target;
1655 h = Math.max((int) (in.height / ((double) in.width / target)), 1);
1656 }
1657 return new Dimensions(h, w);
1658 }
1659
1660 public Bitmap getAvatar(String avatar, int size) {
1661 if (avatar == null) {
1662 return null;
1663 }
1664 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1665 return bm;
1666 }
1667
1668 private static class Dimensions {
1669 public final int width;
1670 public final int height;
1671
1672 Dimensions(int height, int width) {
1673 this.width = width;
1674 this.height = height;
1675 }
1676
1677 public int getMin() {
1678 return Math.min(width, height);
1679 }
1680
1681 public boolean valid() {
1682 return width > 0 && height > 0;
1683 }
1684 }
1685
1686 private static class NotAVideoFile extends Exception {
1687 public NotAVideoFile(Throwable t) {
1688 super(t);
1689 }
1690
1691 public NotAVideoFile() {
1692 super();
1693 }
1694 }
1695
1696 public static class ImageCompressionException extends Exception {
1697
1698 ImageCompressionException(String message) {
1699 super(message);
1700 }
1701 }
1702
1703 public static class FileCopyException extends Exception {
1704 private final int resId;
1705
1706 private FileCopyException(@StringRes int resId) {
1707 this.resId = resId;
1708 }
1709
1710 public @StringRes int getResId() {
1711 return resId;
1712 }
1713 }
1714}