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