1package eu.siacs.conversations.persistance;
2
3import android.graphics.Bitmap;
4import android.graphics.BitmapFactory;
5import android.graphics.Canvas;
6import android.graphics.Matrix;
7import android.graphics.RectF;
8import android.net.Uri;
9import android.os.Environment;
10import android.util.Base64;
11import android.util.Base64OutputStream;
12import android.util.Log;
13import android.webkit.MimeTypeMap;
14
15import java.io.ByteArrayOutputStream;
16import java.io.Closeable;
17import java.io.File;
18import java.io.FileNotFoundException;
19import java.io.FileOutputStream;
20import java.io.IOException;
21import java.io.InputStream;
22import java.io.OutputStream;
23import java.net.Socket;
24import java.net.URL;
25import java.security.DigestOutputStream;
26import java.security.MessageDigest;
27import java.security.NoSuchAlgorithmException;
28import java.text.SimpleDateFormat;
29import java.util.Arrays;
30import java.util.Date;
31import java.util.Locale;
32
33import eu.siacs.conversations.Config;
34import eu.siacs.conversations.R;
35import eu.siacs.conversations.entities.DownloadableFile;
36import eu.siacs.conversations.entities.Message;
37import eu.siacs.conversations.entities.Transferable;
38import eu.siacs.conversations.services.XmppConnectionService;
39import eu.siacs.conversations.utils.CryptoHelper;
40import eu.siacs.conversations.utils.ExifHelper;
41import eu.siacs.conversations.utils.FileUtils;
42import eu.siacs.conversations.xmpp.pep.Avatar;
43
44public class FileBackend {
45
46 private static int IMAGE_SIZE = 1920;
47
48 private final SimpleDateFormat imageDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.US);
49
50 private XmppConnectionService mXmppConnectionService;
51
52 public FileBackend(XmppConnectionService service) {
53 this.mXmppConnectionService = service;
54 }
55
56 public DownloadableFile getFile(Message message) {
57 return getFile(message, true);
58 }
59
60 public DownloadableFile getFile(Message message, boolean decrypted) {
61 final boolean encrypted = !decrypted
62 && (message.getEncryption() == Message.ENCRYPTION_PGP
63 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
64 if (encrypted) {
65 return new DownloadableFile(getConversationsFileDirectory()+message.getUuid()+".pgp");
66 } else {
67 String path = message.getRelativeFilePath();
68 if (path == null) {
69 path = message.getUuid();
70 } else if (path.startsWith("/")) {
71 return new DownloadableFile(path);
72 }
73 String mime = message.getMimeType();
74 if (mime != null && mime.startsWith("image")) {
75 return new DownloadableFile(getConversationsImageDirectory() + path);
76 } else {
77 return new DownloadableFile(getConversationsFileDirectory() + path);
78 }
79 }
80 }
81
82 public static String getConversationsFileDirectory() {
83 return Environment.getExternalStorageDirectory().getAbsolutePath()+"/Conversations/";
84 }
85
86 public static String getConversationsImageDirectory() {
87 return Environment.getExternalStoragePublicDirectory(
88 Environment.DIRECTORY_PICTURES).getAbsolutePath()
89 + "/Conversations/";
90 }
91
92 public Bitmap resize(Bitmap originalBitmap, int size) {
93 int w = originalBitmap.getWidth();
94 int h = originalBitmap.getHeight();
95 if (Math.max(w, h) > size) {
96 int scalledW;
97 int scalledH;
98 if (w <= h) {
99 scalledW = (int) (w / ((double) h / size));
100 scalledH = size;
101 } else {
102 scalledW = size;
103 scalledH = (int) (h / ((double) w / size));
104 }
105 Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
106 if (originalBitmap != null && !originalBitmap.isRecycled()) {
107 originalBitmap.recycle();
108 }
109 return result;
110 } else {
111 return originalBitmap;
112 }
113 }
114
115 public Bitmap rotate(Bitmap bitmap, int degree) {
116 int w = bitmap.getWidth();
117 int h = bitmap.getHeight();
118 Matrix mtx = new Matrix();
119 mtx.postRotate(degree);
120 Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
121 if (bitmap != null && !bitmap.isRecycled()) {
122 bitmap.recycle();
123 }
124 return result;
125 }
126
127 public boolean useImageAsIs(Uri uri) {
128 String path = getOriginalPath(uri);
129 if (path == null) {
130 return false;
131 }
132 File file = new File(path);
133 long size = file.length();
134 if (size == 0 || size >= 524288 ) {
135 return false;
136 }
137 BitmapFactory.Options options = new BitmapFactory.Options();
138 options.inJustDecodeBounds = true;
139 try {
140 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options);
141 if (options == null || options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
142 return false;
143 }
144 return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
145 } catch (FileNotFoundException e) {
146 return false;
147 }
148 }
149
150 public String getOriginalPath(Uri uri) {
151 Log.d(Config.LOGTAG,"get original path for uri: "+uri.toString());
152 return FileUtils.getPath(mXmppConnectionService,uri);
153 }
154
155 public DownloadableFile copyFileToPrivateStorage(Message message, Uri uri) throws FileCopyException {
156 Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage");
157 String mime = mXmppConnectionService.getContentResolver().getType(uri);
158 String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime);
159 message.setRelativeFilePath(message.getUuid() + "." + extension);
160 DownloadableFile file = mXmppConnectionService.getFileBackend().getFile(message);
161 file.getParentFile().mkdirs();
162 OutputStream os = null;
163 InputStream is = null;
164 try {
165 file.createNewFile();
166 os = new FileOutputStream(file);
167 is = mXmppConnectionService.getContentResolver().openInputStream(uri);
168 byte[] buffer = new byte[1024];
169 int length;
170 while ((length = is.read(buffer)) > 0) {
171 os.write(buffer, 0, length);
172 }
173 os.flush();
174 } catch(FileNotFoundException e) {
175 throw new FileCopyException(R.string.error_file_not_found);
176 } catch (IOException e) {
177 e.printStackTrace();
178 throw new FileCopyException(R.string.error_io_exception);
179 } finally {
180 close(os);
181 close(is);
182 }
183 Log.d(Config.LOGTAG, "output file name " + mXmppConnectionService.getFileBackend().getFile(message));
184 return file;
185 }
186
187 public DownloadableFile copyImageToPrivateStorage(Message message, Uri image)
188 throws FileCopyException {
189 return this.copyImageToPrivateStorage(message, image, 0);
190 }
191
192 private DownloadableFile copyImageToPrivateStorage(Message message,Uri image, int sampleSize) throws FileCopyException {
193 switch(Config.IMAGE_FORMAT) {
194 case JPEG:
195 message.setRelativeFilePath(message.getUuid()+".jpg");
196 break;
197 case PNG:
198 message.setRelativeFilePath(message.getUuid()+".png");
199 break;
200 case WEBP:
201 message.setRelativeFilePath(message.getUuid()+".webp");
202 break;
203 }
204 DownloadableFile file = getFile(message);
205 file.getParentFile().mkdirs();
206 InputStream is = null;
207 OutputStream os = null;
208 try {
209 file.createNewFile();
210 is = mXmppConnectionService.getContentResolver().openInputStream(image);
211 os = new FileOutputStream(file);
212
213 Bitmap originalBitmap;
214 BitmapFactory.Options options = new BitmapFactory.Options();
215 int inSampleSize = (int) Math.pow(2, sampleSize);
216 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
217 options.inSampleSize = inSampleSize;
218 originalBitmap = BitmapFactory.decodeStream(is, null, options);
219 is.close();
220 if (originalBitmap == null) {
221 throw new FileCopyException(R.string.error_not_an_image_file);
222 }
223 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
224 int rotation = getRotation(image);
225 if (rotation > 0) {
226 scaledBitmap = rotate(scaledBitmap, rotation);
227 }
228 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, Config.IMAGE_QUALITY, os);
229 if (!success) {
230 throw new FileCopyException(R.string.error_compressing_image);
231 }
232 os.flush();
233 long size = file.getSize();
234 int width = scaledBitmap.getWidth();
235 int height = scaledBitmap.getHeight();
236 message.setBody(Long.toString(size) + '|' + width + '|' + height);
237 return file;
238 } catch (FileNotFoundException e) {
239 throw new FileCopyException(R.string.error_file_not_found);
240 } catch (IOException e) {
241 e.printStackTrace();
242 throw new FileCopyException(R.string.error_io_exception);
243 } catch (SecurityException e) {
244 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
245 } catch (OutOfMemoryError e) {
246 ++sampleSize;
247 if (sampleSize <= 3) {
248 return copyImageToPrivateStorage(message, image, sampleSize);
249 } else {
250 throw new FileCopyException(R.string.error_out_of_memory);
251 }
252 } catch (NullPointerException e) {
253 throw new FileCopyException(R.string.error_io_exception);
254 } finally {
255 close(os);
256 close(is);
257 }
258 }
259
260 private int getRotation(File file) {
261 return getRotation(Uri.parse("file://"+file.getAbsolutePath()));
262 }
263
264 private int getRotation(Uri image) {
265 InputStream is = null;
266 try {
267 is = mXmppConnectionService.getContentResolver().openInputStream(image);
268 return ExifHelper.getOrientation(is);
269 } catch (FileNotFoundException e) {
270 return 0;
271 } finally {
272 close(is);
273 }
274 }
275
276 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly)
277 throws FileNotFoundException {
278 Bitmap thumbnail = mXmppConnectionService.getBitmapCache().get(message.getUuid());
279 if ((thumbnail == null) && (!cacheOnly)) {
280 File file = getFile(message);
281 BitmapFactory.Options options = new BitmapFactory.Options();
282 options.inSampleSize = calcSampleSize(file, size);
283 Bitmap fullsize = BitmapFactory.decodeFile(file.getAbsolutePath(),options);
284 if (fullsize == null) {
285 throw new FileNotFoundException();
286 }
287 thumbnail = resize(fullsize, size);
288 int rotation = getRotation(file);
289 if (rotation > 0) {
290 thumbnail = rotate(thumbnail, rotation);
291 }
292 this.mXmppConnectionService.getBitmapCache().put(message.getUuid(),thumbnail);
293 }
294 return thumbnail;
295 }
296
297 public Uri getTakePhotoUri() {
298 StringBuilder pathBuilder = new StringBuilder();
299 pathBuilder.append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
300 pathBuilder.append('/');
301 pathBuilder.append("Camera");
302 pathBuilder.append('/');
303 pathBuilder.append("IMG_" + this.imageDateFormat.format(new Date()) + ".jpg");
304 Uri uri = Uri.parse("file://" + pathBuilder.toString());
305 File file = new File(uri.toString());
306 file.getParentFile().mkdirs();
307 return uri;
308 }
309
310 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
311 try {
312 Avatar avatar = new Avatar();
313 Bitmap bm = cropCenterSquare(image, size);
314 if (bm == null) {
315 return null;
316 }
317 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
318 Base64OutputStream mBase64OutputSttream = new Base64OutputStream(
319 mByteArrayOutputStream, Base64.DEFAULT);
320 MessageDigest digest = MessageDigest.getInstance("SHA-1");
321 DigestOutputStream mDigestOutputStream = new DigestOutputStream(
322 mBase64OutputSttream, digest);
323 if (!bm.compress(format, 75, mDigestOutputStream)) {
324 return null;
325 }
326 mDigestOutputStream.flush();
327 mDigestOutputStream.close();
328 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
329 avatar.image = new String(mByteArrayOutputStream.toByteArray());
330 return avatar;
331 } catch (NoSuchAlgorithmException e) {
332 return null;
333 } catch (IOException e) {
334 return null;
335 }
336 }
337
338 public boolean isAvatarCached(Avatar avatar) {
339 File file = new File(getAvatarPath(avatar.getFilename()));
340 return file.exists();
341 }
342
343 public boolean save(Avatar avatar) {
344 File file;
345 if (isAvatarCached(avatar)) {
346 file = new File(getAvatarPath(avatar.getFilename()));
347 } else {
348 String filename = getAvatarPath(avatar.getFilename());
349 file = new File(filename + ".tmp");
350 file.getParentFile().mkdirs();
351 OutputStream os = null;
352 try {
353 file.createNewFile();
354 os = new FileOutputStream(file);
355 MessageDigest digest = MessageDigest.getInstance("SHA-1");
356 digest.reset();
357 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
358 mDigestOutputStream.write(avatar.getImageAsBytes());
359 mDigestOutputStream.flush();
360 mDigestOutputStream.close();
361 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
362 if (sha1sum.equals(avatar.sha1sum)) {
363 file.renameTo(new File(filename));
364 } else {
365 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
366 file.delete();
367 return false;
368 }
369 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
370 return false;
371 } finally {
372 close(os);
373 }
374 }
375 avatar.size = file.length();
376 return true;
377 }
378
379 public String getAvatarPath(String avatar) {
380 return mXmppConnectionService.getFilesDir().getAbsolutePath()+ "/avatars/" + avatar;
381 }
382
383 public Uri getAvatarUri(String avatar) {
384 return Uri.parse("file:" + getAvatarPath(avatar));
385 }
386
387 public Bitmap cropCenterSquare(Uri image, int size) {
388 if (image == null) {
389 return null;
390 }
391 InputStream is = null;
392 try {
393 BitmapFactory.Options options = new BitmapFactory.Options();
394 options.inSampleSize = calcSampleSize(image, size);
395 is = mXmppConnectionService.getContentResolver().openInputStream(image);
396 if (is == null) {
397 return null;
398 }
399 Bitmap input = BitmapFactory.decodeStream(is, null, options);
400 if (input == null) {
401 return null;
402 } else {
403 int rotation = getRotation(image);
404 if (rotation > 0) {
405 input = rotate(input, rotation);
406 }
407 return cropCenterSquare(input, size);
408 }
409 } catch (FileNotFoundException e) {
410 return null;
411 } finally {
412 close(is);
413 }
414 }
415
416 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
417 if (image == null) {
418 return null;
419 }
420 InputStream is = null;
421 try {
422 BitmapFactory.Options options = new BitmapFactory.Options();
423 options.inSampleSize = calcSampleSize(image,Math.max(newHeight, newWidth));
424 is = mXmppConnectionService.getContentResolver().openInputStream(image);
425 if (is == null) {
426 return null;
427 }
428 Bitmap source = BitmapFactory.decodeStream(is, null, options);
429 if (source == null) {
430 return null;
431 }
432 int sourceWidth = source.getWidth();
433 int sourceHeight = source.getHeight();
434 float xScale = (float) newWidth / sourceWidth;
435 float yScale = (float) newHeight / sourceHeight;
436 float scale = Math.max(xScale, yScale);
437 float scaledWidth = scale * sourceWidth;
438 float scaledHeight = scale * sourceHeight;
439 float left = (newWidth - scaledWidth) / 2;
440 float top = (newHeight - scaledHeight) / 2;
441
442 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
443 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
444 Canvas canvas = new Canvas(dest);
445 canvas.drawBitmap(source, null, targetRect, null);
446 if (source != null && !source.isRecycled()) {
447 source.recycle();
448 }
449 return dest;
450 } catch (FileNotFoundException e) {
451 return null;
452 } finally {
453 close(is);
454 }
455 }
456
457 public Bitmap cropCenterSquare(Bitmap input, int size) {
458 int w = input.getWidth();
459 int h = input.getHeight();
460
461 float scale = Math.max((float) size / h, (float) size / w);
462
463 float outWidth = scale * w;
464 float outHeight = scale * h;
465 float left = (size - outWidth) / 2;
466 float top = (size - outHeight) / 2;
467 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
468
469 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
470 Canvas canvas = new Canvas(output);
471 canvas.drawBitmap(input, null, target, null);
472 if (input != null && !input.isRecycled()) {
473 input.recycle();
474 }
475 return output;
476 }
477
478 private int calcSampleSize(Uri image, int size) throws FileNotFoundException {
479 BitmapFactory.Options options = new BitmapFactory.Options();
480 options.inJustDecodeBounds = true;
481 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
482 return calcSampleSize(options, size);
483 }
484
485 private int calcSampleSize(File image, int size) {
486 BitmapFactory.Options options = new BitmapFactory.Options();
487 options.inJustDecodeBounds = true;
488 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
489 return calcSampleSize(options, size);
490 }
491
492 private int calcSampleSize(BitmapFactory.Options options, int size) {
493 int height = options.outHeight;
494 int width = options.outWidth;
495 int inSampleSize = 1;
496
497 if (height > size || width > size) {
498 int halfHeight = height / 2;
499 int halfWidth = width / 2;
500
501 while ((halfHeight / inSampleSize) > size
502 && (halfWidth / inSampleSize) > size) {
503 inSampleSize *= 2;
504 }
505 }
506 return inSampleSize;
507 }
508
509 public Uri getJingleFileUri(Message message) {
510 File file = getFile(message);
511 return Uri.parse("file://" + file.getAbsolutePath());
512 }
513
514 public void updateFileParams(Message message) {
515 updateFileParams(message,null);
516 }
517
518 public void updateFileParams(Message message, URL url) {
519 DownloadableFile file = getFile(message);
520 if (message.getType() == Message.TYPE_IMAGE || file.getMimeType().startsWith("image/")) {
521 BitmapFactory.Options options = new BitmapFactory.Options();
522 options.inJustDecodeBounds = true;
523 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
524 int rotation = getRotation(file);
525 boolean rotated = rotation == 90 || rotation == 270;
526 int imageHeight = rotated ? options.outWidth : options.outHeight;
527 int imageWidth = rotated ? options.outHeight : options.outWidth;
528 if (url == null) {
529 message.setBody(Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
530 } else {
531 message.setBody(url.toString()+"|"+Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
532 }
533 } else {
534 if (url != null) {
535 message.setBody(url.toString()+"|"+Long.toString(file.getSize()));
536 } else {
537 message.setBody(Long.toString(file.getSize()));
538 }
539 }
540
541 }
542
543 public class FileCopyException extends Exception {
544 private static final long serialVersionUID = -1010013599132881427L;
545 private int resId;
546
547 public FileCopyException(int resId) {
548 this.resId = resId;
549 }
550
551 public int getResId() {
552 return resId;
553 }
554 }
555
556 public Bitmap getAvatar(String avatar, int size) {
557 if (avatar == null) {
558 return null;
559 }
560 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
561 if (bm == null) {
562 return null;
563 }
564 return bm;
565 }
566
567 public boolean isFileAvailable(Message message) {
568 return getFile(message).exists();
569 }
570
571 public static void close(Closeable stream) {
572 if (stream != null) {
573 try {
574 stream.close();
575 } catch (IOException e) {
576 }
577 }
578 }
579
580 public static void close(Socket socket) {
581 if (socket != null) {
582 try {
583 socket.close();
584 } catch (IOException e) {
585 }
586 }
587 }
588}