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 } finally {
239 close(os);
240 close(is);
241 }
242 }
243
244 private int getRotation(Uri image) {
245 InputStream is = null;
246 try {
247 is = mXmppConnectionService.getContentResolver().openInputStream(image);
248 return ExifHelper.getOrientation(is);
249 } catch (FileNotFoundException e) {
250 return 0;
251 } finally {
252 close(is);
253 }
254 }
255
256 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly)
257 throws FileNotFoundException {
258 Bitmap thumbnail = mXmppConnectionService.getBitmapCache().get(
259 message.getUuid());
260 if ((thumbnail == null) && (!cacheOnly)) {
261 File file = getFile(message);
262 BitmapFactory.Options options = new BitmapFactory.Options();
263 options.inSampleSize = calcSampleSize(file, size);
264 Bitmap fullsize = BitmapFactory.decodeFile(file.getAbsolutePath(),options);
265 if (fullsize == null) {
266 throw new FileNotFoundException();
267 }
268 thumbnail = resize(fullsize, size);
269 this.mXmppConnectionService.getBitmapCache().put(message.getUuid(),
270 thumbnail);
271 }
272 return thumbnail;
273 }
274
275 public Uri getTakePhotoUri() {
276 StringBuilder pathBuilder = new StringBuilder();
277 pathBuilder.append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
278 pathBuilder.append('/');
279 pathBuilder.append("Camera");
280 pathBuilder.append('/');
281 pathBuilder.append("IMG_" + this.imageDateFormat.format(new Date()) + ".jpg");
282 Uri uri = Uri.parse("file://" + pathBuilder.toString());
283 File file = new File(uri.toString());
284 file.getParentFile().mkdirs();
285 return uri;
286 }
287
288 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
289 try {
290 Avatar avatar = new Avatar();
291 Bitmap bm = cropCenterSquare(image, size);
292 if (bm == null) {
293 return null;
294 }
295 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
296 Base64OutputStream mBase64OutputSttream = new Base64OutputStream(
297 mByteArrayOutputStream, Base64.DEFAULT);
298 MessageDigest digest = MessageDigest.getInstance("SHA-1");
299 DigestOutputStream mDigestOutputStream = new DigestOutputStream(
300 mBase64OutputSttream, digest);
301 if (!bm.compress(format, 75, mDigestOutputStream)) {
302 return null;
303 }
304 mDigestOutputStream.flush();
305 mDigestOutputStream.close();
306 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
307 avatar.image = new String(mByteArrayOutputStream.toByteArray());
308 return avatar;
309 } catch (NoSuchAlgorithmException e) {
310 return null;
311 } catch (IOException e) {
312 return null;
313 }
314 }
315
316 public boolean isAvatarCached(Avatar avatar) {
317 File file = new File(getAvatarPath(avatar.getFilename()));
318 return file.exists();
319 }
320
321 public boolean save(Avatar avatar) {
322 File file;
323 if (isAvatarCached(avatar)) {
324 file = new File(getAvatarPath(avatar.getFilename()));
325 } else {
326 String filename = getAvatarPath(avatar.getFilename());
327 file = new File(filename + ".tmp");
328 file.getParentFile().mkdirs();
329 OutputStream os = null;
330 try {
331 file.createNewFile();
332 os = new FileOutputStream(file);
333 MessageDigest digest = MessageDigest.getInstance("SHA-1");
334 digest.reset();
335 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
336 mDigestOutputStream.write(avatar.getImageAsBytes());
337 mDigestOutputStream.flush();
338 mDigestOutputStream.close();
339 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
340 if (sha1sum.equals(avatar.sha1sum)) {
341 file.renameTo(new File(filename));
342 } else {
343 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
344 file.delete();
345 return false;
346 }
347 } catch (FileNotFoundException e) {
348 return false;
349 } catch (IOException e) {
350 return false;
351 } catch (NoSuchAlgorithmException e) {
352 return false;
353 } finally {
354 close(os);
355 }
356 }
357 avatar.size = file.length();
358 return true;
359 }
360
361 public String getAvatarPath(String avatar) {
362 return mXmppConnectionService.getFilesDir().getAbsolutePath()+ "/avatars/" + avatar;
363 }
364
365 public Uri getAvatarUri(String avatar) {
366 return Uri.parse("file:" + getAvatarPath(avatar));
367 }
368
369 public Bitmap cropCenterSquare(Uri image, int size) {
370 if (image == null) {
371 return null;
372 }
373 InputStream is = null;
374 try {
375 BitmapFactory.Options options = new BitmapFactory.Options();
376 options.inSampleSize = calcSampleSize(image, size);
377 is = mXmppConnectionService.getContentResolver().openInputStream(image);
378 Bitmap input = BitmapFactory.decodeStream(is, null, options);
379 if (input == null) {
380 return null;
381 } else {
382 int rotation = getRotation(image);
383 if (rotation > 0) {
384 input = rotate(input, rotation);
385 }
386 return cropCenterSquare(input, size);
387 }
388 } catch (FileNotFoundException e) {
389 return null;
390 } finally {
391 close(is);
392 }
393 }
394
395 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
396 if (image == null) {
397 return null;
398 }
399 InputStream is = null;
400 try {
401 BitmapFactory.Options options = new BitmapFactory.Options();
402 options.inSampleSize = calcSampleSize(image,Math.max(newHeight, newWidth));
403 is = mXmppConnectionService.getContentResolver().openInputStream(image);
404 Bitmap source = BitmapFactory.decodeStream(is, null, options);
405 if (source == null) {
406 return null;
407 }
408 int sourceWidth = source.getWidth();
409 int sourceHeight = source.getHeight();
410 float xScale = (float) newWidth / sourceWidth;
411 float yScale = (float) newHeight / sourceHeight;
412 float scale = Math.max(xScale, yScale);
413 float scaledWidth = scale * sourceWidth;
414 float scaledHeight = scale * sourceHeight;
415 float left = (newWidth - scaledWidth) / 2;
416 float top = (newHeight - scaledHeight) / 2;
417
418 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
419 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
420 Canvas canvas = new Canvas(dest);
421 canvas.drawBitmap(source, null, targetRect, null);
422 return dest;
423 } catch (FileNotFoundException e) {
424 return null;
425 } finally {
426 close(is);
427 }
428 }
429
430 public Bitmap cropCenterSquare(Bitmap input, int size) {
431 int w = input.getWidth();
432 int h = input.getHeight();
433
434 float scale = Math.max((float) size / h, (float) size / w);
435
436 float outWidth = scale * w;
437 float outHeight = scale * h;
438 float left = (size - outWidth) / 2;
439 float top = (size - outHeight) / 2;
440 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
441
442 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
443 Canvas canvas = new Canvas(output);
444 canvas.drawBitmap(input, null, target, null);
445 return output;
446 }
447
448 private int calcSampleSize(Uri image, int size) throws FileNotFoundException {
449 BitmapFactory.Options options = new BitmapFactory.Options();
450 options.inJustDecodeBounds = true;
451 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
452 return calcSampleSize(options, size);
453 }
454
455 private int calcSampleSize(File image, int size) {
456 BitmapFactory.Options options = new BitmapFactory.Options();
457 options.inJustDecodeBounds = true;
458 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
459 return calcSampleSize(options, size);
460 }
461
462 private int calcSampleSize(BitmapFactory.Options options, int size) {
463 int height = options.outHeight;
464 int width = options.outWidth;
465 int inSampleSize = 1;
466
467 if (height > size || width > size) {
468 int halfHeight = height / 2;
469 int halfWidth = width / 2;
470
471 while ((halfHeight / inSampleSize) > size
472 && (halfWidth / inSampleSize) > size) {
473 inSampleSize *= 2;
474 }
475 }
476 return inSampleSize;
477 }
478
479 public Uri getJingleFileUri(Message message) {
480 File file = getFile(message);
481 return Uri.parse("file://" + file.getAbsolutePath());
482 }
483
484 public void updateFileParams(Message message) {
485 updateFileParams(message,null);
486 }
487
488 public void updateFileParams(Message message, URL url) {
489 DownloadableFile file = getFile(message);
490 if (message.getType() == Message.TYPE_IMAGE || file.getMimeType().startsWith("image/")) {
491 BitmapFactory.Options options = new BitmapFactory.Options();
492 options.inJustDecodeBounds = true;
493 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
494 int imageHeight = options.outHeight;
495 int imageWidth = options.outWidth;
496 if (url == null) {
497 message.setBody(Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
498 } else {
499 message.setBody(url.toString()+"|"+Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
500 }
501 } else {
502 if (url != null) {
503 message.setBody(url.toString()+"|"+Long.toString(file.getSize()));
504 } else {
505 message.setBody(Long.toString(file.getSize()));
506 }
507 }
508
509 }
510
511 public class FileCopyException extends Exception {
512 private static final long serialVersionUID = -1010013599132881427L;
513 private int resId;
514
515 public FileCopyException(int resId) {
516 this.resId = resId;
517 }
518
519 public int getResId() {
520 return resId;
521 }
522 }
523
524 public Bitmap getAvatar(String avatar, int size) {
525 if (avatar == null) {
526 return null;
527 }
528 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
529 if (bm == null) {
530 return null;
531 }
532 return bm;
533 }
534
535 public boolean isFileAvailable(Message message) {
536 return getFile(message).exists();
537 }
538
539 public static void close(Closeable stream) {
540 if (stream != null) {
541 try {
542 stream.close();
543 } catch (IOException e) {
544 }
545 }
546 }
547}