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