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