FileBackend.java

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