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