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 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 (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
361 return false;
362 } finally {
363 close(os);
364 }
365 }
366 avatar.size = file.length();
367 return true;
368 }
369
370 public String getAvatarPath(String avatar) {
371 return mXmppConnectionService.getFilesDir().getAbsolutePath()+ "/avatars/" + avatar;
372 }
373
374 public Uri getAvatarUri(String avatar) {
375 return Uri.parse("file:" + getAvatarPath(avatar));
376 }
377
378 public Bitmap cropCenterSquare(Uri image, int size) {
379 if (image == null) {
380 return null;
381 }
382 InputStream is = null;
383 try {
384 BitmapFactory.Options options = new BitmapFactory.Options();
385 options.inSampleSize = calcSampleSize(image, size);
386 is = mXmppConnectionService.getContentResolver().openInputStream(image);
387 if (is == null) {
388 return null;
389 }
390 Bitmap input = BitmapFactory.decodeStream(is, null, options);
391 if (input == null) {
392 return null;
393 } else {
394 int rotation = getRotation(image);
395 if (rotation > 0) {
396 input = rotate(input, rotation);
397 }
398 return cropCenterSquare(input, size);
399 }
400 } catch (FileNotFoundException e) {
401 return null;
402 } finally {
403 close(is);
404 }
405 }
406
407 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
408 if (image == null) {
409 return null;
410 }
411 InputStream is = null;
412 try {
413 BitmapFactory.Options options = new BitmapFactory.Options();
414 options.inSampleSize = calcSampleSize(image,Math.max(newHeight, newWidth));
415 is = mXmppConnectionService.getContentResolver().openInputStream(image);
416 if (is == null) {
417 return null;
418 }
419 Bitmap source = BitmapFactory.decodeStream(is, null, options);
420 if (source == null) {
421 return null;
422 }
423 int sourceWidth = source.getWidth();
424 int sourceHeight = source.getHeight();
425 float xScale = (float) newWidth / sourceWidth;
426 float yScale = (float) newHeight / sourceHeight;
427 float scale = Math.max(xScale, yScale);
428 float scaledWidth = scale * sourceWidth;
429 float scaledHeight = scale * sourceHeight;
430 float left = (newWidth - scaledWidth) / 2;
431 float top = (newHeight - scaledHeight) / 2;
432
433 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
434 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
435 Canvas canvas = new Canvas(dest);
436 canvas.drawBitmap(source, null, targetRect, null);
437 return dest;
438 } catch (FileNotFoundException e) {
439 return null;
440 } finally {
441 close(is);
442 }
443 }
444
445 public Bitmap cropCenterSquare(Bitmap input, int size) {
446 int w = input.getWidth();
447 int h = input.getHeight();
448
449 float scale = Math.max((float) size / h, (float) size / w);
450
451 float outWidth = scale * w;
452 float outHeight = scale * h;
453 float left = (size - outWidth) / 2;
454 float top = (size - outHeight) / 2;
455 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
456
457 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
458 Canvas canvas = new Canvas(output);
459 canvas.drawBitmap(input, null, target, null);
460 return output;
461 }
462
463 private int calcSampleSize(Uri image, int size) throws FileNotFoundException {
464 BitmapFactory.Options options = new BitmapFactory.Options();
465 options.inJustDecodeBounds = true;
466 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
467 return calcSampleSize(options, size);
468 }
469
470 private int calcSampleSize(File image, int size) {
471 BitmapFactory.Options options = new BitmapFactory.Options();
472 options.inJustDecodeBounds = true;
473 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
474 return calcSampleSize(options, size);
475 }
476
477 private int calcSampleSize(BitmapFactory.Options options, int size) {
478 int height = options.outHeight;
479 int width = options.outWidth;
480 int inSampleSize = 1;
481
482 if (height > size || width > size) {
483 int halfHeight = height / 2;
484 int halfWidth = width / 2;
485
486 while ((halfHeight / inSampleSize) > size
487 && (halfWidth / inSampleSize) > size) {
488 inSampleSize *= 2;
489 }
490 }
491 return inSampleSize;
492 }
493
494 public Uri getJingleFileUri(Message message) {
495 File file = getFile(message);
496 return Uri.parse("file://" + file.getAbsolutePath());
497 }
498
499 public void updateFileParams(Message message) {
500 updateFileParams(message,null);
501 }
502
503 public void updateFileParams(Message message, URL url) {
504 DownloadableFile file = getFile(message);
505 if (message.getType() == Message.TYPE_IMAGE || file.getMimeType().startsWith("image/")) {
506 BitmapFactory.Options options = new BitmapFactory.Options();
507 options.inJustDecodeBounds = true;
508 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
509 int imageHeight = options.outHeight;
510 int imageWidth = options.outWidth;
511 if (url == null) {
512 message.setBody(Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
513 } else {
514 message.setBody(url.toString()+"|"+Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
515 }
516 } else {
517 if (url != null) {
518 message.setBody(url.toString()+"|"+Long.toString(file.getSize()));
519 } else {
520 message.setBody(Long.toString(file.getSize()));
521 }
522 }
523
524 }
525
526 public class FileCopyException extends Exception {
527 private static final long serialVersionUID = -1010013599132881427L;
528 private int resId;
529
530 public FileCopyException(int resId) {
531 this.resId = resId;
532 }
533
534 public int getResId() {
535 return resId;
536 }
537 }
538
539 public Bitmap getAvatar(String avatar, int size) {
540 if (avatar == null) {
541 return null;
542 }
543 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
544 if (bm == null) {
545 return null;
546 }
547 return bm;
548 }
549
550 public boolean isFileAvailable(Message message) {
551 return getFile(message).exists();
552 }
553
554 public static void close(Closeable stream) {
555 if (stream != null) {
556 try {
557 stream.close();
558 } catch (IOException e) {
559 }
560 }
561 }
562
563 public static void close(Socket socket) {
564 if (socket != null) {
565 try {
566 socket.close();
567 } catch (IOException e) {
568 }
569 }
570 }
571}