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","org.mozilla.fennec_fdroid");
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 return FileProvider.getUriForFile(context, getAuthority(context), file);
540 } catch (IllegalArgumentException e) {
541 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
542 throw new SecurityException(e);
543 } else {
544 return Uri.fromFile(file);
545 }
546 }
547 } else {
548 return Uri.fromFile(file);
549 }
550 }
551
552 public static String getAuthority(Context context) {
553 return context.getPackageName() + FILE_PROVIDER;
554 }
555
556 public static Uri getIndexableTakePhotoUri(Uri original) {
557 if (Config.ONLY_INTERNAL_STORAGE || "file".equals(original.getScheme())) {
558 return original;
559 } else {
560 List<String> segments = original.getPathSegments();
561 return Uri.parse("file://" + getTakePhotoPath() + segments.get(segments.size() - 1));
562 }
563 }
564
565 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
566 Bitmap bm = cropCenterSquare(image, size);
567 if (bm == null) {
568 return null;
569 }
570 if (hasAlpha(bm)) {
571 Log.d(Config.LOGTAG,"alpha in avatar detected; uploading as PNG");
572 bm.recycle();
573 bm = cropCenterSquare(image, 96);
574 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
575 }
576 return getPepAvatar(bm, format, 100);
577 }
578
579 private static boolean hasAlpha(final Bitmap bitmap) {
580 for(int x = 0; x < bitmap.getWidth(); ++x) {
581 for(int y = 0; y < bitmap.getWidth(); ++y) {
582 if (Color.alpha(bitmap.getPixel(x,y)) < 255) {
583 return true;
584 }
585 }
586 }
587 return false;
588 }
589
590 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
591 try {
592 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
593 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
594 MessageDigest digest = MessageDigest.getInstance("SHA-1");
595 DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest);
596 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
597 return null;
598 }
599 mDigestOutputStream.flush();
600 mDigestOutputStream.close();
601 long chars = mByteArrayOutputStream.size();
602 if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) {
603 int q = quality - 2;
604 Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q);
605 return getPepAvatar(bitmap, format, q);
606 }
607 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
608 final Avatar avatar = new Avatar();
609 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
610 avatar.image = new String(mByteArrayOutputStream.toByteArray());
611 if (format.equals(Bitmap.CompressFormat.WEBP)) {
612 avatar.type = "image/webp";
613 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
614 avatar.type = "image/jpeg";
615 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
616 avatar.type = "image/png";
617 }
618 avatar.width = bitmap.getWidth();
619 avatar.height = bitmap.getHeight();
620 return avatar;
621 } catch (Exception e) {
622 return null;
623 }
624 }
625
626 public Avatar getStoredPepAvatar(String hash) {
627 if (hash == null) {
628 return null;
629 }
630 Avatar avatar = new Avatar();
631 File file = new File(getAvatarPath(hash));
632 FileInputStream is = null;
633 try {
634 avatar.size = file.length();
635 BitmapFactory.Options options = new BitmapFactory.Options();
636 options.inJustDecodeBounds = true;
637 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
638 is = new FileInputStream(file);
639 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
640 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
641 MessageDigest digest = MessageDigest.getInstance("SHA-1");
642 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
643 byte[] buffer = new byte[4096];
644 int length;
645 while ((length = is.read(buffer)) > 0) {
646 os.write(buffer, 0, length);
647 }
648 os.flush();
649 os.close();
650 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
651 avatar.image = new String(mByteArrayOutputStream.toByteArray());
652 avatar.height = options.outHeight;
653 avatar.width = options.outWidth;
654 avatar.type = options.outMimeType;
655 return avatar;
656 } catch (NoSuchAlgorithmException | IOException e) {
657 return null;
658 } finally {
659 close(is);
660 }
661 }
662
663 public boolean isAvatarCached(Avatar avatar) {
664 File file = new File(getAvatarPath(avatar.getFilename()));
665 return file.exists();
666 }
667
668 public boolean save(final Avatar avatar) {
669 File file;
670 if (isAvatarCached(avatar)) {
671 file = new File(getAvatarPath(avatar.getFilename()));
672 avatar.size = file.length();
673 } else {
674 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath()+"/"+ UUID.randomUUID().toString());
675 file.getParentFile().mkdirs();
676 OutputStream os = null;
677 try {
678 file.createNewFile();
679 os = new FileOutputStream(file);
680 MessageDigest digest = MessageDigest.getInstance("SHA-1");
681 digest.reset();
682 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
683 final byte[] bytes = avatar.getImageAsBytes();
684 mDigestOutputStream.write(bytes);
685 mDigestOutputStream.flush();
686 mDigestOutputStream.close();
687 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
688 if (sha1sum.equals(avatar.sha1sum)) {
689 String filename = getAvatarPath(avatar.getFilename());
690 file.renameTo(new File(filename));
691 } else {
692 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
693 file.delete();
694 return false;
695 }
696 avatar.size = bytes.length;
697 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
698 return false;
699 } finally {
700 close(os);
701 }
702 }
703 return true;
704 }
705
706 private String getAvatarPath(String avatar) {
707 return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/avatars/" + avatar;
708 }
709
710 public Uri getAvatarUri(String avatar) {
711 return Uri.parse("file:" + getAvatarPath(avatar));
712 }
713
714 public Bitmap cropCenterSquare(Uri image, int size) {
715 if (image == null) {
716 return null;
717 }
718 InputStream is = null;
719 try {
720 BitmapFactory.Options options = new BitmapFactory.Options();
721 options.inSampleSize = calcSampleSize(image, size);
722 is = mXmppConnectionService.getContentResolver().openInputStream(image);
723 if (is == null) {
724 return null;
725 }
726 Bitmap input = BitmapFactory.decodeStream(is, null, options);
727 if (input == null) {
728 return null;
729 } else {
730 input = rotate(input, getRotation(image));
731 return cropCenterSquare(input, size);
732 }
733 } catch (FileNotFoundException | SecurityException e) {
734 return null;
735 } finally {
736 close(is);
737 }
738 }
739
740 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
741 if (image == null) {
742 return null;
743 }
744 InputStream is = null;
745 try {
746 BitmapFactory.Options options = new BitmapFactory.Options();
747 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
748 is = mXmppConnectionService.getContentResolver().openInputStream(image);
749 if (is == null) {
750 return null;
751 }
752 Bitmap source = BitmapFactory.decodeStream(is, null, options);
753 if (source == null) {
754 return null;
755 }
756 int sourceWidth = source.getWidth();
757 int sourceHeight = source.getHeight();
758 float xScale = (float) newWidth / sourceWidth;
759 float yScale = (float) newHeight / sourceHeight;
760 float scale = Math.max(xScale, yScale);
761 float scaledWidth = scale * sourceWidth;
762 float scaledHeight = scale * sourceHeight;
763 float left = (newWidth - scaledWidth) / 2;
764 float top = (newHeight - scaledHeight) / 2;
765
766 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
767 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
768 Canvas canvas = new Canvas(dest);
769 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
770 if (source.isRecycled()) {
771 source.recycle();
772 }
773 return dest;
774 } catch (SecurityException e) {
775 return null; //android 6.0 with revoked permissions for example
776 } catch (FileNotFoundException e) {
777 return null;
778 } finally {
779 close(is);
780 }
781 }
782
783 public Bitmap cropCenterSquare(Bitmap input, int size) {
784 int w = input.getWidth();
785 int h = input.getHeight();
786
787 float scale = Math.max((float) size / h, (float) size / w);
788
789 float outWidth = scale * w;
790 float outHeight = scale * h;
791 float left = (size - outWidth) / 2;
792 float top = (size - outHeight) / 2;
793 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
794
795 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
796 Canvas canvas = new Canvas(output);
797 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
798 if (!input.isRecycled()) {
799 input.recycle();
800 }
801 return output;
802 }
803
804 private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
805 BitmapFactory.Options options = new BitmapFactory.Options();
806 options.inJustDecodeBounds = true;
807 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
808 return calcSampleSize(options, size);
809 }
810
811 private static int calcSampleSize(File image, int size) {
812 BitmapFactory.Options options = new BitmapFactory.Options();
813 options.inJustDecodeBounds = true;
814 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
815 return calcSampleSize(options, size);
816 }
817
818 public static int calcSampleSize(BitmapFactory.Options options, int size) {
819 int height = options.outHeight;
820 int width = options.outWidth;
821 int inSampleSize = 1;
822
823 if (height > size || width > size) {
824 int halfHeight = height / 2;
825 int halfWidth = width / 2;
826
827 while ((halfHeight / inSampleSize) > size
828 && (halfWidth / inSampleSize) > size) {
829 inSampleSize *= 2;
830 }
831 }
832 return inSampleSize;
833 }
834
835 public void updateFileParams(Message message) {
836 updateFileParams(message, null);
837 }
838
839 public void updateFileParams(Message message, URL url) {
840 DownloadableFile file = getFile(message);
841 final String mime = file.getMimeType();
842 boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
843 boolean video = mime != null && mime.startsWith("video/");
844 boolean audio = mime != null && mime.startsWith("audio/");
845 final StringBuilder body = new StringBuilder();
846 if (url != null) {
847 body.append(url.toString());
848 }
849 body.append('|').append(file.getSize());
850 if (image || video) {
851 try {
852 Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
853 body.append('|').append(dimensions.width).append('|').append(dimensions.height);
854 } catch (NotAVideoFile notAVideoFile) {
855 Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file");
856 //fall threw
857 }
858 } else if (audio) {
859 body.append("|0|0|").append(getMediaRuntime(file));
860 }
861 message.setBody(body.toString());
862 }
863
864 public int getMediaRuntime(Uri uri) {
865 try {
866 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
867 mediaMetadataRetriever.setDataSource(mXmppConnectionService, uri);
868 return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
869 } catch (RuntimeException e) {
870 return 0;
871 }
872 }
873
874 private int getMediaRuntime(File file) {
875 try {
876 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
877 mediaMetadataRetriever.setDataSource(file.toString());
878 return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
879 } catch (RuntimeException e) {
880 return 0;
881 }
882 }
883
884 private Dimensions getImageDimensions(File file) {
885 BitmapFactory.Options options = new BitmapFactory.Options();
886 options.inJustDecodeBounds = true;
887 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
888 int rotation = getRotation(file);
889 boolean rotated = rotation == 90 || rotation == 270;
890 int imageHeight = rotated ? options.outWidth : options.outHeight;
891 int imageWidth = rotated ? options.outHeight : options.outWidth;
892 return new Dimensions(imageHeight, imageWidth);
893 }
894
895 private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
896 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
897 try {
898 metadataRetriever.setDataSource(file.getAbsolutePath());
899 } catch (RuntimeException e) {
900 throw new NotAVideoFile(e);
901 }
902 return getVideoDimensions(metadataRetriever);
903 }
904
905 private static Dimensions getVideoDimensions(Context context, Uri uri) throws NotAVideoFile {
906 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
907 try {
908 mediaMetadataRetriever.setDataSource(context, uri);
909 } catch (RuntimeException e) {
910 throw new NotAVideoFile(e);
911 }
912 return getVideoDimensions(mediaMetadataRetriever);
913 }
914
915 private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever) throws NotAVideoFile {
916 String hasVideo = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
917 if (hasVideo == null) {
918 throw new NotAVideoFile();
919 }
920 int rotation = extractRotationFromMediaRetriever(metadataRetriever);
921 boolean rotated = rotation == 90 || rotation == 270;
922 int height;
923 try {
924 String h = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
925 height = Integer.parseInt(h);
926 } catch (Exception e) {
927 height = -1;
928 }
929 int width;
930 try {
931 String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
932 width = Integer.parseInt(w);
933 } catch (Exception e) {
934 width = -1;
935 }
936 metadataRetriever.release();
937 Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
938 return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
939 }
940
941 private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
942 int rotation;
943 if (Build.VERSION.SDK_INT >= 17) {
944 String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
945 try {
946 rotation = Integer.parseInt(r);
947 } catch (Exception e) {
948 rotation = 0;
949 }
950 } else {
951 rotation = 0;
952 }
953 return rotation;
954 }
955
956 private static class Dimensions {
957 public final int width;
958 public final int height;
959
960 public Dimensions(int height, int width) {
961 this.width = width;
962 this.height = height;
963 }
964
965 public int getMin() {
966 return Math.min(width, height);
967 }
968 }
969
970 private static class NotAVideoFile extends Exception {
971 public NotAVideoFile(Throwable t) {
972 super(t);
973 }
974
975 public NotAVideoFile() {
976 super();
977 }
978 }
979
980 public class FileCopyException extends Exception {
981 private static final long serialVersionUID = -1010013599132881427L;
982 private int resId;
983
984 public FileCopyException(int resId) {
985 this.resId = resId;
986 }
987
988 public int getResId() {
989 return resId;
990 }
991 }
992
993 public Bitmap getAvatar(String avatar, int size) {
994 if (avatar == null) {
995 return null;
996 }
997 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
998 if (bm == null) {
999 return null;
1000 }
1001 return bm;
1002 }
1003
1004 public boolean isFileAvailable(Message message) {
1005 return getFile(message).exists();
1006 }
1007
1008 public static void close(Closeable stream) {
1009 if (stream != null) {
1010 try {
1011 stream.close();
1012 } catch (IOException e) {
1013 }
1014 }
1015 }
1016
1017 public static void close(Socket socket) {
1018 if (socket != null) {
1019 try {
1020 socket.close();
1021 } catch (IOException e) {
1022 }
1023 }
1024 }
1025
1026
1027 public static boolean weOwnFile(Context context, Uri uri) {
1028 if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
1029 return false;
1030 } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
1031 return fileIsInFilesDir(context, uri);
1032 } else {
1033 return weOwnFileLollipop(uri);
1034 }
1035 }
1036
1037
1038 /**
1039 * This is more than hacky but probably way better than doing nothing
1040 * Further 'optimizations' might contain to get the parents of CacheDir and NoBackupDir
1041 * and check against those as well
1042 */
1043 private static boolean fileIsInFilesDir(Context context, Uri uri) {
1044 try {
1045 final String haystack = context.getFilesDir().getParentFile().getCanonicalPath();
1046 final String needle = new File(uri.getPath()).getCanonicalPath();
1047 return needle.startsWith(haystack);
1048 } catch (IOException e) {
1049 return false;
1050 }
1051 }
1052
1053 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
1054 private static boolean weOwnFileLollipop(Uri uri) {
1055 try {
1056 File file = new File(uri.getPath());
1057 FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor();
1058 StructStat st = Os.fstat(fd);
1059 return st.st_uid == android.os.Process.myUid();
1060 } catch (FileNotFoundException e) {
1061 return false;
1062 } catch (Exception e) {
1063 return true;
1064 }
1065 }
1066}