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