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