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 eu.siacs.conversations.Config;
40import eu.siacs.conversations.R;
41import eu.siacs.conversations.entities.DownloadableFile;
42import eu.siacs.conversations.entities.Message;
43import eu.siacs.conversations.services.AttachFileToConversationRunnable;
44import eu.siacs.conversations.services.XmppConnectionService;
45import eu.siacs.conversations.ui.adapter.MediaAdapter;
46import eu.siacs.conversations.ui.util.Attachment;
47import eu.siacs.conversations.utils.CryptoHelper;
48import eu.siacs.conversations.utils.FileUtils;
49import eu.siacs.conversations.utils.FileWriterException;
50import eu.siacs.conversations.utils.MimeUtils;
51import eu.siacs.conversations.xmpp.pep.Avatar;
52
53import java.io.ByteArrayOutputStream;
54import java.io.Closeable;
55import java.io.File;
56import java.io.FileDescriptor;
57import java.io.FileInputStream;
58import java.io.FileNotFoundException;
59import java.io.FileOutputStream;
60import java.io.IOException;
61import java.io.InputStream;
62import java.io.OutputStream;
63import java.net.ServerSocket;
64import java.net.Socket;
65import java.security.DigestOutputStream;
66import java.security.MessageDigest;
67import java.security.NoSuchAlgorithmException;
68import java.text.SimpleDateFormat;
69import java.util.ArrayList;
70import java.util.Date;
71import java.util.List;
72import java.util.Locale;
73import java.util.UUID;
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 final var parentDirectory = file.getParentFile();
668 if (parentDirectory != null && parentDirectory.mkdirs()) {
669 Log.d(Config.LOGTAG,"created directory "+parentDirectory.getAbsolutePath());
670 }
671 try {
672 if (file.createNewFile()) {
673 Log.d(
674 Config.LOGTAG,
675 "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
676 }
677 } catch (final IOException e) {
678 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
679 }
680 try (final OutputStream os = new FileOutputStream(file);
681 final InputStream is =
682 mXmppConnectionService.getContentResolver().openInputStream(uri)) {
683 if (is == null) {
684 throw new FileCopyException(R.string.error_file_not_found);
685 }
686 try {
687 ByteStreams.copy(is, os);
688 } catch (final IOException e) {
689 throw new FileWriterException(file);
690 }
691 try {
692 os.flush();
693 } catch (final IOException e) {
694 throw new FileWriterException(file);
695 }
696 } catch (final FileNotFoundException e) {
697 cleanup(file);
698 throw new FileCopyException(R.string.error_file_not_found);
699 } catch (final FileWriterException e) {
700 cleanup(file);
701 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
702 } catch (final SecurityException | IllegalStateException | IllegalArgumentException e) {
703 cleanup(file);
704 throw new FileCopyException(R.string.error_security_exception);
705 } catch (final IOException e) {
706 cleanup(file);
707 throw new FileCopyException(R.string.error_io_exception);
708 }
709 }
710
711 public void copyFileToPrivateStorage(Message message, Uri uri, String type)
712 throws FileCopyException {
713 final String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
714 Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
715 String extension = MimeUtils.guessExtensionFromMimeType(mime);
716 if (extension == null) {
717 Log.d(Config.LOGTAG, "extension from mime type was null");
718 extension = getExtensionFromUri(uri);
719 }
720 if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
721 extension = "oga";
722 }
723 setupRelativeFilePath(message, String.format("%s.%s", message.getUuid(), extension));
724 copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
725 }
726
727 private String getExtensionFromUri(final Uri uri) {
728 final String[] projection = {MediaStore.MediaColumns.DATA};
729 String filename = null;
730 try (final Cursor cursor =
731 mXmppConnectionService
732 .getContentResolver()
733 .query(uri, projection, null, null, null)) {
734 if (cursor != null && cursor.moveToFirst()) {
735 filename = cursor.getString(0);
736 }
737 } catch (final Exception e) {
738 filename = null;
739 }
740 if (filename == null) {
741 final List<String> segments = uri.getPathSegments();
742 if (segments.size() > 0) {
743 filename = segments.get(segments.size() - 1);
744 }
745 }
746 final int pos = filename == null ? -1 : filename.lastIndexOf('.');
747 return pos > 0 ? filename.substring(pos + 1) : null;
748 }
749
750 private void copyImageToPrivateStorage(File file, Uri image, int sampleSize)
751 throws FileCopyException, ImageCompressionException {
752 final File parent = file.getParentFile();
753 if (parent != null && parent.mkdirs()) {
754 Log.d(Config.LOGTAG, "created parent directory");
755 }
756 InputStream is = null;
757 OutputStream os = null;
758 try {
759 if (!file.exists() && !file.createNewFile()) {
760 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
761 }
762 is = mXmppConnectionService.getContentResolver().openInputStream(image);
763 if (is == null) {
764 throw new FileCopyException(R.string.error_not_an_image_file);
765 }
766 final Bitmap originalBitmap;
767 final BitmapFactory.Options options = new BitmapFactory.Options();
768 final int inSampleSize = (int) Math.pow(2, sampleSize);
769 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
770 options.inSampleSize = inSampleSize;
771 originalBitmap = BitmapFactory.decodeStream(is, null, options);
772 is.close();
773 if (originalBitmap == null) {
774 throw new ImageCompressionException("Source file was not an image");
775 }
776 if (!"image/jpeg".equals(options.outMimeType) && hasAlpha(originalBitmap)) {
777 originalBitmap.recycle();
778 throw new ImageCompressionException("Source file had alpha channel");
779 }
780 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
781 final int rotation = getRotation(image);
782 scaledBitmap = rotate(scaledBitmap, rotation);
783 boolean targetSizeReached = false;
784 int quality = Config.IMAGE_QUALITY;
785 final int imageMaxSize =
786 mXmppConnectionService
787 .getResources()
788 .getInteger(R.integer.auto_accept_filesize);
789 while (!targetSizeReached) {
790 os = new FileOutputStream(file);
791 Log.d(Config.LOGTAG, "compressing image with quality " + quality);
792 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
793 if (!success) {
794 throw new FileCopyException(R.string.error_compressing_image);
795 }
796 os.flush();
797 final long fileSize = file.length();
798 Log.d(Config.LOGTAG, "achieved file size of " + fileSize);
799 targetSizeReached = fileSize <= imageMaxSize || quality <= 50;
800 quality -= 5;
801 }
802 scaledBitmap.recycle();
803 } catch (final FileNotFoundException e) {
804 cleanup(file);
805 throw new FileCopyException(R.string.error_file_not_found);
806 } catch (final IOException e) {
807 cleanup(file);
808 throw new FileCopyException(R.string.error_io_exception);
809 } catch (SecurityException e) {
810 cleanup(file);
811 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
812 } catch (final OutOfMemoryError e) {
813 ++sampleSize;
814 if (sampleSize <= 3) {
815 copyImageToPrivateStorage(file, image, sampleSize);
816 } else {
817 throw new FileCopyException(R.string.error_out_of_memory);
818 }
819 } finally {
820 close(os);
821 close(is);
822 }
823 }
824
825 private static void cleanup(final File file) {
826 try {
827 file.delete();
828 } catch (Exception e) {
829
830 }
831 }
832
833 public void copyImageToPrivateStorage(File file, Uri image)
834 throws FileCopyException, ImageCompressionException {
835 Log.d(
836 Config.LOGTAG,
837 "copy image ("
838 + image.toString()
839 + ") to private storage "
840 + file.getAbsolutePath());
841 copyImageToPrivateStorage(file, image, 0);
842 }
843
844 public void copyImageToPrivateStorage(Message message, Uri image)
845 throws FileCopyException, ImageCompressionException {
846 final String filename;
847 switch (Config.IMAGE_FORMAT) {
848 case JPEG:
849 filename = String.format("%s.%s", message.getUuid(), "jpg");
850 break;
851 case PNG:
852 filename = String.format("%s.%s", message.getUuid(), "png");
853 break;
854 case WEBP:
855 filename = String.format("%s.%s", message.getUuid(), "webp");
856 break;
857 default:
858 throw new IllegalStateException("Unknown image format");
859 }
860 setupRelativeFilePath(message, filename);
861 copyImageToPrivateStorage(getFile(message), image);
862 updateFileParams(message);
863 }
864
865 public void setupRelativeFilePath(final Message message, final String filename) {
866 final String extension = MimeUtils.extractRelevantExtension(filename);
867 final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
868 setupRelativeFilePath(message, filename, mime);
869 }
870
871 public File getStorageLocation(final String filename, final String mime) {
872 final File parentDirectory;
873 if (Strings.isNullOrEmpty(mime)) {
874 parentDirectory =
875 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
876 } else if (mime.startsWith("image/")) {
877 parentDirectory =
878 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
879 } else if (mime.startsWith("video/")) {
880 parentDirectory =
881 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
882 } else if (MediaAdapter.DOCUMENT_MIMES.contains(mime)) {
883 parentDirectory =
884 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
885 } else {
886 parentDirectory =
887 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
888 }
889 final File appDirectory =
890 new File(parentDirectory, mXmppConnectionService.getString(R.string.app_name));
891 return new File(appDirectory, filename);
892 }
893
894 public static boolean inConversationsDirectory(final Context context, String path) {
895 final File fileDirectory = new File(path).getParentFile();
896 for (final String type : STORAGE_TYPES) {
897 final File typeDirectory =
898 new File(
899 Environment.getExternalStoragePublicDirectory(type),
900 context.getString(R.string.app_name));
901 if (typeDirectory.equals(fileDirectory)) {
902 return true;
903 }
904 }
905 return false;
906 }
907
908 public void setupRelativeFilePath(
909 final Message message, final String filename, final String mime) {
910 final File file = getStorageLocation(filename, mime);
911 message.setRelativeFilePath(file.getAbsolutePath());
912 }
913
914 public boolean unusualBounds(final Uri image) {
915 try {
916 final BitmapFactory.Options options = new BitmapFactory.Options();
917 options.inJustDecodeBounds = true;
918 final InputStream inputStream =
919 mXmppConnectionService.getContentResolver().openInputStream(image);
920 BitmapFactory.decodeStream(inputStream, null, options);
921 close(inputStream);
922 float ratio = (float) options.outHeight / options.outWidth;
923 return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
924 } catch (final Exception e) {
925 Log.w(Config.LOGTAG, "unable to detect image bounds", e);
926 return false;
927 }
928 }
929
930 private int getRotation(final File file) {
931 try (final InputStream inputStream = new FileInputStream(file)) {
932 return getRotation(inputStream);
933 } catch (Exception e) {
934 return 0;
935 }
936 }
937
938 private int getRotation(final Uri image) {
939 try (final InputStream is =
940 mXmppConnectionService.getContentResolver().openInputStream(image)) {
941 return is == null ? 0 : getRotation(is);
942 } catch (final Exception e) {
943 return 0;
944 }
945 }
946
947 private static int getRotation(final InputStream inputStream) throws IOException {
948 final ExifInterface exif = new ExifInterface(inputStream);
949 final int orientation =
950 exif.getAttributeInt(
951 ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
952 switch (orientation) {
953 case ExifInterface.ORIENTATION_ROTATE_180:
954 return 180;
955 case ExifInterface.ORIENTATION_ROTATE_90:
956 return 90;
957 case ExifInterface.ORIENTATION_ROTATE_270:
958 return 270;
959 default:
960 return 0;
961 }
962 }
963
964 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
965 final String uuid = message.getUuid();
966 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
967 Bitmap thumbnail = cache.get(uuid);
968 if ((thumbnail == null) && (!cacheOnly)) {
969 synchronized (THUMBNAIL_LOCK) {
970 thumbnail = cache.get(uuid);
971 if (thumbnail != null) {
972 return thumbnail;
973 }
974 DownloadableFile file = getFile(message);
975 final String mime = file.getMimeType();
976 if ("application/pdf".equals(mime)) {
977 thumbnail = getPdfDocumentPreview(file, size);
978 } else if (mime.startsWith("video/")) {
979 thumbnail = getVideoPreview(file, size);
980 } else {
981 final Bitmap fullSize = getFullSizeImagePreview(file, size);
982 if (fullSize == null) {
983 throw new FileNotFoundException();
984 }
985 thumbnail = resize(fullSize, size);
986 thumbnail = rotate(thumbnail, getRotation(file));
987 if (mime.equals("image/gif")) {
988 Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
989 drawOverlay(
990 withGifOverlay,
991 paintOverlayBlack(withGifOverlay)
992 ? R.drawable.play_gif_black
993 : R.drawable.play_gif_white,
994 1.0f);
995 thumbnail.recycle();
996 thumbnail = withGifOverlay;
997 }
998 }
999 cache.put(uuid, thumbnail);
1000 }
1001 }
1002 return thumbnail;
1003 }
1004
1005 private Bitmap getFullSizeImagePreview(File file, int size) {
1006 BitmapFactory.Options options = new BitmapFactory.Options();
1007 options.inSampleSize = calcSampleSize(file, size);
1008 try {
1009 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1010 } catch (OutOfMemoryError e) {
1011 options.inSampleSize *= 2;
1012 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1013 }
1014 }
1015
1016 private void drawOverlay(Bitmap bitmap, int resource, float factor) {
1017 Bitmap overlay =
1018 BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
1019 Canvas canvas = new Canvas(bitmap);
1020 float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
1021 Log.d(
1022 Config.LOGTAG,
1023 "target size overlay: "
1024 + targetSize
1025 + " overlay bitmap size was "
1026 + overlay.getHeight());
1027 float left = (canvas.getWidth() - targetSize) / 2.0f;
1028 float top = (canvas.getHeight() - targetSize) / 2.0f;
1029 RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
1030 canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
1031 }
1032
1033 /** https://stackoverflow.com/a/3943023/210897 */
1034 private boolean paintOverlayBlack(final Bitmap bitmap) {
1035 final int h = bitmap.getHeight();
1036 final int w = bitmap.getWidth();
1037 int record = 0;
1038 for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
1039 for (int x = Math.round(w * IGNORE_PADDING);
1040 x < w - Math.round(w * IGNORE_PADDING);
1041 ++x) {
1042 int pixel = bitmap.getPixel(x, y);
1043 if ((Color.red(pixel) * 0.299
1044 + Color.green(pixel) * 0.587
1045 + Color.blue(pixel) * 0.114)
1046 > 186) {
1047 --record;
1048 } else {
1049 ++record;
1050 }
1051 }
1052 }
1053 return record < 0;
1054 }
1055
1056 private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1057 final int h = bitmap.getHeight();
1058 final int w = bitmap.getWidth();
1059 int white = 0;
1060 for (int y = 0; y < h; ++y) {
1061 for (int x = 0; x < w; ++x) {
1062 int pixel = bitmap.getPixel(x, y);
1063 if ((Color.red(pixel) * 0.299
1064 + Color.green(pixel) * 0.587
1065 + Color.blue(pixel) * 0.114)
1066 > 186) {
1067 white++;
1068 }
1069 }
1070 }
1071 return white > (h * w * 0.4f);
1072 }
1073
1074 private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1075 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1076 Bitmap frame;
1077 try {
1078 metadataRetriever.setDataSource(mXmppConnectionService, uri);
1079 frame = metadataRetriever.getFrameAtTime(0);
1080 metadataRetriever.release();
1081 return cropCenterSquare(frame, size);
1082 } catch (Exception e) {
1083 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1084 frame.eraseColor(0xff000000);
1085 return frame;
1086 }
1087 }
1088
1089 private Bitmap getVideoPreview(final File file, final int size) {
1090 final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1091 Bitmap frame;
1092 try {
1093 metadataRetriever.setDataSource(file.getAbsolutePath());
1094 frame = metadataRetriever.getFrameAtTime(0);
1095 metadataRetriever.release();
1096 frame = resize(frame, size);
1097 } catch (IOException | RuntimeException e) {
1098 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1099 frame.eraseColor(0xff000000);
1100 }
1101 drawOverlay(
1102 frame,
1103 paintOverlayBlack(frame)
1104 ? R.drawable.play_video_black
1105 : R.drawable.play_video_white,
1106 0.75f);
1107 return frame;
1108 }
1109
1110 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1111 private Bitmap getPdfDocumentPreview(final File file, final int size) {
1112 try {
1113 final ParcelFileDescriptor fileDescriptor =
1114 ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1115 final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1116 drawOverlay(
1117 rendered,
1118 paintOverlayBlackPdf(rendered)
1119 ? R.drawable.open_pdf_black
1120 : R.drawable.open_pdf_white,
1121 0.75f);
1122 return rendered;
1123 } catch (final IOException | SecurityException e) {
1124 Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1125 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1126 placeholder.eraseColor(0xff000000);
1127 return placeholder;
1128 }
1129 }
1130
1131 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1132 private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1133 try {
1134 ParcelFileDescriptor fileDescriptor =
1135 mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1136 final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1137 return cropCenterSquare(bitmap, size);
1138 } catch (Exception e) {
1139 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1140 placeholder.eraseColor(0xff000000);
1141 return placeholder;
1142 }
1143 }
1144
1145 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1146 private Bitmap renderPdfDocument(
1147 ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1148 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1149 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1150 final Dimensions dimensions =
1151 scalePdfDimensions(
1152 new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1153 final Bitmap rendered =
1154 Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1155 rendered.eraseColor(0xffffffff);
1156 page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1157 page.close();
1158 pdfRenderer.close();
1159 fileDescriptor.close();
1160 return rendered;
1161 }
1162
1163 public Uri getTakePhotoUri() {
1164 final String filename =
1165 String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1166 final File directory;
1167 if (Config.ONLY_INTERNAL_STORAGE) {
1168 directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1169 } else {
1170 directory =
1171 new File(
1172 Environment.getExternalStoragePublicDirectory(
1173 Environment.DIRECTORY_DCIM),
1174 "Camera");
1175 }
1176 final File file = new File(directory, filename);
1177 file.getParentFile().mkdirs();
1178 return getUriForFile(mXmppConnectionService, file);
1179 }
1180
1181 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
1182
1183 final Avatar uncompressAvatar = getUncompressedAvatar(image);
1184 if (uncompressAvatar != null
1185 && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
1186 return uncompressAvatar;
1187 }
1188 if (uncompressAvatar != null) {
1189 Log.d(
1190 Config.LOGTAG,
1191 "uncompressed avatar exceeded char limit by "
1192 + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
1193 }
1194
1195 Bitmap bm = cropCenterSquare(image, size);
1196 if (bm == null) {
1197 return null;
1198 }
1199 if (hasAlpha(bm)) {
1200 Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1201 bm.recycle();
1202 bm = cropCenterSquare(image, 96);
1203 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1204 }
1205 return getPepAvatar(bm, format, 100);
1206 }
1207
1208 private Avatar getUncompressedAvatar(Uri uri) {
1209 Bitmap bitmap = null;
1210 try {
1211 bitmap =
1212 BitmapFactory.decodeStream(
1213 mXmppConnectionService.getContentResolver().openInputStream(uri));
1214 return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
1215 } catch (Exception e) {
1216 return null;
1217 } finally {
1218 if (bitmap != null) {
1219 bitmap.recycle();
1220 }
1221 }
1222 }
1223
1224 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1225 try {
1226 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1227 Base64OutputStream mBase64OutputStream =
1228 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1229 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1230 DigestOutputStream mDigestOutputStream =
1231 new DigestOutputStream(mBase64OutputStream, digest);
1232 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1233 return null;
1234 }
1235 mDigestOutputStream.flush();
1236 mDigestOutputStream.close();
1237 long chars = mByteArrayOutputStream.size();
1238 if (format != Bitmap.CompressFormat.PNG
1239 && quality >= 50
1240 && chars >= Config.AVATAR_CHAR_LIMIT) {
1241 int q = quality - 2;
1242 Log.d(
1243 Config.LOGTAG,
1244 "avatar char length was " + chars + " reducing quality to " + q);
1245 return getPepAvatar(bitmap, format, q);
1246 }
1247 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1248 final Avatar avatar = new Avatar();
1249 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1250 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1251 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1252 avatar.type = "image/webp";
1253 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1254 avatar.type = "image/jpeg";
1255 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1256 avatar.type = "image/png";
1257 }
1258 avatar.width = bitmap.getWidth();
1259 avatar.height = bitmap.getHeight();
1260 return avatar;
1261 } catch (OutOfMemoryError e) {
1262 Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1263 return null;
1264 } catch (Exception e) {
1265 return null;
1266 }
1267 }
1268
1269 public Avatar getStoredPepAvatar(String hash) {
1270 if (hash == null) {
1271 return null;
1272 }
1273 Avatar avatar = new Avatar();
1274 final File file = getAvatarFile(hash);
1275 FileInputStream is = null;
1276 try {
1277 avatar.size = file.length();
1278 BitmapFactory.Options options = new BitmapFactory.Options();
1279 options.inJustDecodeBounds = true;
1280 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1281 is = new FileInputStream(file);
1282 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1283 Base64OutputStream mBase64OutputStream =
1284 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1285 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1286 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1287 byte[] buffer = new byte[4096];
1288 int length;
1289 while ((length = is.read(buffer)) > 0) {
1290 os.write(buffer, 0, length);
1291 }
1292 os.flush();
1293 os.close();
1294 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1295 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1296 avatar.height = options.outHeight;
1297 avatar.width = options.outWidth;
1298 avatar.type = options.outMimeType;
1299 return avatar;
1300 } catch (NoSuchAlgorithmException | IOException e) {
1301 return null;
1302 } finally {
1303 close(is);
1304 }
1305 }
1306
1307 public boolean isAvatarCached(Avatar avatar) {
1308 final File file = getAvatarFile(avatar.getFilename());
1309 return file.exists();
1310 }
1311
1312 public boolean save(final Avatar avatar) {
1313 File file;
1314 if (isAvatarCached(avatar)) {
1315 file = getAvatarFile(avatar.getFilename());
1316 avatar.size = file.length();
1317 } else {
1318 file =
1319 new File(
1320 mXmppConnectionService.getCacheDir().getAbsolutePath()
1321 + "/"
1322 + UUID.randomUUID().toString());
1323 if (file.getParentFile().mkdirs()) {
1324 Log.d(Config.LOGTAG, "created cache directory");
1325 }
1326 OutputStream os = null;
1327 try {
1328 if (!file.createNewFile()) {
1329 Log.d(
1330 Config.LOGTAG,
1331 "unable to create temporary file " + file.getAbsolutePath());
1332 }
1333 os = new FileOutputStream(file);
1334 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1335 digest.reset();
1336 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1337 final byte[] bytes = avatar.getImageAsBytes();
1338 mDigestOutputStream.write(bytes);
1339 mDigestOutputStream.flush();
1340 mDigestOutputStream.close();
1341 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1342 if (sha1sum.equals(avatar.sha1sum)) {
1343 final File outputFile = getAvatarFile(avatar.getFilename());
1344 if (outputFile.getParentFile().mkdirs()) {
1345 Log.d(Config.LOGTAG, "created avatar directory");
1346 }
1347 final File avatarFile = getAvatarFile(avatar.getFilename());
1348 if (!file.renameTo(avatarFile)) {
1349 Log.d(
1350 Config.LOGTAG,
1351 "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1352 return false;
1353 }
1354 } else {
1355 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1356 if (!file.delete()) {
1357 Log.d(Config.LOGTAG, "unable to delete temporary file");
1358 }
1359 return false;
1360 }
1361 avatar.size = bytes.length;
1362 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1363 return false;
1364 } finally {
1365 close(os);
1366 }
1367 }
1368 return true;
1369 }
1370
1371 public void deleteHistoricAvatarPath() {
1372 delete(getHistoricAvatarPath());
1373 }
1374
1375 private void delete(final File file) {
1376 if (file.isDirectory()) {
1377 final File[] files = file.listFiles();
1378 if (files != null) {
1379 for (final File f : files) {
1380 delete(f);
1381 }
1382 }
1383 }
1384 if (file.delete()) {
1385 Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1386 }
1387 }
1388
1389 private File getHistoricAvatarPath() {
1390 return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1391 }
1392
1393 private File getAvatarFile(String avatar) {
1394 return new File(mXmppConnectionService.getCacheDir(), "/avatars/" + avatar);
1395 }
1396
1397 public Uri getAvatarUri(String avatar) {
1398 return Uri.fromFile(getAvatarFile(avatar));
1399 }
1400
1401 public Bitmap cropCenterSquare(Uri image, int size) {
1402 if (image == null) {
1403 return null;
1404 }
1405 InputStream is = null;
1406 try {
1407 BitmapFactory.Options options = new BitmapFactory.Options();
1408 options.inSampleSize = calcSampleSize(image, size);
1409 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1410 if (is == null) {
1411 return null;
1412 }
1413 Bitmap input = BitmapFactory.decodeStream(is, null, options);
1414 if (input == null) {
1415 return null;
1416 } else {
1417 input = rotate(input, getRotation(image));
1418 return cropCenterSquare(input, size);
1419 }
1420 } catch (FileNotFoundException | SecurityException e) {
1421 Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1422 return null;
1423 } finally {
1424 close(is);
1425 }
1426 }
1427
1428 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1429 if (image == null) {
1430 return null;
1431 }
1432 InputStream is = null;
1433 try {
1434 BitmapFactory.Options options = new BitmapFactory.Options();
1435 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1436 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1437 if (is == null) {
1438 return null;
1439 }
1440 Bitmap source = BitmapFactory.decodeStream(is, null, options);
1441 if (source == null) {
1442 return null;
1443 }
1444 int sourceWidth = source.getWidth();
1445 int sourceHeight = source.getHeight();
1446 float xScale = (float) newWidth / sourceWidth;
1447 float yScale = (float) newHeight / sourceHeight;
1448 float scale = Math.max(xScale, yScale);
1449 float scaledWidth = scale * sourceWidth;
1450 float scaledHeight = scale * sourceHeight;
1451 float left = (newWidth - scaledWidth) / 2;
1452 float top = (newHeight - scaledHeight) / 2;
1453
1454 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1455 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1456 Canvas canvas = new Canvas(dest);
1457 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1458 if (source.isRecycled()) {
1459 source.recycle();
1460 }
1461 return dest;
1462 } catch (SecurityException e) {
1463 return null; // android 6.0 with revoked permissions for example
1464 } catch (FileNotFoundException e) {
1465 return null;
1466 } finally {
1467 close(is);
1468 }
1469 }
1470
1471 public Bitmap cropCenterSquare(Bitmap input, int size) {
1472 int w = input.getWidth();
1473 int h = input.getHeight();
1474
1475 float scale = Math.max((float) size / h, (float) size / w);
1476
1477 float outWidth = scale * w;
1478 float outHeight = scale * h;
1479 float left = (size - outWidth) / 2;
1480 float top = (size - outHeight) / 2;
1481 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1482
1483 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1484 Canvas canvas = new Canvas(output);
1485 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1486 if (!input.isRecycled()) {
1487 input.recycle();
1488 }
1489 return output;
1490 }
1491
1492 private int calcSampleSize(Uri image, int size)
1493 throws FileNotFoundException, SecurityException {
1494 final BitmapFactory.Options options = new BitmapFactory.Options();
1495 options.inJustDecodeBounds = true;
1496 final InputStream inputStream =
1497 mXmppConnectionService.getContentResolver().openInputStream(image);
1498 BitmapFactory.decodeStream(inputStream, null, options);
1499 close(inputStream);
1500 return calcSampleSize(options, size);
1501 }
1502
1503 public void updateFileParams(Message message) {
1504 updateFileParams(message, null);
1505 }
1506
1507 public void updateFileParams(final Message message, final String url) {
1508 final boolean encrypted =
1509 message.getEncryption() == Message.ENCRYPTION_PGP
1510 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED;
1511 final DownloadableFile file = getFile(message);
1512 final String mime = file.getMimeType();
1513 final boolean image =
1514 message.getType() == Message.TYPE_IMAGE
1515 || (mime != null && mime.startsWith("image/"));
1516 final boolean privateMessage = message.isPrivateMessage();
1517 final StringBuilder body = new StringBuilder();
1518 if (url != null) {
1519 body.append(url);
1520 }
1521 if (encrypted && !file.exists()) {
1522 Log.d(Config.LOGTAG, "skipping updateFileParams because file is encrypted");
1523 final DownloadableFile encryptedFile = getFile(message, false);
1524 body.append('|').append(encryptedFile.getSize());
1525 } else {
1526 Log.d(Config.LOGTAG, "running updateFileParams");
1527 final boolean ambiguous = MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime);
1528 final boolean video = mime != null && mime.startsWith("video/");
1529 final boolean audio = mime != null && mime.startsWith("audio/");
1530 final boolean pdf = "application/pdf".equals(mime);
1531 body.append('|').append(file.getSize());
1532 if (ambiguous) {
1533 try {
1534 final Dimensions dimensions = getVideoDimensions(file);
1535 if (dimensions.valid()) {
1536 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is video");
1537 body.append('|')
1538 .append(dimensions.width)
1539 .append('|')
1540 .append(dimensions.height);
1541 } else {
1542 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1543 body.append("|0|0|").append(getMediaRuntime(file));
1544 }
1545 } catch (final IOException | NotAVideoFile e) {
1546 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1547 body.append("|0|0|").append(getMediaRuntime(file));
1548 }
1549 } else if (image || video || pdf) {
1550 try {
1551 final Dimensions dimensions;
1552 if (video) {
1553 dimensions = getVideoDimensions(file);
1554 } else if (pdf) {
1555 dimensions = getPdfDocumentDimensions(file);
1556 } else {
1557 dimensions = getImageDimensions(file);
1558 }
1559 if (dimensions.valid()) {
1560 body.append('|')
1561 .append(dimensions.width)
1562 .append('|')
1563 .append(dimensions.height);
1564 }
1565 } catch (final IOException | NotAVideoFile notAVideoFile) {
1566 Log.d(
1567 Config.LOGTAG,
1568 "file with mime type " + file.getMimeType() + " was not a video file");
1569 // fall threw
1570 }
1571 } else if (audio) {
1572 body.append("|0|0|").append(getMediaRuntime(file));
1573 }
1574 }
1575 message.setBody(body.toString());
1576 message.setDeleted(false);
1577 message.setType(
1578 privateMessage
1579 ? Message.TYPE_PRIVATE_FILE
1580 : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1581 }
1582
1583 private int getMediaRuntime(final File file) {
1584 try {
1585 final MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1586 mediaMetadataRetriever.setDataSource(file.toString());
1587 final String value =
1588 mediaMetadataRetriever.extractMetadata(
1589 MediaMetadataRetriever.METADATA_KEY_DURATION);
1590 if (Strings.isNullOrEmpty(value)) {
1591 return 0;
1592 }
1593 return Integer.parseInt(value);
1594 } catch (final Exception e) {
1595 return 0;
1596 }
1597 }
1598
1599 private Dimensions getImageDimensions(File file) {
1600 final BitmapFactory.Options options = new BitmapFactory.Options();
1601 options.inJustDecodeBounds = true;
1602 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1603 final int rotation = getRotation(file);
1604 final boolean rotated = rotation == 90 || rotation == 270;
1605 final int imageHeight = rotated ? options.outWidth : options.outHeight;
1606 final int imageWidth = rotated ? options.outHeight : options.outWidth;
1607 return new Dimensions(imageHeight, imageWidth);
1608 }
1609
1610 private Dimensions getVideoDimensions(final File file) throws NotAVideoFile, IOException {
1611 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1612 try {
1613 metadataRetriever.setDataSource(file.getAbsolutePath());
1614 } catch (RuntimeException e) {
1615 throw new NotAVideoFile(e);
1616 }
1617 return getVideoDimensions(metadataRetriever);
1618 }
1619
1620 private Dimensions getPdfDocumentDimensions(final File file) {
1621 final ParcelFileDescriptor fileDescriptor;
1622 try {
1623 fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1624 if (fileDescriptor == null) {
1625 return new Dimensions(0, 0);
1626 }
1627 } catch (final FileNotFoundException e) {
1628 return new Dimensions(0, 0);
1629 }
1630 try {
1631 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1632 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1633 final int height = page.getHeight();
1634 final int width = page.getWidth();
1635 page.close();
1636 pdfRenderer.close();
1637 return scalePdfDimensions(new Dimensions(height, width));
1638 } catch (final IOException | SecurityException e) {
1639 Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1640 return new Dimensions(0, 0);
1641 }
1642 }
1643
1644 private Dimensions scalePdfDimensions(Dimensions in) {
1645 final DisplayMetrics displayMetrics =
1646 mXmppConnectionService.getResources().getDisplayMetrics();
1647 final int target = (int) (displayMetrics.density * 288);
1648 return scalePdfDimensions(in, target, true);
1649 }
1650
1651 private static Dimensions scalePdfDimensions(
1652 final Dimensions in, final int target, final boolean fit) {
1653 final int w, h;
1654 if (fit == (in.width <= in.height)) {
1655 w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1656 h = target;
1657 } else {
1658 w = target;
1659 h = Math.max((int) (in.height / ((double) in.width / target)), 1);
1660 }
1661 return new Dimensions(h, w);
1662 }
1663
1664 public Bitmap getAvatar(String avatar, int size) {
1665 if (avatar == null) {
1666 return null;
1667 }
1668 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1669 return bm;
1670 }
1671
1672 private static class Dimensions {
1673 public final int width;
1674 public final int height;
1675
1676 Dimensions(int height, int width) {
1677 this.width = width;
1678 this.height = height;
1679 }
1680
1681 public int getMin() {
1682 return Math.min(width, height);
1683 }
1684
1685 public boolean valid() {
1686 return width > 0 && height > 0;
1687 }
1688 }
1689
1690 private static class NotAVideoFile extends Exception {
1691 public NotAVideoFile(Throwable t) {
1692 super(t);
1693 }
1694
1695 public NotAVideoFile() {
1696 super();
1697 }
1698 }
1699
1700 public static class ImageCompressionException extends Exception {
1701
1702 ImageCompressionException(String message) {
1703 super(message);
1704 }
1705 }
1706
1707 public static class FileCopyException extends Exception {
1708 private final int resId;
1709
1710 private FileCopyException(@StringRes int resId) {
1711 this.resId = resId;
1712 }
1713
1714 public @StringRes int getResId() {
1715 return resId;
1716 }
1717 }
1718}