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