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