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