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 byte[] data;
1065 if (Arrays.asList(parts[0].split(";")).contains("base64")) {
1066 data = Base64.decode(parts[1], 0);
1067 } else {
1068 data = parts[1].getBytes("UTF-8");
1069 }
1070
1071 ImageDecoder.Source source = ImageDecoder.createSource(ByteBuffer.wrap(data));
1072 thumbnail = ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1073 int w = info.getSize().getWidth();
1074 int h = info.getSize().getHeight();
1075 Rect r = rectForSize(w, h, size);
1076 decoder.setTargetSize(r.width(), r.height());
1077 });
1078
1079 if (thumbnail != null) {
1080 cache.put(file.getAbsolutePath(), thumbnail);
1081 return thumbnail;
1082 }
1083 } else if (uri.getScheme().equals("cid")) {
1084 Cid cid = BobTransfer.cid(uri);
1085 if (cid == null) continue;
1086 DownloadableFile f = mXmppConnectionService.getFileForCid(cid);
1087 if (f != null && f.canRead()) {
1088 return getThumbnail(f, res, size, cacheOnly);
1089 }
1090 }
1091 }
1092 }
1093 }
1094 }
1095
1096 return getThumbnail(file, res, size, cacheOnly);
1097 }
1098
1099 public Drawable getThumbnail(DownloadableFile file, Resources res, int size, boolean cacheOnly) throws IOException {
1100 final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1101 Drawable thumbnail = cache.get(file.getAbsolutePath());
1102 if ((thumbnail == null) && (!cacheOnly)) {
1103 synchronized (THUMBNAIL_LOCK) {
1104 thumbnail = cache.get(file.getAbsolutePath());
1105 if (thumbnail != null) {
1106 return thumbnail;
1107 }
1108 final String mime = file.getMimeType();
1109 if ("application/pdf".equals(mime)) {
1110 thumbnail = new BitmapDrawable(res, getPdfDocumentPreview(file, size));
1111 } else if (mime.startsWith("video/")) {
1112 thumbnail = new BitmapDrawable(res, getVideoPreview(file, size));
1113 } else {
1114 thumbnail = getImagePreview(file, res, size, mime);
1115 if (thumbnail == null) {
1116 throw new FileNotFoundException();
1117 }
1118 }
1119 cache.put(file.getAbsolutePath(), thumbnail);
1120 }
1121 }
1122 return thumbnail;
1123 }
1124
1125 public Bitmap getThumbnailBitmap(Message message, Resources res, int size) throws IOException {
1126 final Drawable drawable = getThumbnail(message, res, size, false);
1127 if (drawable == null) return null;
1128 return drawDrawable(drawable);
1129 }
1130
1131 public static Rect rectForSize(int w, int h, int size) {
1132 int scalledW;
1133 int scalledH;
1134 if (w <= h) {
1135 scalledW = Math.max((int) (w / ((double) h / size)), 1);
1136 scalledH = size;
1137 } else {
1138 scalledW = size;
1139 scalledH = Math.max((int) (h / ((double) w / size)), 1);
1140 }
1141
1142 if (scalledW > w || scalledH > h) return new Rect(0, 0, w, h);
1143
1144 return new Rect(0, 0, scalledW, scalledH);
1145 }
1146
1147 private Drawable getImagePreview(File file, Resources res, int size, final String mime) throws IOException {
1148 if (android.os.Build.VERSION.SDK_INT >= 28) {
1149 ImageDecoder.Source source = ImageDecoder.createSource(file);
1150 return ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1151 int w = info.getSize().getWidth();
1152 int h = info.getSize().getHeight();
1153 Rect r = rectForSize(w, h, size);
1154 decoder.setTargetSize(r.width(), r.height());
1155 });
1156 } else {
1157 BitmapFactory.Options options = new BitmapFactory.Options();
1158 options.inSampleSize = calcSampleSize(file, size);
1159 Bitmap bitmap = null;
1160 try {
1161 bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1162 } catch (OutOfMemoryError e) {
1163 options.inSampleSize *= 2;
1164 bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1165 }
1166 if (bitmap == null) return null;
1167
1168 bitmap = resize(bitmap, size);
1169 bitmap = rotate(bitmap, getRotation(file));
1170 if (mime.equals("image/gif")) {
1171 Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
1172 drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
1173 bitmap.recycle();
1174 bitmap = withGifOverlay;
1175 }
1176 return new BitmapDrawable(res, bitmap);
1177 }
1178 }
1179
1180 protected Bitmap drawDrawable(Drawable drawable) {
1181 Bitmap bitmap = null;
1182
1183 if (drawable instanceof BitmapDrawable) {
1184 bitmap = ((BitmapDrawable) drawable).getBitmap();
1185 if (bitmap != null) return bitmap;
1186 }
1187
1188 bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
1189 Canvas canvas = new Canvas(bitmap);
1190 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1191 drawable.draw(canvas);
1192 return bitmap;
1193 }
1194
1195 private void drawOverlay(Bitmap bitmap, int resource, float factor) {
1196 Bitmap overlay =
1197 BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
1198 Canvas canvas = new Canvas(bitmap);
1199 float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
1200 Log.d(
1201 Config.LOGTAG,
1202 "target size overlay: "
1203 + targetSize
1204 + " overlay bitmap size was "
1205 + overlay.getHeight());
1206 float left = (canvas.getWidth() - targetSize) / 2.0f;
1207 float top = (canvas.getHeight() - targetSize) / 2.0f;
1208 RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
1209 canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
1210 }
1211
1212 /** https://stackoverflow.com/a/3943023/210897 */
1213 private boolean paintOverlayBlack(final Bitmap bitmap) {
1214 final int h = bitmap.getHeight();
1215 final int w = bitmap.getWidth();
1216 int record = 0;
1217 for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
1218 for (int x = Math.round(w * IGNORE_PADDING);
1219 x < w - Math.round(w * IGNORE_PADDING);
1220 ++x) {
1221 int pixel = bitmap.getPixel(x, y);
1222 if ((Color.red(pixel) * 0.299
1223 + Color.green(pixel) * 0.587
1224 + Color.blue(pixel) * 0.114)
1225 > 186) {
1226 --record;
1227 } else {
1228 ++record;
1229 }
1230 }
1231 }
1232 return record < 0;
1233 }
1234
1235 private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1236 final int h = bitmap.getHeight();
1237 final int w = bitmap.getWidth();
1238 int white = 0;
1239 for (int y = 0; y < h; ++y) {
1240 for (int x = 0; x < w; ++x) {
1241 int pixel = bitmap.getPixel(x, y);
1242 if ((Color.red(pixel) * 0.299
1243 + Color.green(pixel) * 0.587
1244 + Color.blue(pixel) * 0.114)
1245 > 186) {
1246 white++;
1247 }
1248 }
1249 }
1250 return white > (h * w * 0.4f);
1251 }
1252
1253 private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1254 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1255 Bitmap frame;
1256 try {
1257 metadataRetriever.setDataSource(mXmppConnectionService, uri);
1258 frame = metadataRetriever.getFrameAtTime(0);
1259 metadataRetriever.release();
1260 return cropCenterSquare(frame, size);
1261 } catch (Exception e) {
1262 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1263 frame.eraseColor(0xff000000);
1264 return frame;
1265 }
1266 }
1267
1268 private Bitmap getVideoPreview(final File file, final int size) {
1269 final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1270 Bitmap frame;
1271 try {
1272 metadataRetriever.setDataSource(file.getAbsolutePath());
1273 frame = metadataRetriever.getFrameAtTime(0);
1274 metadataRetriever.release();
1275 frame = resize(frame, size);
1276 } catch (IOException | RuntimeException e) {
1277 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1278 frame.eraseColor(0xff000000);
1279 }
1280 drawOverlay(
1281 frame,
1282 paintOverlayBlack(frame)
1283 ? R.drawable.play_video_black
1284 : R.drawable.play_video_white,
1285 0.75f);
1286 return frame;
1287 }
1288
1289 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1290 private Bitmap getPdfDocumentPreview(final File file, final int size) {
1291 try {
1292 final ParcelFileDescriptor fileDescriptor =
1293 ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1294 final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1295 drawOverlay(
1296 rendered,
1297 paintOverlayBlackPdf(rendered)
1298 ? R.drawable.open_pdf_black
1299 : R.drawable.open_pdf_white,
1300 0.75f);
1301 return rendered;
1302 } catch (final IOException | SecurityException e) {
1303 Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1304 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1305 placeholder.eraseColor(0xff000000);
1306 return placeholder;
1307 }
1308 }
1309
1310 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1311 private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1312 try {
1313 ParcelFileDescriptor fileDescriptor =
1314 mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1315 final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1316 return cropCenterSquare(bitmap, size);
1317 } catch (Exception e) {
1318 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1319 placeholder.eraseColor(0xff000000);
1320 return placeholder;
1321 }
1322 }
1323
1324 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1325 private Bitmap renderPdfDocument(
1326 ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1327 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1328 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1329 final Dimensions dimensions =
1330 scalePdfDimensions(
1331 new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1332 final Bitmap rendered =
1333 Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1334 rendered.eraseColor(0xffffffff);
1335 page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1336 page.close();
1337 pdfRenderer.close();
1338 fileDescriptor.close();
1339 return rendered;
1340 }
1341
1342 public Uri getTakePhotoUri() {
1343 final String filename =
1344 String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1345 final File directory;
1346 if (Config.ONLY_INTERNAL_STORAGE) {
1347 directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1348 } else {
1349 directory =
1350 new File(
1351 Environment.getExternalStoragePublicDirectory(
1352 Environment.DIRECTORY_DCIM),
1353 "Camera");
1354 }
1355 final File file = new File(directory, filename);
1356 file.getParentFile().mkdirs();
1357 return getUriForFile(mXmppConnectionService, file);
1358 }
1359
1360 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
1361
1362 final Avatar uncompressAvatar = getUncompressedAvatar(image);
1363 if (uncompressAvatar != null
1364 && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
1365 return uncompressAvatar;
1366 }
1367 if (uncompressAvatar != null) {
1368 Log.d(
1369 Config.LOGTAG,
1370 "uncompressed avatar exceeded char limit by "
1371 + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
1372 }
1373
1374 Bitmap bm = cropCenterSquare(image, size);
1375 if (bm == null) {
1376 return null;
1377 }
1378 if (hasAlpha(bm)) {
1379 Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1380 bm.recycle();
1381 bm = cropCenterSquare(image, 96);
1382 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1383 }
1384 return getPepAvatar(bm, format, 100);
1385 }
1386
1387 private Avatar getUncompressedAvatar(Uri uri) {
1388 Bitmap bitmap = null;
1389 try {
1390 bitmap =
1391 BitmapFactory.decodeStream(
1392 mXmppConnectionService.getContentResolver().openInputStream(uri));
1393 return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
1394 } catch (Exception e) {
1395 return null;
1396 } finally {
1397 if (bitmap != null) {
1398 bitmap.recycle();
1399 }
1400 }
1401 }
1402
1403 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1404 try {
1405 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1406 Base64OutputStream mBase64OutputStream =
1407 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1408 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1409 DigestOutputStream mDigestOutputStream =
1410 new DigestOutputStream(mBase64OutputStream, digest);
1411 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1412 return null;
1413 }
1414 mDigestOutputStream.flush();
1415 mDigestOutputStream.close();
1416 long chars = mByteArrayOutputStream.size();
1417 if (format != Bitmap.CompressFormat.PNG
1418 && quality >= 50
1419 && chars >= Config.AVATAR_CHAR_LIMIT) {
1420 int q = quality - 2;
1421 Log.d(
1422 Config.LOGTAG,
1423 "avatar char length was " + chars + " reducing quality to " + q);
1424 return getPepAvatar(bitmap, format, q);
1425 }
1426 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1427 final Avatar avatar = new Avatar();
1428 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1429 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1430 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1431 avatar.type = "image/webp";
1432 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1433 avatar.type = "image/jpeg";
1434 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1435 avatar.type = "image/png";
1436 }
1437 avatar.width = bitmap.getWidth();
1438 avatar.height = bitmap.getHeight();
1439 return avatar;
1440 } catch (OutOfMemoryError e) {
1441 Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1442 return null;
1443 } catch (Exception e) {
1444 return null;
1445 }
1446 }
1447
1448 public Avatar getStoredPepAvatar(String hash) {
1449 if (hash == null) {
1450 return null;
1451 }
1452 Avatar avatar = new Avatar();
1453 final File file = getAvatarFile(hash);
1454 FileInputStream is = null;
1455 try {
1456 avatar.size = file.length();
1457 BitmapFactory.Options options = new BitmapFactory.Options();
1458 options.inJustDecodeBounds = true;
1459 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1460 is = new FileInputStream(file);
1461 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1462 Base64OutputStream mBase64OutputStream =
1463 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1464 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1465 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1466 byte[] buffer = new byte[4096];
1467 int length;
1468 while ((length = is.read(buffer)) > 0) {
1469 os.write(buffer, 0, length);
1470 }
1471 os.flush();
1472 os.close();
1473 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1474 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1475 avatar.height = options.outHeight;
1476 avatar.width = options.outWidth;
1477 avatar.type = options.outMimeType;
1478 return avatar;
1479 } catch (NoSuchAlgorithmException | IOException e) {
1480 return null;
1481 } finally {
1482 close(is);
1483 }
1484 }
1485
1486 public boolean isAvatarCached(Avatar avatar) {
1487 final File file = getAvatarFile(avatar.getFilename());
1488 return file.exists();
1489 }
1490
1491 public boolean save(final Avatar avatar) {
1492 File file;
1493 if (isAvatarCached(avatar)) {
1494 file = getAvatarFile(avatar.getFilename());
1495 avatar.size = file.length();
1496 } else {
1497 file =
1498 new File(
1499 mXmppConnectionService.getCacheDir().getAbsolutePath()
1500 + "/"
1501 + UUID.randomUUID().toString());
1502 if (file.getParentFile().mkdirs()) {
1503 Log.d(Config.LOGTAG, "created cache directory");
1504 }
1505 OutputStream os = null;
1506 try {
1507 if (!file.createNewFile()) {
1508 Log.d(
1509 Config.LOGTAG,
1510 "unable to create temporary file " + file.getAbsolutePath());
1511 }
1512 os = new FileOutputStream(file);
1513 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1514 digest.reset();
1515 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1516 final byte[] bytes = avatar.getImageAsBytes();
1517 mDigestOutputStream.write(bytes);
1518 mDigestOutputStream.flush();
1519 mDigestOutputStream.close();
1520 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1521 if (sha1sum.equals(avatar.sha1sum)) {
1522 final File outputFile = getAvatarFile(avatar.getFilename());
1523 if (outputFile.getParentFile().mkdirs()) {
1524 Log.d(Config.LOGTAG, "created avatar directory");
1525 }
1526 final File avatarFile = getAvatarFile(avatar.getFilename());
1527 if (!file.renameTo(avatarFile)) {
1528 Log.d(
1529 Config.LOGTAG,
1530 "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1531 return false;
1532 }
1533 } else {
1534 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1535 if (!file.delete()) {
1536 Log.d(Config.LOGTAG, "unable to delete temporary file");
1537 }
1538 return false;
1539 }
1540 avatar.size = bytes.length;
1541 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1542 return false;
1543 } finally {
1544 close(os);
1545 }
1546 }
1547 return true;
1548 }
1549
1550 public void deleteHistoricAvatarPath() {
1551 delete(getHistoricAvatarPath());
1552 }
1553
1554 private void delete(final File file) {
1555 if (file.isDirectory()) {
1556 final File[] files = file.listFiles();
1557 if (files != null) {
1558 for (final File f : files) {
1559 delete(f);
1560 }
1561 }
1562 }
1563 if (file.delete()) {
1564 Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1565 }
1566 }
1567
1568 private File getHistoricAvatarPath() {
1569 return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1570 }
1571
1572 private File getAvatarFile(String avatar) {
1573 return new File(mXmppConnectionService.getCacheDir(), "/avatars/" + avatar);
1574 }
1575
1576 public Uri getAvatarUri(String avatar) {
1577 return Uri.fromFile(getAvatarFile(avatar));
1578 }
1579
1580 public Bitmap cropCenterSquare(Uri image, int size) {
1581 if (image == null) {
1582 return null;
1583 }
1584 InputStream is = null;
1585 try {
1586 BitmapFactory.Options options = new BitmapFactory.Options();
1587 options.inSampleSize = calcSampleSize(image, size);
1588 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1589 if (is == null) {
1590 return null;
1591 }
1592 Bitmap input = BitmapFactory.decodeStream(is, null, options);
1593 if (input == null) {
1594 return null;
1595 } else {
1596 input = rotate(input, getRotation(image));
1597 return cropCenterSquare(input, size);
1598 }
1599 } catch (FileNotFoundException | SecurityException e) {
1600 Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1601 return null;
1602 } finally {
1603 close(is);
1604 }
1605 }
1606
1607 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1608 if (image == null) {
1609 return null;
1610 }
1611 InputStream is = null;
1612 try {
1613 BitmapFactory.Options options = new BitmapFactory.Options();
1614 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1615 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1616 if (is == null) {
1617 return null;
1618 }
1619 Bitmap source = BitmapFactory.decodeStream(is, null, options);
1620 if (source == null) {
1621 return null;
1622 }
1623 int sourceWidth = source.getWidth();
1624 int sourceHeight = source.getHeight();
1625 float xScale = (float) newWidth / sourceWidth;
1626 float yScale = (float) newHeight / sourceHeight;
1627 float scale = Math.max(xScale, yScale);
1628 float scaledWidth = scale * sourceWidth;
1629 float scaledHeight = scale * sourceHeight;
1630 float left = (newWidth - scaledWidth) / 2;
1631 float top = (newHeight - scaledHeight) / 2;
1632
1633 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1634 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1635 Canvas canvas = new Canvas(dest);
1636 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1637 if (source.isRecycled()) {
1638 source.recycle();
1639 }
1640 return dest;
1641 } catch (SecurityException e) {
1642 return null; // android 6.0 with revoked permissions for example
1643 } catch (FileNotFoundException e) {
1644 return null;
1645 } finally {
1646 close(is);
1647 }
1648 }
1649
1650 public Bitmap cropCenterSquare(Bitmap input, int size) {
1651 int w = input.getWidth();
1652 int h = input.getHeight();
1653
1654 float scale = Math.max((float) size / h, (float) size / w);
1655
1656 float outWidth = scale * w;
1657 float outHeight = scale * h;
1658 float left = (size - outWidth) / 2;
1659 float top = (size - outHeight) / 2;
1660 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1661
1662 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1663 Canvas canvas = new Canvas(output);
1664 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1665 if (!input.isRecycled()) {
1666 input.recycle();
1667 }
1668 return output;
1669 }
1670
1671 private int calcSampleSize(Uri image, int size)
1672 throws FileNotFoundException, SecurityException {
1673 final BitmapFactory.Options options = new BitmapFactory.Options();
1674 options.inJustDecodeBounds = true;
1675 final InputStream inputStream =
1676 mXmppConnectionService.getContentResolver().openInputStream(image);
1677 BitmapFactory.decodeStream(inputStream, null, options);
1678 close(inputStream);
1679 return calcSampleSize(options, size);
1680 }
1681
1682 public void updateFileParams(Message message) {
1683 updateFileParams(message, null);
1684 }
1685
1686 public void updateFileParams(final Message message, final String url) {
1687 updateFileParams(message, url, true);
1688 }
1689
1690 public void updateFileParams(final Message message, final String url, boolean updateCids) {
1691 final boolean encrypted =
1692 message.getEncryption() == Message.ENCRYPTION_PGP
1693 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED;
1694 final DownloadableFile file = getFile(message);
1695 final String mime = file.getMimeType();
1696 final boolean privateMessage = message.isPrivateMessage();
1697 final boolean image =
1698 message.getType() == Message.TYPE_IMAGE
1699 || (mime != null && mime.startsWith("image/"));
1700 Message.FileParams fileParams = message.getFileParams();
1701 if (fileParams == null) fileParams = new Message.FileParams();
1702 if (url != null) {
1703 fileParams.url = url;
1704 }
1705 if (encrypted && !file.exists()) {
1706 Log.d(Config.LOGTAG, "skipping updateFileParams because file is encrypted");
1707 final DownloadableFile encryptedFile = getFile(message, false);
1708 fileParams.size = encryptedFile.getSize();
1709 } else {
1710 Log.d(Config.LOGTAG, "running updateFileParams");
1711 final boolean ambiguous = MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime);
1712 final boolean video = mime != null && mime.startsWith("video/");
1713 final boolean audio = mime != null && mime.startsWith("audio/");
1714 final boolean pdf = "application/pdf".equals(mime);
1715 fileParams.size = file.getSize();
1716 if (ambiguous) {
1717 try {
1718 final Dimensions dimensions = getVideoDimensions(file);
1719 if (dimensions.valid()) {
1720 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is video");
1721 fileParams.width = dimensions.width;
1722 fileParams.height = dimensions.height;
1723 } else {
1724 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1725 fileParams.runtime = getMediaRuntime(file);
1726 }
1727 } catch (final NotAVideoFile e) {
1728 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1729 fileParams.runtime = getMediaRuntime(file);
1730 }
1731 } else if (image || video || pdf) {
1732 try {
1733 final Dimensions dimensions;
1734 if (video) {
1735 dimensions = getVideoDimensions(file);
1736 } else if (pdf) {
1737 dimensions = getPdfDocumentDimensions(file);
1738 } else {
1739 dimensions = getImageDimensions(file);
1740 }
1741 if (dimensions.valid()) {
1742 fileParams.width = dimensions.width;
1743 fileParams.height = dimensions.height;
1744 }
1745 } catch (NotAVideoFile notAVideoFile) {
1746 Log.d(
1747 Config.LOGTAG,
1748 "file with mime type " + file.getMimeType() + " was not a video file");
1749 // fall threw
1750 }
1751 } else if (audio) {
1752 fileParams.runtime = getMediaRuntime(file);
1753 }
1754 }
1755 message.setFileParams(fileParams);
1756 message.setDeleted(false);
1757 message.setType(
1758 privateMessage
1759 ? Message.TYPE_PRIVATE_FILE
1760 : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1761
1762 if (updateCids) {
1763 try {
1764 Cid[] cids = calculateCids(new FileInputStream(getFile(message)));
1765 for (int i = 0; i < cids.length; i++) {
1766 mXmppConnectionService.saveCid(cids[i], file);
1767 }
1768 } catch (final IOException e) { }
1769 }
1770 }
1771
1772 private int getMediaRuntime(final File file) {
1773 try {
1774 final MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1775 mediaMetadataRetriever.setDataSource(file.toString());
1776 final String value =
1777 mediaMetadataRetriever.extractMetadata(
1778 MediaMetadataRetriever.METADATA_KEY_DURATION);
1779 if (Strings.isNullOrEmpty(value)) {
1780 return 0;
1781 }
1782 return Integer.parseInt(value);
1783 } catch (final Exception e) {
1784 return 0;
1785 }
1786 }
1787
1788 private Dimensions getImageDimensions(File file) {
1789 final BitmapFactory.Options options = new BitmapFactory.Options();
1790 options.inJustDecodeBounds = true;
1791 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1792 final int rotation = getRotation(file);
1793 final boolean rotated = rotation == 90 || rotation == 270;
1794 final int imageHeight = rotated ? options.outWidth : options.outHeight;
1795 final int imageWidth = rotated ? options.outHeight : options.outWidth;
1796 return new Dimensions(imageHeight, imageWidth);
1797 }
1798
1799 private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1800 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1801 try {
1802 metadataRetriever.setDataSource(file.getAbsolutePath());
1803 } catch (RuntimeException e) {
1804 throw new NotAVideoFile(e);
1805 }
1806 return getVideoDimensions(metadataRetriever);
1807 }
1808
1809 private Dimensions getPdfDocumentDimensions(final File file) {
1810 final ParcelFileDescriptor fileDescriptor;
1811 try {
1812 fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1813 if (fileDescriptor == null) {
1814 return new Dimensions(0, 0);
1815 }
1816 } catch (final FileNotFoundException e) {
1817 return new Dimensions(0, 0);
1818 }
1819 try {
1820 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1821 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1822 final int height = page.getHeight();
1823 final int width = page.getWidth();
1824 page.close();
1825 pdfRenderer.close();
1826 return scalePdfDimensions(new Dimensions(height, width));
1827 } catch (final IOException | SecurityException e) {
1828 Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1829 return new Dimensions(0, 0);
1830 }
1831 }
1832
1833 private Dimensions scalePdfDimensions(Dimensions in) {
1834 final DisplayMetrics displayMetrics =
1835 mXmppConnectionService.getResources().getDisplayMetrics();
1836 final int target = (int) (displayMetrics.density * 288);
1837 return scalePdfDimensions(in, target, true);
1838 }
1839
1840 private static Dimensions scalePdfDimensions(
1841 final Dimensions in, final int target, final boolean fit) {
1842 final int w, h;
1843 if (fit == (in.width <= in.height)) {
1844 w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1845 h = target;
1846 } else {
1847 w = target;
1848 h = Math.max((int) (in.height / ((double) in.width / target)), 1);
1849 }
1850 return new Dimensions(h, w);
1851 }
1852
1853 public Bitmap getAvatar(String avatar, int size) {
1854 if (avatar == null) {
1855 return null;
1856 }
1857 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1858 return bm;
1859 }
1860
1861 private static class Dimensions {
1862 public final int width;
1863 public final int height;
1864
1865 Dimensions(int height, int width) {
1866 this.width = width;
1867 this.height = height;
1868 }
1869
1870 public int getMin() {
1871 return Math.min(width, height);
1872 }
1873
1874 public boolean valid() {
1875 return width > 0 && height > 0;
1876 }
1877 }
1878
1879 private static class NotAVideoFile extends Exception {
1880 public NotAVideoFile(Throwable t) {
1881 super(t);
1882 }
1883
1884 public NotAVideoFile() {
1885 super();
1886 }
1887 }
1888
1889 public static class ImageCompressionException extends Exception {
1890
1891 ImageCompressionException(String message) {
1892 super(message);
1893 }
1894 }
1895
1896 public static class FileCopyException extends Exception {
1897 private final int resId;
1898
1899 private FileCopyException(@StringRes int resId) {
1900 this.resId = resId;
1901 }
1902
1903 public @StringRes int getResId() {
1904 return resId;
1905 }
1906 }
1907}