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 weOwnFile(final Uri uri) {
374 if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
375 return false;
376 } else {
377 return weOwnFileLollipop(uri);
378 }
379 }
380
381 private static boolean weOwnFileLollipop(final Uri uri) {
382 final String path = uri.getPath();
383 if (path == null) {
384 return false;
385 }
386 try {
387 File file = new File(path);
388 FileDescriptor fd =
389 ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
390 .getFileDescriptor();
391 StructStat st = Os.fstat(fd);
392 return st.st_uid == android.os.Process.myUid();
393 } catch (FileNotFoundException e) {
394 return false;
395 } catch (Exception e) {
396 return true;
397 }
398 }
399
400 public static Uri getMediaUri(Context context, File file) {
401 final String filePath = file.getAbsolutePath();
402 try (final Cursor cursor =
403 context.getContentResolver()
404 .query(
405 MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
406 new String[] {MediaStore.Images.Media._ID},
407 MediaStore.Images.Media.DATA + "=? ",
408 new String[] {filePath},
409 null)) {
410 if (cursor != null && cursor.moveToFirst()) {
411 final int id =
412 cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
413 return Uri.withAppendedPath(
414 MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
415 } else {
416 return null;
417 }
418 } catch (final Exception e) {
419 return null;
420 }
421 }
422
423 public static void updateFileParams(Message message, String url, long size) {
424 final StringBuilder body = new StringBuilder();
425 body.append(url).append('|').append(size);
426 message.setBody(body.toString());
427 }
428
429 public Bitmap getPreviewForUri(Attachment attachment, int size, boolean cacheOnly) {
430 final String key = "attachment_" + attachment.getUuid().toString() + "_" + size;
431 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
432 Bitmap bitmap = cache.get(key);
433 if (bitmap != null || cacheOnly) {
434 return bitmap;
435 }
436 final String mime = attachment.getMime();
437 if ("application/pdf".equals(mime)) {
438 bitmap = cropCenterSquarePdf(attachment.getUri(), size);
439 drawOverlay(
440 bitmap,
441 paintOverlayBlackPdf(bitmap)
442 ? R.drawable.open_pdf_black
443 : R.drawable.open_pdf_white,
444 0.75f);
445 } else if (mime != null && mime.startsWith("video/")) {
446 bitmap = cropCenterSquareVideo(attachment.getUri(), size);
447 drawOverlay(
448 bitmap,
449 paintOverlayBlack(bitmap)
450 ? R.drawable.play_video_black
451 : R.drawable.play_video_white,
452 0.75f);
453 } else {
454 bitmap = cropCenterSquare(attachment.getUri(), size);
455 if (bitmap != null && "image/gif".equals(mime)) {
456 Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
457 drawOverlay(
458 withGifOverlay,
459 paintOverlayBlack(withGifOverlay)
460 ? R.drawable.play_gif_black
461 : R.drawable.play_gif_white,
462 1.0f);
463 bitmap.recycle();
464 bitmap = withGifOverlay;
465 }
466 }
467 if (bitmap != null) {
468 cache.put(key, bitmap);
469 }
470 return bitmap;
471 }
472
473 public void updateMediaScanner(File file) {
474 updateMediaScanner(file, null);
475 }
476
477 public void updateMediaScanner(File file, final Runnable callback) {
478 MediaScannerConnection.scanFile(
479 mXmppConnectionService,
480 new String[] {file.getAbsolutePath()},
481 null,
482 new MediaScannerConnection.MediaScannerConnectionClient() {
483 @Override
484 public void onMediaScannerConnected() {}
485
486 @Override
487 public void onScanCompleted(String path, Uri uri) {
488 if (callback != null && file.getAbsolutePath().equals(path)) {
489 callback.run();
490 } else {
491 Log.d(Config.LOGTAG, "media scanner scanned wrong file");
492 if (callback != null) {
493 callback.run();
494 }
495 }
496 }
497 });
498 }
499
500 public boolean deleteFile(Message message) {
501 File file = getFile(message);
502 if (file.delete()) {
503 updateMediaScanner(file);
504 return true;
505 } else {
506 return false;
507 }
508 }
509
510 public DownloadableFile getFile(Message message) {
511 return getFile(message, true);
512 }
513
514 public DownloadableFile getFileForPath(String path) {
515 return getFileForPath(
516 path,
517 MimeUtils.guessMimeTypeFromExtension(MimeUtils.extractRelevantExtension(path)));
518 }
519
520 private DownloadableFile getFileForPath(final String path, final String mime) {
521 if (path.startsWith("/")) {
522 return new DownloadableFile(path);
523 } else {
524 return getLegacyFileForFilename(path, mime);
525 }
526 }
527
528 public DownloadableFile getLegacyFileForFilename(final String filename, final String mime) {
529 if (Strings.isNullOrEmpty(mime)) {
530 return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
531 } else if (mime.startsWith("image/")) {
532 return new DownloadableFile(getLegacyStorageLocation("Images"), filename);
533 } else if (mime.startsWith("video/")) {
534 return new DownloadableFile(getLegacyStorageLocation("Videos"), filename);
535 } else {
536 return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
537 }
538 }
539
540 public boolean isInternalFile(final File file) {
541 final File internalFile = getFileForPath(file.getName());
542 return file.getAbsolutePath().equals(internalFile.getAbsolutePath());
543 }
544
545 public DownloadableFile getFile(Message message, boolean decrypted) {
546 final boolean encrypted =
547 !decrypted
548 && (message.getEncryption() == Message.ENCRYPTION_PGP
549 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
550 String path = message.getRelativeFilePath();
551 if (path == null) {
552 path = message.getUuid();
553 }
554 final DownloadableFile file = getFileForPath(path, message.getMimeType());
555 if (encrypted) {
556 return new DownloadableFile(
557 mXmppConnectionService.getCacheDir(),
558 String.format("%s.%s", file.getName(), "pgp"));
559 } else {
560 return file;
561 }
562 }
563
564 public List<Attachment> convertToAttachments(List<DatabaseBackend.FilePath> relativeFilePaths) {
565 final List<Attachment> attachments = new ArrayList<>();
566 for (final DatabaseBackend.FilePath relativeFilePath : relativeFilePaths) {
567 final String mime =
568 MimeUtils.guessMimeTypeFromExtension(
569 MimeUtils.extractRelevantExtension(relativeFilePath.path));
570 final File file = getFileForPath(relativeFilePath.path, mime);
571 attachments.add(Attachment.of(relativeFilePath.uuid, file, mime));
572 }
573 return attachments;
574 }
575
576 private File getLegacyStorageLocation(final String type) {
577 if (Config.ONLY_INTERNAL_STORAGE) {
578 return new File(mXmppConnectionService.getFilesDir(), type);
579 } else {
580 final File appDirectory =
581 new File(
582 Environment.getExternalStorageDirectory(),
583 mXmppConnectionService.getString(R.string.app_name));
584 final File appMediaDirectory = new File(appDirectory, "Media");
585 final String locationName =
586 String.format(
587 "%s %s", mXmppConnectionService.getString(R.string.app_name), type);
588 return new File(appMediaDirectory, locationName);
589 }
590 }
591
592 private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
593 int w = originalBitmap.getWidth();
594 int h = originalBitmap.getHeight();
595 if (w <= 0 || h <= 0) {
596 throw new IOException("Decoded bitmap reported bounds smaller 0");
597 } else if (Math.max(w, h) > size) {
598 int scalledW;
599 int scalledH;
600 if (w <= h) {
601 scalledW = Math.max((int) (w / ((double) h / size)), 1);
602 scalledH = size;
603 } else {
604 scalledW = size;
605 scalledH = Math.max((int) (h / ((double) w / size)), 1);
606 }
607 final Bitmap result =
608 Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
609 if (!originalBitmap.isRecycled()) {
610 originalBitmap.recycle();
611 }
612 return result;
613 } else {
614 return originalBitmap;
615 }
616 }
617
618 public boolean useImageAsIs(final Uri uri) {
619 final String path = getOriginalPath(uri);
620 if (path == null || isPathBlacklisted(path)) {
621 return false;
622 }
623 final File file = new File(path);
624 long size = file.length();
625 if (size == 0
626 || size
627 >= mXmppConnectionService
628 .getResources()
629 .getInteger(R.integer.auto_accept_filesize)) {
630 return false;
631 }
632 BitmapFactory.Options options = new BitmapFactory.Options();
633 options.inJustDecodeBounds = true;
634 try {
635 final InputStream inputStream =
636 mXmppConnectionService.getContentResolver().openInputStream(uri);
637 BitmapFactory.decodeStream(inputStream, null, options);
638 close(inputStream);
639 if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
640 return false;
641 }
642 return (options.outWidth <= Config.IMAGE_SIZE
643 && options.outHeight <= Config.IMAGE_SIZE
644 && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
645 } catch (FileNotFoundException e) {
646 Log.d(Config.LOGTAG, "unable to get image dimensions", e);
647 return false;
648 }
649 }
650
651 public String getOriginalPath(final Uri uri) {
652 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
653 // On Android 11+ we don’t have access to the original file
654 return null;
655 } else {
656 return FileUtils.getPath(mXmppConnectionService, uri);
657 }
658 }
659
660 private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
661 Log.d(
662 Config.LOGTAG,
663 "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
664 file.getParentFile().mkdirs();
665 try {
666 file.createNewFile();
667 } catch (IOException e) {
668 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
669 }
670 try (final OutputStream os = new FileOutputStream(file);
671 final InputStream is =
672 mXmppConnectionService.getContentResolver().openInputStream(uri)) {
673 if (is == null) {
674 throw new FileCopyException(R.string.error_file_not_found);
675 }
676 try {
677 ByteStreams.copy(is, os);
678 } catch (IOException e) {
679 throw new FileWriterException(file);
680 }
681 try {
682 os.flush();
683 } catch (IOException e) {
684 throw new FileWriterException(file);
685 }
686 } catch (final FileNotFoundException e) {
687 cleanup(file);
688 throw new FileCopyException(R.string.error_file_not_found);
689 } catch (final FileWriterException e) {
690 cleanup(file);
691 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
692 } catch (final SecurityException | IllegalStateException e) {
693 cleanup(file);
694 throw new FileCopyException(R.string.error_security_exception);
695 } catch (final IOException e) {
696 cleanup(file);
697 throw new FileCopyException(R.string.error_io_exception);
698 }
699 }
700
701 public void copyFileToPrivateStorage(Message message, Uri uri, String type)
702 throws FileCopyException {
703 String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
704 Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
705 String extension = MimeUtils.guessExtensionFromMimeType(mime);
706 if (extension == null) {
707 Log.d(Config.LOGTAG, "extension from mime type was null");
708 extension = getExtensionFromUri(uri);
709 }
710 if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
711 extension = "oga";
712 }
713 setupRelativeFilePath(message, String.format("%s.%s", message.getUuid(), extension));
714 copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
715 }
716
717 private String getExtensionFromUri(final Uri uri) {
718 final String[] projection = {MediaStore.MediaColumns.DATA};
719 String filename = null;
720 try (final Cursor cursor =
721 mXmppConnectionService
722 .getContentResolver()
723 .query(uri, projection, null, null, null)) {
724 if (cursor != null && cursor.moveToFirst()) {
725 filename = cursor.getString(0);
726 }
727 } catch (final Exception e) {
728 filename = null;
729 }
730 if (filename == null) {
731 final List<String> segments = uri.getPathSegments();
732 if (segments.size() > 0) {
733 filename = segments.get(segments.size() - 1);
734 }
735 }
736 final int pos = filename == null ? -1 : filename.lastIndexOf('.');
737 return pos > 0 ? filename.substring(pos + 1) : null;
738 }
739
740 private void copyImageToPrivateStorage(File file, Uri image, int sampleSize)
741 throws FileCopyException, ImageCompressionException {
742 final File parent = file.getParentFile();
743 if (parent != null && parent.mkdirs()) {
744 Log.d(Config.LOGTAG, "created parent directory");
745 }
746 InputStream is = null;
747 OutputStream os = null;
748 try {
749 if (!file.exists() && !file.createNewFile()) {
750 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
751 }
752 is = mXmppConnectionService.getContentResolver().openInputStream(image);
753 if (is == null) {
754 throw new FileCopyException(R.string.error_not_an_image_file);
755 }
756 final Bitmap originalBitmap;
757 final BitmapFactory.Options options = new BitmapFactory.Options();
758 final int inSampleSize = (int) Math.pow(2, sampleSize);
759 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
760 options.inSampleSize = inSampleSize;
761 originalBitmap = BitmapFactory.decodeStream(is, null, options);
762 is.close();
763 if (originalBitmap == null) {
764 throw new ImageCompressionException("Source file was not an image");
765 }
766 if (!"image/jpeg".equals(options.outMimeType) && hasAlpha(originalBitmap)) {
767 originalBitmap.recycle();
768 throw new ImageCompressionException("Source file had alpha channel");
769 }
770 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
771 final int rotation = getRotation(image);
772 scaledBitmap = rotate(scaledBitmap, rotation);
773 boolean targetSizeReached = false;
774 int quality = Config.IMAGE_QUALITY;
775 final int imageMaxSize =
776 mXmppConnectionService
777 .getResources()
778 .getInteger(R.integer.auto_accept_filesize);
779 while (!targetSizeReached) {
780 os = new FileOutputStream(file);
781 Log.d(Config.LOGTAG, "compressing image with quality " + quality);
782 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
783 if (!success) {
784 throw new FileCopyException(R.string.error_compressing_image);
785 }
786 os.flush();
787 final long fileSize = file.length();
788 Log.d(Config.LOGTAG, "achieved file size of " + fileSize);
789 targetSizeReached = fileSize <= imageMaxSize || quality <= 50;
790 quality -= 5;
791 }
792 scaledBitmap.recycle();
793 } catch (final FileNotFoundException e) {
794 cleanup(file);
795 throw new FileCopyException(R.string.error_file_not_found);
796 } catch (final IOException e) {
797 cleanup(file);
798 throw new FileCopyException(R.string.error_io_exception);
799 } catch (SecurityException e) {
800 cleanup(file);
801 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
802 } catch (final OutOfMemoryError e) {
803 ++sampleSize;
804 if (sampleSize <= 3) {
805 copyImageToPrivateStorage(file, image, sampleSize);
806 } else {
807 throw new FileCopyException(R.string.error_out_of_memory);
808 }
809 } finally {
810 close(os);
811 close(is);
812 }
813 }
814
815 private static void cleanup(final File file) {
816 try {
817 file.delete();
818 } catch (Exception e) {
819
820 }
821 }
822
823 public void copyImageToPrivateStorage(File file, Uri image)
824 throws FileCopyException, ImageCompressionException {
825 Log.d(
826 Config.LOGTAG,
827 "copy image ("
828 + image.toString()
829 + ") to private storage "
830 + file.getAbsolutePath());
831 copyImageToPrivateStorage(file, image, 0);
832 }
833
834 public void copyImageToPrivateStorage(Message message, Uri image)
835 throws FileCopyException, ImageCompressionException {
836 final String filename;
837 switch (Config.IMAGE_FORMAT) {
838 case JPEG:
839 filename = String.format("%s.%s", message.getUuid(), "jpg");
840 break;
841 case PNG:
842 filename = String.format("%s.%s", message.getUuid(), "png");
843 break;
844 case WEBP:
845 filename = String.format("%s.%s", message.getUuid(), "webp");
846 break;
847 default:
848 throw new IllegalStateException("Unknown image format");
849 }
850 setupRelativeFilePath(message, filename);
851 copyImageToPrivateStorage(getFile(message), image);
852 updateFileParams(message);
853 }
854
855 public void setupRelativeFilePath(final Message message, final String filename) {
856 final String extension = MimeUtils.extractRelevantExtension(filename);
857 final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
858 setupRelativeFilePath(message, filename, mime);
859 }
860
861 public File getStorageLocation(final String filename, final String mime) {
862 final File parentDirectory;
863 if (Strings.isNullOrEmpty(mime)) {
864 parentDirectory =
865 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
866 } else if (mime.startsWith("image/")) {
867 parentDirectory =
868 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
869 } else if (mime.startsWith("video/")) {
870 parentDirectory =
871 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
872 } else if (MediaAdapter.DOCUMENT_MIMES.contains(mime)) {
873 parentDirectory =
874 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
875 } else {
876 parentDirectory =
877 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
878 }
879 final File appDirectory =
880 new File(parentDirectory, mXmppConnectionService.getString(R.string.app_name));
881 return new File(appDirectory, filename);
882 }
883
884 public static boolean inConversationsDirectory(final Context context, String path) {
885 final File fileDirectory = new File(path).getParentFile();
886 for (final String type : STORAGE_TYPES) {
887 final File typeDirectory =
888 new File(
889 Environment.getExternalStoragePublicDirectory(type),
890 context.getString(R.string.app_name));
891 if (typeDirectory.equals(fileDirectory)) {
892 return true;
893 }
894 }
895 return false;
896 }
897
898 public void setupRelativeFilePath(
899 final Message message, final String filename, final String mime) {
900 final File file = getStorageLocation(filename, mime);
901 message.setRelativeFilePath(file.getAbsolutePath());
902 }
903
904 public boolean unusualBounds(final Uri image) {
905 try {
906 final BitmapFactory.Options options = new BitmapFactory.Options();
907 options.inJustDecodeBounds = true;
908 final InputStream inputStream =
909 mXmppConnectionService.getContentResolver().openInputStream(image);
910 BitmapFactory.decodeStream(inputStream, null, options);
911 close(inputStream);
912 float ratio = (float) options.outHeight / options.outWidth;
913 return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
914 } catch (final Exception e) {
915 Log.w(Config.LOGTAG, "unable to detect image bounds", e);
916 return false;
917 }
918 }
919
920 private int getRotation(final File file) {
921 try (final InputStream inputStream = new FileInputStream(file)) {
922 return getRotation(inputStream);
923 } catch (Exception e) {
924 return 0;
925 }
926 }
927
928 private int getRotation(final Uri image) {
929 try (final InputStream is =
930 mXmppConnectionService.getContentResolver().openInputStream(image)) {
931 return is == null ? 0 : getRotation(is);
932 } catch (final Exception e) {
933 return 0;
934 }
935 }
936
937 private static int getRotation(final InputStream inputStream) throws IOException {
938 final ExifInterface exif = new ExifInterface(inputStream);
939 final int orientation =
940 exif.getAttributeInt(
941 ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
942 switch (orientation) {
943 case ExifInterface.ORIENTATION_ROTATE_180:
944 return 180;
945 case ExifInterface.ORIENTATION_ROTATE_90:
946 return 90;
947 case ExifInterface.ORIENTATION_ROTATE_270:
948 return 270;
949 default:
950 return 0;
951 }
952 }
953
954 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
955 final String uuid = message.getUuid();
956 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
957 Bitmap thumbnail = cache.get(uuid);
958 if ((thumbnail == null) && (!cacheOnly)) {
959 synchronized (THUMBNAIL_LOCK) {
960 thumbnail = cache.get(uuid);
961 if (thumbnail != null) {
962 return thumbnail;
963 }
964 DownloadableFile file = getFile(message);
965 final String mime = file.getMimeType();
966 if ("application/pdf".equals(mime)) {
967 thumbnail = getPdfDocumentPreview(file, size);
968 } else if (mime.startsWith("video/")) {
969 thumbnail = getVideoPreview(file, size);
970 } else {
971 final Bitmap fullSize = getFullSizeImagePreview(file, size);
972 if (fullSize == null) {
973 throw new FileNotFoundException();
974 }
975 thumbnail = resize(fullSize, size);
976 thumbnail = rotate(thumbnail, getRotation(file));
977 if (mime.equals("image/gif")) {
978 Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
979 drawOverlay(
980 withGifOverlay,
981 paintOverlayBlack(withGifOverlay)
982 ? R.drawable.play_gif_black
983 : R.drawable.play_gif_white,
984 1.0f);
985 thumbnail.recycle();
986 thumbnail = withGifOverlay;
987 }
988 }
989 cache.put(uuid, thumbnail);
990 }
991 }
992 return thumbnail;
993 }
994
995 private Bitmap getFullSizeImagePreview(File file, int size) {
996 BitmapFactory.Options options = new BitmapFactory.Options();
997 options.inSampleSize = calcSampleSize(file, size);
998 try {
999 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1000 } catch (OutOfMemoryError e) {
1001 options.inSampleSize *= 2;
1002 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1003 }
1004 }
1005
1006 private void drawOverlay(Bitmap bitmap, int resource, float factor) {
1007 Bitmap overlay =
1008 BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
1009 Canvas canvas = new Canvas(bitmap);
1010 float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
1011 Log.d(
1012 Config.LOGTAG,
1013 "target size overlay: "
1014 + targetSize
1015 + " overlay bitmap size was "
1016 + overlay.getHeight());
1017 float left = (canvas.getWidth() - targetSize) / 2.0f;
1018 float top = (canvas.getHeight() - targetSize) / 2.0f;
1019 RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
1020 canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
1021 }
1022
1023 /** https://stackoverflow.com/a/3943023/210897 */
1024 private boolean paintOverlayBlack(final Bitmap bitmap) {
1025 final int h = bitmap.getHeight();
1026 final int w = bitmap.getWidth();
1027 int record = 0;
1028 for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
1029 for (int x = Math.round(w * IGNORE_PADDING);
1030 x < w - Math.round(w * IGNORE_PADDING);
1031 ++x) {
1032 int pixel = bitmap.getPixel(x, y);
1033 if ((Color.red(pixel) * 0.299
1034 + Color.green(pixel) * 0.587
1035 + Color.blue(pixel) * 0.114)
1036 > 186) {
1037 --record;
1038 } else {
1039 ++record;
1040 }
1041 }
1042 }
1043 return record < 0;
1044 }
1045
1046 private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1047 final int h = bitmap.getHeight();
1048 final int w = bitmap.getWidth();
1049 int white = 0;
1050 for (int y = 0; y < h; ++y) {
1051 for (int x = 0; x < w; ++x) {
1052 int pixel = bitmap.getPixel(x, y);
1053 if ((Color.red(pixel) * 0.299
1054 + Color.green(pixel) * 0.587
1055 + Color.blue(pixel) * 0.114)
1056 > 186) {
1057 white++;
1058 }
1059 }
1060 }
1061 return white > (h * w * 0.4f);
1062 }
1063
1064 private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1065 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1066 Bitmap frame;
1067 try {
1068 metadataRetriever.setDataSource(mXmppConnectionService, uri);
1069 frame = metadataRetriever.getFrameAtTime(0);
1070 metadataRetriever.release();
1071 return cropCenterSquare(frame, size);
1072 } catch (Exception e) {
1073 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1074 frame.eraseColor(0xff000000);
1075 return frame;
1076 }
1077 }
1078
1079 private Bitmap getVideoPreview(final File file, final int size) {
1080 final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1081 Bitmap frame;
1082 try {
1083 metadataRetriever.setDataSource(file.getAbsolutePath());
1084 frame = metadataRetriever.getFrameAtTime(0);
1085 metadataRetriever.release();
1086 frame = resize(frame, size);
1087 } catch (IOException | RuntimeException e) {
1088 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1089 frame.eraseColor(0xff000000);
1090 }
1091 drawOverlay(
1092 frame,
1093 paintOverlayBlack(frame)
1094 ? R.drawable.play_video_black
1095 : R.drawable.play_video_white,
1096 0.75f);
1097 return frame;
1098 }
1099
1100 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1101 private Bitmap getPdfDocumentPreview(final File file, final int size) {
1102 try {
1103 final ParcelFileDescriptor fileDescriptor =
1104 ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1105 final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1106 drawOverlay(
1107 rendered,
1108 paintOverlayBlackPdf(rendered)
1109 ? R.drawable.open_pdf_black
1110 : R.drawable.open_pdf_white,
1111 0.75f);
1112 return rendered;
1113 } catch (final IOException | SecurityException e) {
1114 Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1115 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1116 placeholder.eraseColor(0xff000000);
1117 return placeholder;
1118 }
1119 }
1120
1121 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1122 private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1123 try {
1124 ParcelFileDescriptor fileDescriptor =
1125 mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1126 final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1127 return cropCenterSquare(bitmap, size);
1128 } catch (Exception e) {
1129 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1130 placeholder.eraseColor(0xff000000);
1131 return placeholder;
1132 }
1133 }
1134
1135 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1136 private Bitmap renderPdfDocument(
1137 ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1138 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1139 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1140 final Dimensions dimensions =
1141 scalePdfDimensions(
1142 new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1143 final Bitmap rendered =
1144 Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1145 rendered.eraseColor(0xffffffff);
1146 page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1147 page.close();
1148 pdfRenderer.close();
1149 fileDescriptor.close();
1150 return rendered;
1151 }
1152
1153 public Uri getTakePhotoUri() {
1154 final String filename =
1155 String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1156 final File directory;
1157 if (Config.ONLY_INTERNAL_STORAGE) {
1158 directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1159 } else {
1160 directory =
1161 new File(
1162 Environment.getExternalStoragePublicDirectory(
1163 Environment.DIRECTORY_DCIM),
1164 "Camera");
1165 }
1166 final File file = new File(directory, filename);
1167 file.getParentFile().mkdirs();
1168 return getUriForFile(mXmppConnectionService, file);
1169 }
1170
1171 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
1172
1173 final Avatar uncompressAvatar = getUncompressedAvatar(image);
1174 if (uncompressAvatar != null
1175 && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
1176 return uncompressAvatar;
1177 }
1178 if (uncompressAvatar != null) {
1179 Log.d(
1180 Config.LOGTAG,
1181 "uncompressed avatar exceeded char limit by "
1182 + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
1183 }
1184
1185 Bitmap bm = cropCenterSquare(image, size);
1186 if (bm == null) {
1187 return null;
1188 }
1189 if (hasAlpha(bm)) {
1190 Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1191 bm.recycle();
1192 bm = cropCenterSquare(image, 96);
1193 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1194 }
1195 return getPepAvatar(bm, format, 100);
1196 }
1197
1198 private Avatar getUncompressedAvatar(Uri uri) {
1199 Bitmap bitmap = null;
1200 try {
1201 bitmap =
1202 BitmapFactory.decodeStream(
1203 mXmppConnectionService.getContentResolver().openInputStream(uri));
1204 return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
1205 } catch (Exception e) {
1206 return null;
1207 } finally {
1208 if (bitmap != null) {
1209 bitmap.recycle();
1210 }
1211 }
1212 }
1213
1214 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1215 try {
1216 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1217 Base64OutputStream mBase64OutputStream =
1218 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1219 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1220 DigestOutputStream mDigestOutputStream =
1221 new DigestOutputStream(mBase64OutputStream, digest);
1222 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1223 return null;
1224 }
1225 mDigestOutputStream.flush();
1226 mDigestOutputStream.close();
1227 long chars = mByteArrayOutputStream.size();
1228 if (format != Bitmap.CompressFormat.PNG
1229 && quality >= 50
1230 && chars >= Config.AVATAR_CHAR_LIMIT) {
1231 int q = quality - 2;
1232 Log.d(
1233 Config.LOGTAG,
1234 "avatar char length was " + chars + " reducing quality to " + q);
1235 return getPepAvatar(bitmap, format, q);
1236 }
1237 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1238 final Avatar avatar = new Avatar();
1239 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1240 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1241 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1242 avatar.type = "image/webp";
1243 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1244 avatar.type = "image/jpeg";
1245 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1246 avatar.type = "image/png";
1247 }
1248 avatar.width = bitmap.getWidth();
1249 avatar.height = bitmap.getHeight();
1250 return avatar;
1251 } catch (OutOfMemoryError e) {
1252 Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1253 return null;
1254 } catch (Exception e) {
1255 return null;
1256 }
1257 }
1258
1259 public Avatar getStoredPepAvatar(String hash) {
1260 if (hash == null) {
1261 return null;
1262 }
1263 Avatar avatar = new Avatar();
1264 final File file = getAvatarFile(hash);
1265 FileInputStream is = null;
1266 try {
1267 avatar.size = file.length();
1268 BitmapFactory.Options options = new BitmapFactory.Options();
1269 options.inJustDecodeBounds = true;
1270 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1271 is = new FileInputStream(file);
1272 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1273 Base64OutputStream mBase64OutputStream =
1274 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1275 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1276 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1277 byte[] buffer = new byte[4096];
1278 int length;
1279 while ((length = is.read(buffer)) > 0) {
1280 os.write(buffer, 0, length);
1281 }
1282 os.flush();
1283 os.close();
1284 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1285 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1286 avatar.height = options.outHeight;
1287 avatar.width = options.outWidth;
1288 avatar.type = options.outMimeType;
1289 return avatar;
1290 } catch (NoSuchAlgorithmException | IOException e) {
1291 return null;
1292 } finally {
1293 close(is);
1294 }
1295 }
1296
1297 public boolean isAvatarCached(Avatar avatar) {
1298 final File file = getAvatarFile(avatar.getFilename());
1299 return file.exists();
1300 }
1301
1302 public boolean save(final Avatar avatar) {
1303 File file;
1304 if (isAvatarCached(avatar)) {
1305 file = getAvatarFile(avatar.getFilename());
1306 avatar.size = file.length();
1307 } else {
1308 file =
1309 new File(
1310 mXmppConnectionService.getCacheDir().getAbsolutePath()
1311 + "/"
1312 + UUID.randomUUID().toString());
1313 if (file.getParentFile().mkdirs()) {
1314 Log.d(Config.LOGTAG, "created cache directory");
1315 }
1316 OutputStream os = null;
1317 try {
1318 if (!file.createNewFile()) {
1319 Log.d(
1320 Config.LOGTAG,
1321 "unable to create temporary file " + file.getAbsolutePath());
1322 }
1323 os = new FileOutputStream(file);
1324 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1325 digest.reset();
1326 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1327 final byte[] bytes = avatar.getImageAsBytes();
1328 mDigestOutputStream.write(bytes);
1329 mDigestOutputStream.flush();
1330 mDigestOutputStream.close();
1331 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1332 if (sha1sum.equals(avatar.sha1sum)) {
1333 final File outputFile = getAvatarFile(avatar.getFilename());
1334 if (outputFile.getParentFile().mkdirs()) {
1335 Log.d(Config.LOGTAG, "created avatar directory");
1336 }
1337 final File avatarFile = getAvatarFile(avatar.getFilename());
1338 if (!file.renameTo(avatarFile)) {
1339 Log.d(
1340 Config.LOGTAG,
1341 "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1342 return false;
1343 }
1344 } else {
1345 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1346 if (!file.delete()) {
1347 Log.d(Config.LOGTAG, "unable to delete temporary file");
1348 }
1349 return false;
1350 }
1351 avatar.size = bytes.length;
1352 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1353 return false;
1354 } finally {
1355 close(os);
1356 }
1357 }
1358 return true;
1359 }
1360
1361 public void deleteHistoricAvatarPath() {
1362 delete(getHistoricAvatarPath());
1363 }
1364
1365 private void delete(final File file) {
1366 if (file.isDirectory()) {
1367 final File[] files = file.listFiles();
1368 if (files != null) {
1369 for (final File f : files) {
1370 delete(f);
1371 }
1372 }
1373 }
1374 if (file.delete()) {
1375 Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1376 }
1377 }
1378
1379 private File getHistoricAvatarPath() {
1380 return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1381 }
1382
1383 private File getAvatarFile(String avatar) {
1384 return new File(mXmppConnectionService.getCacheDir(), "/avatars/" + avatar);
1385 }
1386
1387 public Uri getAvatarUri(String avatar) {
1388 return Uri.fromFile(getAvatarFile(avatar));
1389 }
1390
1391 public Bitmap cropCenterSquare(Uri image, int size) {
1392 if (image == null) {
1393 return null;
1394 }
1395 InputStream is = null;
1396 try {
1397 BitmapFactory.Options options = new BitmapFactory.Options();
1398 options.inSampleSize = calcSampleSize(image, size);
1399 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1400 if (is == null) {
1401 return null;
1402 }
1403 Bitmap input = BitmapFactory.decodeStream(is, null, options);
1404 if (input == null) {
1405 return null;
1406 } else {
1407 input = rotate(input, getRotation(image));
1408 return cropCenterSquare(input, size);
1409 }
1410 } catch (FileNotFoundException | SecurityException e) {
1411 Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1412 return null;
1413 } finally {
1414 close(is);
1415 }
1416 }
1417
1418 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1419 if (image == null) {
1420 return null;
1421 }
1422 InputStream is = null;
1423 try {
1424 BitmapFactory.Options options = new BitmapFactory.Options();
1425 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1426 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1427 if (is == null) {
1428 return null;
1429 }
1430 Bitmap source = BitmapFactory.decodeStream(is, null, options);
1431 if (source == null) {
1432 return null;
1433 }
1434 int sourceWidth = source.getWidth();
1435 int sourceHeight = source.getHeight();
1436 float xScale = (float) newWidth / sourceWidth;
1437 float yScale = (float) newHeight / sourceHeight;
1438 float scale = Math.max(xScale, yScale);
1439 float scaledWidth = scale * sourceWidth;
1440 float scaledHeight = scale * sourceHeight;
1441 float left = (newWidth - scaledWidth) / 2;
1442 float top = (newHeight - scaledHeight) / 2;
1443
1444 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1445 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1446 Canvas canvas = new Canvas(dest);
1447 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1448 if (source.isRecycled()) {
1449 source.recycle();
1450 }
1451 return dest;
1452 } catch (SecurityException e) {
1453 return null; // android 6.0 with revoked permissions for example
1454 } catch (FileNotFoundException e) {
1455 return null;
1456 } finally {
1457 close(is);
1458 }
1459 }
1460
1461 public Bitmap cropCenterSquare(Bitmap input, int size) {
1462 int w = input.getWidth();
1463 int h = input.getHeight();
1464
1465 float scale = Math.max((float) size / h, (float) size / w);
1466
1467 float outWidth = scale * w;
1468 float outHeight = scale * h;
1469 float left = (size - outWidth) / 2;
1470 float top = (size - outHeight) / 2;
1471 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1472
1473 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1474 Canvas canvas = new Canvas(output);
1475 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1476 if (!input.isRecycled()) {
1477 input.recycle();
1478 }
1479 return output;
1480 }
1481
1482 private int calcSampleSize(Uri image, int size)
1483 throws FileNotFoundException, SecurityException {
1484 final BitmapFactory.Options options = new BitmapFactory.Options();
1485 options.inJustDecodeBounds = true;
1486 final InputStream inputStream =
1487 mXmppConnectionService.getContentResolver().openInputStream(image);
1488 BitmapFactory.decodeStream(inputStream, null, options);
1489 close(inputStream);
1490 return calcSampleSize(options, size);
1491 }
1492
1493 public void updateFileParams(Message message) {
1494 updateFileParams(message, null);
1495 }
1496
1497 public void updateFileParams(final Message message, final String url) {
1498 final boolean encrypted =
1499 message.getEncryption() == Message.ENCRYPTION_PGP
1500 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED;
1501 final DownloadableFile file = getFile(message);
1502 final String mime = file.getMimeType();
1503 final boolean image =
1504 message.getType() == Message.TYPE_IMAGE
1505 || (mime != null && mime.startsWith("image/"));
1506 final boolean privateMessage = message.isPrivateMessage();
1507 final StringBuilder body = new StringBuilder();
1508 if (url != null) {
1509 body.append(url);
1510 }
1511 if (encrypted && !file.exists()) {
1512 Log.d(Config.LOGTAG, "skipping updateFileParams because file is encrypted");
1513 final DownloadableFile encryptedFile = getFile(message, false);
1514 body.append('|').append(encryptedFile.getSize());
1515 } else {
1516 Log.d(Config.LOGTAG, "running updateFileParams");
1517 final boolean ambiguous = MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime);
1518 final boolean video = mime != null && mime.startsWith("video/");
1519 final boolean audio = mime != null && mime.startsWith("audio/");
1520 final boolean pdf = "application/pdf".equals(mime);
1521 body.append('|').append(file.getSize());
1522 if (ambiguous) {
1523 try {
1524 final Dimensions dimensions = getVideoDimensions(file);
1525 if (dimensions.valid()) {
1526 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is video");
1527 body.append('|')
1528 .append(dimensions.width)
1529 .append('|')
1530 .append(dimensions.height);
1531 } else {
1532 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1533 body.append("|0|0|").append(getMediaRuntime(file));
1534 }
1535 } catch (final IOException | NotAVideoFile e) {
1536 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1537 body.append("|0|0|").append(getMediaRuntime(file));
1538 }
1539 } else if (image || video || pdf) {
1540 try {
1541 final Dimensions dimensions;
1542 if (video) {
1543 dimensions = getVideoDimensions(file);
1544 } else if (pdf) {
1545 dimensions = getPdfDocumentDimensions(file);
1546 } else {
1547 dimensions = getImageDimensions(file);
1548 }
1549 if (dimensions.valid()) {
1550 body.append('|')
1551 .append(dimensions.width)
1552 .append('|')
1553 .append(dimensions.height);
1554 }
1555 } catch (final IOException | NotAVideoFile notAVideoFile) {
1556 Log.d(
1557 Config.LOGTAG,
1558 "file with mime type " + file.getMimeType() + " was not a video file");
1559 // fall threw
1560 }
1561 } else if (audio) {
1562 body.append("|0|0|").append(getMediaRuntime(file));
1563 }
1564 }
1565 message.setBody(body.toString());
1566 message.setDeleted(false);
1567 message.setType(
1568 privateMessage
1569 ? Message.TYPE_PRIVATE_FILE
1570 : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1571 }
1572
1573 private int getMediaRuntime(final File file) {
1574 try {
1575 final MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1576 mediaMetadataRetriever.setDataSource(file.toString());
1577 final String value =
1578 mediaMetadataRetriever.extractMetadata(
1579 MediaMetadataRetriever.METADATA_KEY_DURATION);
1580 if (Strings.isNullOrEmpty(value)) {
1581 return 0;
1582 }
1583 return Integer.parseInt(value);
1584 } catch (final Exception e) {
1585 return 0;
1586 }
1587 }
1588
1589 private Dimensions getImageDimensions(File file) {
1590 final BitmapFactory.Options options = new BitmapFactory.Options();
1591 options.inJustDecodeBounds = true;
1592 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1593 final int rotation = getRotation(file);
1594 final boolean rotated = rotation == 90 || rotation == 270;
1595 final int imageHeight = rotated ? options.outWidth : options.outHeight;
1596 final int imageWidth = rotated ? options.outHeight : options.outWidth;
1597 return new Dimensions(imageHeight, imageWidth);
1598 }
1599
1600 private Dimensions getVideoDimensions(final File file) throws NotAVideoFile, IOException {
1601 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1602 try {
1603 metadataRetriever.setDataSource(file.getAbsolutePath());
1604 } catch (RuntimeException e) {
1605 throw new NotAVideoFile(e);
1606 }
1607 return getVideoDimensions(metadataRetriever);
1608 }
1609
1610 private Dimensions getPdfDocumentDimensions(final File file) {
1611 final ParcelFileDescriptor fileDescriptor;
1612 try {
1613 fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1614 if (fileDescriptor == null) {
1615 return new Dimensions(0, 0);
1616 }
1617 } catch (final FileNotFoundException e) {
1618 return new Dimensions(0, 0);
1619 }
1620 try {
1621 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1622 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1623 final int height = page.getHeight();
1624 final int width = page.getWidth();
1625 page.close();
1626 pdfRenderer.close();
1627 return scalePdfDimensions(new Dimensions(height, width));
1628 } catch (final IOException | SecurityException e) {
1629 Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1630 return new Dimensions(0, 0);
1631 }
1632 }
1633
1634 private Dimensions scalePdfDimensions(Dimensions in) {
1635 final DisplayMetrics displayMetrics =
1636 mXmppConnectionService.getResources().getDisplayMetrics();
1637 final int target = (int) (displayMetrics.density * 288);
1638 return scalePdfDimensions(in, target, true);
1639 }
1640
1641 private static Dimensions scalePdfDimensions(
1642 final Dimensions in, final int target, final boolean fit) {
1643 final int w, h;
1644 if (fit == (in.width <= in.height)) {
1645 w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1646 h = target;
1647 } else {
1648 w = target;
1649 h = Math.max((int) (in.height / ((double) in.width / target)), 1);
1650 }
1651 return new Dimensions(h, w);
1652 }
1653
1654 public Bitmap getAvatar(String avatar, int size) {
1655 if (avatar == null) {
1656 return null;
1657 }
1658 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1659 return bm;
1660 }
1661
1662 private static class Dimensions {
1663 public final int width;
1664 public final int height;
1665
1666 Dimensions(int height, int width) {
1667 this.width = width;
1668 this.height = height;
1669 }
1670
1671 public int getMin() {
1672 return Math.min(width, height);
1673 }
1674
1675 public boolean valid() {
1676 return width > 0 && height > 0;
1677 }
1678 }
1679
1680 private static class NotAVideoFile extends Exception {
1681 public NotAVideoFile(Throwable t) {
1682 super(t);
1683 }
1684
1685 public NotAVideoFile() {
1686 super();
1687 }
1688 }
1689
1690 public static class ImageCompressionException extends Exception {
1691
1692 ImageCompressionException(String message) {
1693 super(message);
1694 }
1695 }
1696
1697 public static class FileCopyException extends Exception {
1698 private final int resId;
1699
1700 private FileCopyException(@StringRes int resId) {
1701 this.resId = resId;
1702 }
1703
1704 public @StringRes int getResId() {
1705 return resId;
1706 }
1707 }
1708}