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