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.DownloadableFile;
34import eu.siacs.conversations.R;
35import eu.siacs.conversations.entities.Conversation;
36import eu.siacs.conversations.entities.Message;
37import eu.siacs.conversations.services.ImageProvider;
38import eu.siacs.conversations.utils.CryptoHelper;
39import eu.siacs.conversations.utils.UIHelper;
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 DownloadableFile getJingleFileLegacy(Message message) {
70 return getJingleFileLegacy(message, true);
71 }
72
73 public DownloadableFile 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 DownloadableFile(path + "/" + filename);
89 }
90
91 public DownloadableFile getJingleFile(Message message) {
92 return getConversationsFile(message, true);
93 }
94
95 public DownloadableFile getConversationsFile(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 DownloadableFile(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 DownloadableFile copyImageToPrivateStorage(Message message, Uri image)
143 throws ImageCopyException {
144 return this.copyImageToPrivateStorage(message, image, 0);
145 }
146
147 private DownloadableFile copyImageToPrivateStorage(Message message, Uri image,
148 int sampleSize) throws ImageCopyException {
149 try {
150 InputStream is = context.getContentResolver()
151 .openInputStream(image);
152 DownloadableFile 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 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.thumbnailCache.put(message.getUuid(), thumbnail);
262 }
263 return thumbnail;
264 }
265
266 public void removeFiles(Conversation conversation) {
267 String prefix = context.getFilesDir().getAbsolutePath();
268 String path = prefix + "/" + conversation.getAccount().getJid() + "/"
269 + conversation.getContactJid();
270 File file = new File(path);
271 try {
272 this.deleteFile(file);
273 } catch (IOException e) {
274 Log.d(Config.LOGTAG,
275 "error deleting file: " + file.getAbsolutePath());
276 }
277 }
278
279 private void deleteFile(File f) throws IOException {
280 if (f.isDirectory()) {
281 for (File c : f.listFiles())
282 deleteFile(c);
283 }
284 f.delete();
285 }
286
287 public Uri getTakePhotoUri() {
288 StringBuilder pathBuilder = new StringBuilder();
289 pathBuilder.append(Environment
290 .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
291 pathBuilder.append('/');
292 pathBuilder.append("Camera");
293 pathBuilder.append('/');
294 pathBuilder.append("IMG_" + this.imageDateFormat.format(new Date())
295 + ".jpg");
296 Uri uri = Uri.parse("file://" + pathBuilder.toString());
297 File file = new File(uri.toString());
298 file.getParentFile().mkdirs();
299 return uri;
300 }
301
302 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
303 try {
304 Avatar avatar = new Avatar();
305 Bitmap bm = cropCenterSquare(image, size);
306 if (bm == null) {
307 return null;
308 }
309 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
310 Base64OutputStream mBase64OutputSttream = new Base64OutputStream(
311 mByteArrayOutputStream, Base64.DEFAULT);
312 MessageDigest digest = MessageDigest.getInstance("SHA-1");
313 DigestOutputStream mDigestOutputStream = new DigestOutputStream(
314 mBase64OutputSttream, digest);
315 if (!bm.compress(format, 75, mDigestOutputStream)) {
316 return null;
317 }
318 mDigestOutputStream.flush();
319 mDigestOutputStream.close();
320 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
321 avatar.image = new String(mByteArrayOutputStream.toByteArray());
322 return avatar;
323 } catch (NoSuchAlgorithmException e) {
324 return null;
325 } catch (IOException e) {
326 return null;
327 }
328 }
329
330 public boolean isAvatarCached(Avatar avatar) {
331 File file = new File(getAvatarPath(context, avatar.getFilename()));
332 return file.exists();
333 }
334
335 public boolean save(Avatar avatar) {
336 if (isAvatarCached(avatar)) {
337 return true;
338 }
339 String filename = getAvatarPath(context, avatar.getFilename());
340 File file = new File(filename + ".tmp");
341 file.getParentFile().mkdirs();
342 try {
343 file.createNewFile();
344 FileOutputStream mFileOutputStream = new FileOutputStream(file);
345 MessageDigest digest = MessageDigest.getInstance("SHA-1");
346 digest.reset();
347 DigestOutputStream mDigestOutputStream = new DigestOutputStream(
348 mFileOutputStream, digest);
349 mDigestOutputStream.write(avatar.getImageAsBytes());
350 mDigestOutputStream.flush();
351 mDigestOutputStream.close();
352 avatar.size = file.length();
353 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
354 if (sha1sum.equals(avatar.sha1sum)) {
355 file.renameTo(new File(filename));
356 return true;
357 } else {
358 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
359 file.delete();
360 return false;
361 }
362 } catch (FileNotFoundException e) {
363 return false;
364 } catch (IOException e) {
365 return false;
366 } catch (NoSuchAlgorithmException e) {
367 return false;
368 }
369 }
370
371 public static String getAvatarPath(Context context, String avatar) {
372 return context.getFilesDir().getAbsolutePath() + "/avatars/" + avatar;
373 }
374
375 public Bitmap cropCenterSquare(Uri image, int size) {
376 try {
377 BitmapFactory.Options options = new BitmapFactory.Options();
378 options.inSampleSize = calcSampleSize(image, size);
379 InputStream is = context.getContentResolver()
380 .openInputStream(image);
381 Bitmap input = BitmapFactory.decodeStream(is, null, options);
382 if (input == null) {
383 return null;
384 } else {
385 int rotation = getRotation(image);
386 if (rotation > 0) {
387 input = rotate(input, rotation);
388 }
389 return cropCenterSquare(input, size);
390 }
391 } catch (FileNotFoundException e) {
392 return null;
393 }
394 }
395
396 public static Bitmap cropCenterSquare(Bitmap input, int size) {
397 int w = input.getWidth();
398 int h = input.getHeight();
399
400 float scale = Math.max((float) size / h, (float) size / w);
401
402 float outWidth = scale * w;
403 float outHeight = scale * h;
404 float left = (size - outWidth) / 2;
405 float top = (size - outHeight) / 2;
406 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
407
408 Bitmap output = Bitmap.createBitmap(size, size, input.getConfig());
409 Canvas canvas = new Canvas(output);
410 canvas.drawBitmap(input, null, target, null);
411 return output;
412 }
413
414 private int calcSampleSize(Uri image, int size)
415 throws FileNotFoundException {
416 BitmapFactory.Options options = new BitmapFactory.Options();
417 options.inJustDecodeBounds = true;
418 BitmapFactory.decodeStream(context.getContentResolver()
419 .openInputStream(image), null, options);
420 return calcSampleSize(options, size);
421 }
422
423 private int calcSampleSize(File image, int size) {
424 BitmapFactory.Options options = new BitmapFactory.Options();
425 options.inJustDecodeBounds = true;
426 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
427 return calcSampleSize(options, size);
428 }
429
430 private int calcSampleSize(BitmapFactory.Options options, int size) {
431 int height = options.outHeight;
432 int width = options.outWidth;
433 int inSampleSize = 1;
434
435 if (height > size || width > size) {
436 int halfHeight = height / 2;
437 int halfWidth = width / 2;
438
439 while ((halfHeight / inSampleSize) > size
440 && (halfWidth / inSampleSize) > size) {
441 inSampleSize *= 2;
442 }
443 }
444 return inSampleSize;
445 }
446
447 public Uri getJingleFileUri(Message message) {
448 File file = getJingleFile(message);
449 if (file.exists()) {
450 return Uri.parse("file://" + file.getAbsolutePath());
451 } else {
452 return ImageProvider.getProviderUri(message);
453 }
454 }
455
456 public class ImageCopyException extends Exception {
457 private static final long serialVersionUID = -1010013599132881427L;
458 private int resId;
459
460 public ImageCopyException(int resId) {
461 this.resId = resId;
462 }
463
464 public int getResId() {
465 return resId;
466 }
467 }
468
469 public static Bitmap getAvatar(String avatar, int size, Context context) {
470 Bitmap bm = BitmapFactory.decodeFile(FileBackend.getAvatarPath(context,
471 avatar));
472 if (bm == null) {
473 return null;
474 }
475 return cropCenterSquare(bm, UIHelper.getRealPx(size, context));
476 }
477}