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