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