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 File file;
322 if (isAvatarCached(avatar)) {
323 file = new File(getAvatarPath(avatar.getFilename()));
324 } else {
325 String filename = getAvatarPath(avatar.getFilename());
326 file = new File(filename + ".tmp");
327 file.getParentFile().mkdirs();
328 try {
329 file.createNewFile();
330 FileOutputStream mFileOutputStream = new FileOutputStream(file);
331 MessageDigest digest = MessageDigest.getInstance("SHA-1");
332 digest.reset();
333 DigestOutputStream mDigestOutputStream = new DigestOutputStream(
334 mFileOutputStream, digest);
335 mDigestOutputStream.write(avatar.getImageAsBytes());
336 mDigestOutputStream.flush();
337 mDigestOutputStream.close();
338 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
339 if (sha1sum.equals(avatar.sha1sum)) {
340 file.renameTo(new File(filename));
341 } else {
342 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
343 file.delete();
344 return false;
345 }
346 } catch (FileNotFoundException e) {
347 return false;
348 } catch (IOException e) {
349 return false;
350 } catch (NoSuchAlgorithmException e) {
351 return false;
352 }
353 }
354 avatar.size = file.length();
355 return true;
356 }
357
358 public String getAvatarPath(String avatar) {
359 return mXmppConnectionService.getFilesDir().getAbsolutePath()
360 + "/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 try {
372 BitmapFactory.Options options = new BitmapFactory.Options();
373 options.inSampleSize = calcSampleSize(image, size);
374 InputStream is = mXmppConnectionService.getContentResolver().openInputStream(image);
375 Bitmap input = BitmapFactory.decodeStream(is, null, options);
376 if (input == null) {
377 return null;
378 } else {
379 int rotation = getRotation(image);
380 if (rotation > 0) {
381 input = rotate(input, rotation);
382 }
383 return cropCenterSquare(input, size);
384 }
385 } catch (FileNotFoundException e) {
386 return null;
387 }
388 }
389
390 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
391 if (image == null) {
392 return null;
393 }
394 try {
395 BitmapFactory.Options options = new BitmapFactory.Options();
396 options.inSampleSize = calcSampleSize(image,Math.max(newHeight, newWidth));
397 InputStream is = mXmppConnectionService.getContentResolver().openInputStream(image);
398 Bitmap source = BitmapFactory.decodeStream(is, null, options);
399
400 int sourceWidth = source.getWidth();
401 int sourceHeight = source.getHeight();
402 float xScale = (float) newWidth / sourceWidth;
403 float yScale = (float) newHeight / sourceHeight;
404 float scale = Math.max(xScale, yScale);
405 float scaledWidth = scale * sourceWidth;
406 float scaledHeight = scale * sourceHeight;
407 float left = (newWidth - scaledWidth) / 2;
408 float top = (newHeight - scaledHeight) / 2;
409
410 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
411 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
412 Canvas canvas = new Canvas(dest);
413 canvas.drawBitmap(source, null, targetRect, null);
414 return dest;
415 } catch (FileNotFoundException e) {
416 return null;
417 }
418
419 }
420
421 public Bitmap cropCenterSquare(Bitmap input, int size) {
422 int w = input.getWidth();
423 int h = input.getHeight();
424
425 float scale = Math.max((float) size / h, (float) size / w);
426
427 float outWidth = scale * w;
428 float outHeight = scale * h;
429 float left = (size - outWidth) / 2;
430 float top = (size - outHeight) / 2;
431 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
432
433 Bitmap output = Bitmap.createBitmap(size, size, input.getConfig());
434 Canvas canvas = new Canvas(output);
435 canvas.drawBitmap(input, null, target, null);
436 return output;
437 }
438
439 private int calcSampleSize(Uri image, int size) throws FileNotFoundException {
440 BitmapFactory.Options options = new BitmapFactory.Options();
441 options.inJustDecodeBounds = true;
442 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
443 return calcSampleSize(options, size);
444 }
445
446 private int calcSampleSize(File image, int size) {
447 BitmapFactory.Options options = new BitmapFactory.Options();
448 options.inJustDecodeBounds = true;
449 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
450 return calcSampleSize(options, size);
451 }
452
453 private int calcSampleSize(BitmapFactory.Options options, int size) {
454 int height = options.outHeight;
455 int width = options.outWidth;
456 int inSampleSize = 1;
457
458 if (height > size || width > size) {
459 int halfHeight = height / 2;
460 int halfWidth = width / 2;
461
462 while ((halfHeight / inSampleSize) > size
463 && (halfWidth / inSampleSize) > size) {
464 inSampleSize *= 2;
465 }
466 }
467 return inSampleSize;
468 }
469
470 public Uri getJingleFileUri(Message message) {
471 File file = getFile(message);
472 return Uri.parse("file://" + file.getAbsolutePath());
473 }
474
475 public void updateFileParams(Message message) {
476 updateFileParams(message,null);
477 }
478
479 public void updateFileParams(Message message, URL url) {
480 DownloadableFile file = getFile(message);
481 if (message.getType() == Message.TYPE_IMAGE || file.getMimeType().startsWith("image/")) {
482 BitmapFactory.Options options = new BitmapFactory.Options();
483 options.inJustDecodeBounds = true;
484 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
485 int imageHeight = options.outHeight;
486 int imageWidth = options.outWidth;
487 if (url == null) {
488 message.setBody(Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
489 } else {
490 message.setBody(url.toString()+"|"+Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
491 }
492 } else {
493 message.setBody(Long.toString(file.getSize()));
494 }
495
496 }
497
498 public class FileCopyException extends Exception {
499 private static final long serialVersionUID = -1010013599132881427L;
500 private int resId;
501
502 public FileCopyException(int resId) {
503 this.resId = resId;
504 }
505
506 public int getResId() {
507 return resId;
508 }
509 }
510
511 public Bitmap getAvatar(String avatar, int size) {
512 if (avatar == null) {
513 return null;
514 }
515 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
516 if (bm == null) {
517 return null;
518 }
519 return bm;
520 }
521
522 public boolean isFileAvailable(Message message) {
523 return getFile(message).exists();
524 }
525}