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