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