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