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