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