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