AttachFileToConversationRunnable.java

  1package eu.siacs.conversations.services;
  2
  3import android.content.Context;
  4import android.content.SharedPreferences;
  5import android.net.Uri;
  6import android.os.Build;
  7import android.os.ParcelFileDescriptor;
  8import android.preference.PreferenceManager;
  9import android.util.Log;
 10
 11import androidx.annotation.RequiresApi;
 12
 13import net.ypresto.androidtranscoder.MediaTranscoder;
 14import net.ypresto.androidtranscoder.format.MediaFormatStrategy;
 15
 16import java.io.File;
 17import java.io.FileDescriptor;
 18import java.io.FileNotFoundException;
 19import java.util.concurrent.ExecutionException;
 20import java.util.concurrent.Future;
 21
 22import eu.siacs.conversations.Config;
 23import eu.siacs.conversations.R;
 24import eu.siacs.conversations.crypto.PgpEngine;
 25import eu.siacs.conversations.entities.DownloadableFile;
 26import eu.siacs.conversations.entities.Message;
 27import eu.siacs.conversations.persistance.FileBackend;
 28import eu.siacs.conversations.ui.UiCallback;
 29import eu.siacs.conversations.utils.Android360pFormatStrategy;
 30import eu.siacs.conversations.utils.Android720pFormatStrategy;
 31import eu.siacs.conversations.utils.MimeUtils;
 32
 33public class AttachFileToConversationRunnable implements Runnable, MediaTranscoder.Listener {
 34
 35	private final XmppConnectionService mXmppConnectionService;
 36	private final Message message;
 37	private final Uri uri;
 38	private final String type;
 39	private final UiCallback<Message> callback;
 40	private final boolean isVideoMessage;
 41	private final long originalFileSize;
 42	private int currentProgress = -1;
 43
 44	AttachFileToConversationRunnable(XmppConnectionService xmppConnectionService, Uri uri, String type, Message message, UiCallback<Message> callback) {
 45		this.uri = uri;
 46		this.type = type;
 47		this.mXmppConnectionService = xmppConnectionService;
 48		this.message = message;
 49		this.callback = callback;
 50		final String mimeType = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
 51		final int autoAcceptFileSize = mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize);
 52		this.originalFileSize = FileBackend.getFileSize(mXmppConnectionService,uri);
 53		this.isVideoMessage = (mimeType != null && mimeType.startsWith("video/")) && originalFileSize > autoAcceptFileSize && !"uncompressed".equals(getVideoCompression());
 54	}
 55
 56	boolean isVideoMessage() {
 57		return this.isVideoMessage;
 58	}
 59
 60	private void processAsFile() {
 61		final String path = mXmppConnectionService.getFileBackend().getOriginalPath(uri);
 62		if (path != null && !FileBackend.isPathBlacklisted(path)) {
 63			message.setRelativeFilePath(path);
 64			mXmppConnectionService.getFileBackend().updateFileParams(message);
 65			if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 66				mXmppConnectionService.getPgpEngine().encrypt(message, callback);
 67			} else {
 68				mXmppConnectionService.sendMessage(message);
 69				callback.success(message);
 70			}
 71		} else {
 72			try {
 73				mXmppConnectionService.getFileBackend().copyFileToPrivateStorage(message, uri, type);
 74				mXmppConnectionService.getFileBackend().updateFileParams(message);
 75				if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 76					final PgpEngine pgpEngine = mXmppConnectionService.getPgpEngine();
 77					if (pgpEngine != null) {
 78						pgpEngine.encrypt(message, callback);
 79					} else if (callback != null) {
 80						callback.error(R.string.unable_to_connect_to_keychain, null);
 81					}
 82				} else {
 83					mXmppConnectionService.sendMessage(message);
 84					callback.success(message);
 85				}
 86			} catch (FileBackend.FileCopyException e) {
 87				callback.error(e.getResId(), message);
 88			}
 89		}
 90	}
 91
 92	private void processAsVideo() throws FileNotFoundException {
 93		Log.d(Config.LOGTAG,"processing file as video");
 94		mXmppConnectionService.startForcingForegroundNotification();
 95		message.setRelativeFilePath(message.getUuid() + ".mp4");
 96		final DownloadableFile file = mXmppConnectionService.getFileBackend().getFile(message);
 97		final MediaFormatStrategy formatStrategy = "720".equals(getVideoCompression()) ? new Android720pFormatStrategy() : new Android360pFormatStrategy();
 98		file.getParentFile().mkdirs();
 99		final ParcelFileDescriptor parcelFileDescriptor = mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
100		if (parcelFileDescriptor == null) {
101			throw new FileNotFoundException("Parcel File Descriptor was null");
102		}
103		FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
104		Future<Void> future = MediaTranscoder.getInstance().transcodeVideo(fileDescriptor, file.getAbsolutePath(), formatStrategy, this);
105		try {
106			future.get();
107		} catch (InterruptedException e) {
108			throw new AssertionError(e);
109		} catch (ExecutionException e) {
110			if (e.getCause() instanceof Error) {
111				mXmppConnectionService.stopForcingForegroundNotification();
112				processAsFile();
113			} else {
114				Log.d(Config.LOGTAG, "ignoring execution exception. Should get handled by onTranscodeFiled() instead", e);
115			}
116		}
117	}
118
119	@Override
120	public void onTranscodeProgress(double progress) {
121		final int p = (int) Math.round(progress * 100);
122		if (p > currentProgress) {
123			currentProgress = p;
124			mXmppConnectionService.getNotificationService().updateFileAddingNotification(p,message);
125		}
126	}
127
128	@Override
129	public void onTranscodeCompleted() {
130		mXmppConnectionService.stopForcingForegroundNotification();
131		final File file = mXmppConnectionService.getFileBackend().getFile(message);
132		long convertedFileSize = mXmppConnectionService.getFileBackend().getFile(message).getSize();
133		Log.d(Config.LOGTAG,"originalFileSize="+originalFileSize+" convertedFileSize="+convertedFileSize);
134		if (originalFileSize != 0 && convertedFileSize >= originalFileSize) {
135			if (file.delete()) {
136				Log.d(Config.LOGTAG,"original file size was smaller. deleting and processing as file");
137				processAsFile();
138				return;
139			} else {
140				Log.d(Config.LOGTAG,"unable to delete converted file");
141			}
142		}
143		mXmppConnectionService.getFileBackend().updateFileParams(message);
144		if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
145			mXmppConnectionService.getPgpEngine().encrypt(message, callback);
146		} else {
147			mXmppConnectionService.sendMessage(message);
148			callback.success(message);
149		}
150	}
151
152	@Override
153	public void onTranscodeCanceled() {
154		mXmppConnectionService.stopForcingForegroundNotification();
155		processAsFile();
156	}
157
158	@Override
159	public void onTranscodeFailed(Exception e) {
160		mXmppConnectionService.stopForcingForegroundNotification();
161		Log.d(Config.LOGTAG,"video transcoding failed",e);
162		processAsFile();
163	}
164
165	@Override
166	public void run() {
167		if (this.isVideoMessage()) {
168			try {
169				processAsVideo();
170			} catch (FileNotFoundException e) {
171				processAsFile();
172			}
173		} else {
174			processAsFile();
175		}
176	}
177
178	private String getVideoCompression() {
179		return getVideoCompression(mXmppConnectionService);
180	}
181
182	public static String getVideoCompression(final Context context) {
183		final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
184		return preferences.getString("video_compression", context.getResources().getString(R.string.video_compression));
185	}
186}