FileBackend.java

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