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