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