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