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