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