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