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