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 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 Bitmap scalledBitmap = Bitmap.createScaledBitmap(originalBitmap,
114 scalledW, scalledH, true);
115 return scalledBitmap;
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 try {
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 file.createNewFile();
159 OutputStream os = new FileOutputStream(file);
160 InputStream 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 os.close();
168 is.close();
169 Log.d(Config.LOGTAG, "output file name " + mXmppConnectionService.getFileBackend().getFile(message));
170 return file;
171 } catch (FileNotFoundException e) {
172 throw new FileCopyException(R.string.error_file_not_found);
173 } catch (IOException e) {
174 throw new FileCopyException(R.string.error_io_exception);
175 }
176 }
177
178 public DownloadableFile copyImageToPrivateStorage(Message message, Uri image)
179 throws FileCopyException {
180 return this.copyImageToPrivateStorage(message, image, 0);
181 }
182
183 private DownloadableFile copyImageToPrivateStorage(Message message,
184 Uri image, int sampleSize) throws FileCopyException {
185 try {
186 InputStream is = mXmppConnectionService.getContentResolver()
187 .openInputStream(image);
188 DownloadableFile file = getFile(message);
189 file.getParentFile().mkdirs();
190 file.createNewFile();
191 Bitmap originalBitmap;
192 BitmapFactory.Options options = new BitmapFactory.Options();
193 int inSampleSize = (int) Math.pow(2, sampleSize);
194 Log.d(Config.LOGTAG, "reading bitmap with sample size "
195 + inSampleSize);
196 options.inSampleSize = inSampleSize;
197 originalBitmap = BitmapFactory.decodeStream(is, null, options);
198 is.close();
199 if (originalBitmap == null) {
200 throw new FileCopyException(R.string.error_not_an_image_file);
201 }
202 Bitmap scalledBitmap = resize(originalBitmap, IMAGE_SIZE);
203 originalBitmap = null;
204 int rotation = getRotation(image);
205 if (rotation > 0) {
206 scalledBitmap = rotate(scalledBitmap, rotation);
207 }
208 OutputStream os = new FileOutputStream(file);
209 boolean success = scalledBitmap.compress(
210 Bitmap.CompressFormat.WEBP, 75, os);
211 if (!success) {
212 throw new FileCopyException(R.string.error_compressing_image);
213 }
214 os.flush();
215 os.close();
216 long size = file.getSize();
217 int width = scalledBitmap.getWidth();
218 int height = scalledBitmap.getHeight();
219 message.setBody(Long.toString(size) + ',' + width + ',' + height);
220 return file;
221 } catch (FileNotFoundException e) {
222 throw new FileCopyException(R.string.error_file_not_found);
223 } catch (IOException e) {
224 throw new FileCopyException(R.string.error_io_exception);
225 } catch (SecurityException e) {
226 throw new FileCopyException(
227 R.string.error_security_exception_during_image_copy);
228 } catch (OutOfMemoryError e) {
229 ++sampleSize;
230 if (sampleSize <= 3) {
231 return copyImageToPrivateStorage(message, image, sampleSize);
232 } else {
233 throw new FileCopyException(R.string.error_out_of_memory);
234 }
235 }
236 }
237
238 private int getRotation(Uri image) {
239 try {
240 InputStream is = mXmppConnectionService.getContentResolver()
241 .openInputStream(image);
242 return ExifHelper.getOrientation(is);
243 } catch (FileNotFoundException e) {
244 return 0;
245 }
246 }
247
248 public Bitmap getImageFromMessage(Message message) {
249 return BitmapFactory.decodeFile(getFile(message).getAbsolutePath());
250 }
251
252 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly)
253 throws FileNotFoundException {
254 Bitmap thumbnail = mXmppConnectionService.getBitmapCache().get(
255 message.getUuid());
256 if ((thumbnail == null) && (!cacheOnly)) {
257 File file = getFile(message);
258 BitmapFactory.Options options = new BitmapFactory.Options();
259 options.inSampleSize = calcSampleSize(file, size);
260 Bitmap fullsize = BitmapFactory.decodeFile(file.getAbsolutePath(),
261 options);
262 if (fullsize == null) {
263 throw new FileNotFoundException();
264 }
265 thumbnail = resize(fullsize, size);
266 this.mXmppConnectionService.getBitmapCache().put(message.getUuid(),
267 thumbnail);
268 }
269 return thumbnail;
270 }
271
272 public Uri getTakePhotoUri() {
273 StringBuilder pathBuilder = new StringBuilder();
274 pathBuilder.append(Environment
275 .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
276 pathBuilder.append('/');
277 pathBuilder.append("Camera");
278 pathBuilder.append('/');
279 pathBuilder.append("IMG_" + this.imageDateFormat.format(new Date())
280 + ".jpg");
281 Uri uri = Uri.parse("file://" + pathBuilder.toString());
282 File file = new File(uri.toString());
283 file.getParentFile().mkdirs();
284 return uri;
285 }
286
287 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
288 try {
289 Avatar avatar = new Avatar();
290 Bitmap bm = cropCenterSquare(image, size);
291 if (bm == null) {
292 return null;
293 }
294 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
295 Base64OutputStream mBase64OutputSttream = new Base64OutputStream(
296 mByteArrayOutputStream, Base64.DEFAULT);
297 MessageDigest digest = MessageDigest.getInstance("SHA-1");
298 DigestOutputStream mDigestOutputStream = new DigestOutputStream(
299 mBase64OutputSttream, digest);
300 if (!bm.compress(format, 75, mDigestOutputStream)) {
301 return null;
302 }
303 mDigestOutputStream.flush();
304 mDigestOutputStream.close();
305 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
306 avatar.image = new String(mByteArrayOutputStream.toByteArray());
307 return avatar;
308 } catch (NoSuchAlgorithmException e) {
309 return null;
310 } catch (IOException e) {
311 return null;
312 }
313 }
314
315 public boolean isAvatarCached(Avatar avatar) {
316 File file = new File(getAvatarPath(avatar.getFilename()));
317 return file.exists();
318 }
319
320 public boolean save(Avatar avatar) {
321 if (isAvatarCached(avatar)) {
322 return true;
323 }
324 String filename = getAvatarPath(avatar.getFilename());
325 File file = new File(filename + ".tmp");
326 file.getParentFile().mkdirs();
327 try {
328 file.createNewFile();
329 FileOutputStream mFileOutputStream = new FileOutputStream(file);
330 MessageDigest digest = MessageDigest.getInstance("SHA-1");
331 digest.reset();
332 DigestOutputStream mDigestOutputStream = new DigestOutputStream(
333 mFileOutputStream, digest);
334 mDigestOutputStream.write(avatar.getImageAsBytes());
335 mDigestOutputStream.flush();
336 mDigestOutputStream.close();
337 avatar.size = file.length();
338 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
339 if (sha1sum.equals(avatar.sha1sum)) {
340 file.renameTo(new File(filename));
341 return true;
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 }
354 }
355
356 public String getAvatarPath(String avatar) {
357 return mXmppConnectionService.getFilesDir().getAbsolutePath()
358 + "/avatars/" + avatar;
359 }
360
361 public Uri getAvatarUri(String avatar) {
362 return Uri.parse("file:" + getAvatarPath(avatar));
363 }
364
365 public Bitmap cropCenterSquare(Uri image, int size) {
366 if (image == null) {
367 return null;
368 }
369 try {
370 BitmapFactory.Options options = new BitmapFactory.Options();
371 options.inSampleSize = calcSampleSize(image, size);
372 InputStream is = mXmppConnectionService.getContentResolver().openInputStream(image);
373 Bitmap input = BitmapFactory.decodeStream(is, null, options);
374 if (input == null) {
375 return null;
376 } else {
377 int rotation = getRotation(image);
378 if (rotation > 0) {
379 input = rotate(input, rotation);
380 }
381 return cropCenterSquare(input, size);
382 }
383 } catch (FileNotFoundException e) {
384 return null;
385 }
386 }
387
388 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
389 if (image == null) {
390 return null;
391 }
392 try {
393 BitmapFactory.Options options = new BitmapFactory.Options();
394 options.inSampleSize = calcSampleSize(image,Math.max(newHeight, newWidth));
395 InputStream is = mXmppConnectionService.getContentResolver().openInputStream(image);
396 Bitmap source = BitmapFactory.decodeStream(is, null, options);
397
398 int sourceWidth = source.getWidth();
399 int sourceHeight = source.getHeight();
400 float xScale = (float) newWidth / sourceWidth;
401 float yScale = (float) newHeight / sourceHeight;
402 float scale = Math.max(xScale, yScale);
403 float scaledWidth = scale * sourceWidth;
404 float scaledHeight = scale * sourceHeight;
405 float left = (newWidth - scaledWidth) / 2;
406 float top = (newHeight - scaledHeight) / 2;
407
408 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
409 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
410 Canvas canvas = new Canvas(dest);
411 canvas.drawBitmap(source, null, targetRect, null);
412 return dest;
413 } catch (FileNotFoundException e) {
414 return null;
415 }
416
417 }
418
419 public Bitmap cropCenterSquare(Bitmap input, int size) {
420 int w = input.getWidth();
421 int h = input.getHeight();
422
423 float scale = Math.max((float) size / h, (float) size / w);
424
425 float outWidth = scale * w;
426 float outHeight = scale * h;
427 float left = (size - outWidth) / 2;
428 float top = (size - outHeight) / 2;
429 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
430
431 Bitmap output = Bitmap.createBitmap(size, size, input.getConfig());
432 Canvas canvas = new Canvas(output);
433 canvas.drawBitmap(input, null, target, null);
434 return output;
435 }
436
437 private int calcSampleSize(Uri image, int size) throws FileNotFoundException {
438 BitmapFactory.Options options = new BitmapFactory.Options();
439 options.inJustDecodeBounds = true;
440 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
441 return calcSampleSize(options, size);
442 }
443
444 private int calcSampleSize(File image, int size) {
445 BitmapFactory.Options options = new BitmapFactory.Options();
446 options.inJustDecodeBounds = true;
447 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
448 return calcSampleSize(options, size);
449 }
450
451 private int calcSampleSize(BitmapFactory.Options options, int size) {
452 int height = options.outHeight;
453 int width = options.outWidth;
454 int inSampleSize = 1;
455
456 if (height > size || width > size) {
457 int halfHeight = height / 2;
458 int halfWidth = width / 2;
459
460 while ((halfHeight / inSampleSize) > size
461 && (halfWidth / inSampleSize) > size) {
462 inSampleSize *= 2;
463 }
464 }
465 return inSampleSize;
466 }
467
468 public Uri getJingleFileUri(Message message) {
469 File file = getFile(message);
470 return Uri.parse("file://" + file.getAbsolutePath());
471 }
472
473 public void updateFileParams(Message message) {
474 updateFileParams(message,null);
475 }
476
477 public void updateFileParams(Message message, URL url) {
478 DownloadableFile file = getFile(message);
479 if (message.getType() == Message.TYPE_IMAGE || file.getMimeType().startsWith("image/")) {
480 BitmapFactory.Options options = new BitmapFactory.Options();
481 options.inJustDecodeBounds = true;
482 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
483 int imageHeight = options.outHeight;
484 int imageWidth = options.outWidth;
485 if (url == null) {
486 message.setBody(Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
487 } else {
488 message.setBody(url.toString()+"|"+Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
489 }
490 } else {
491 message.setBody(Long.toString(file.getSize()));
492 }
493
494 }
495
496 public class FileCopyException extends Exception {
497 private static final long serialVersionUID = -1010013599132881427L;
498 private int resId;
499
500 public FileCopyException(int resId) {
501 this.resId = resId;
502 }
503
504 public int getResId() {
505 return resId;
506 }
507 }
508
509 public Bitmap getAvatar(String avatar, int size) {
510 if (avatar == null) {
511 return null;
512 }
513 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
514 if (bm == null) {
515 return null;
516 }
517 return bm;
518 }
519
520 public boolean isFileAvailable(Message message) {
521 return getFile(message).exists();
522 }
523}