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