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