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