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