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