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