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