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