Merge remote-tracking branch 'remotes/upstream/master' into switchListVsGridMaster
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / FileOperationsHelper.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author masensio
5 * @author David A. Velasco
6 * Copyright (C) 2015 ownCloud Inc.
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2,
10 * as published by the Free Software Foundation.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *
20 */
21
22 package com.owncloud.android.files;
23
24 import android.accounts.Account;
25 import android.content.ActivityNotFoundException;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.pm.PackageManager;
29 import android.content.pm.ResolveInfo;
30 import android.graphics.Bitmap;
31 import android.net.Uri;
32 import android.support.v4.app.DialogFragment;
33 import android.webkit.MimeTypeMap;
34 import android.widget.Toast;
35
36 import com.owncloud.android.MainApp;
37 import com.owncloud.android.R;
38 import com.owncloud.android.authentication.AccountUtils;
39 import com.owncloud.android.datamodel.OCFile;
40 import com.owncloud.android.datamodel.ThumbnailsCacheManager;
41 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
42 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
43 import com.owncloud.android.lib.common.network.WebdavUtils;
44 import com.owncloud.android.lib.common.utils.Log_OC;
45 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
46 import com.owncloud.android.services.OperationsService;
47 import com.owncloud.android.services.observer.FileObserverService;
48 import com.owncloud.android.ui.activity.FileActivity;
49 import com.owncloud.android.ui.adapter.DiskLruImageCacheFileProvider;
50 import com.owncloud.android.ui.dialog.ShareLinkToDialog;
51
52 import org.apache.http.protocol.HTTP;
53
54 import java.util.List;
55
56 import java.io.ByteArrayOutputStream;
57 import java.io.File;
58 import java.io.FileNotFoundException;
59 import java.io.FileOutputStream;
60 import java.io.IOException;
61
62 /**
63 *
64 */
65 public class FileOperationsHelper {
66
67 private static final String TAG = FileOperationsHelper.class.getName();
68
69 private static final String FTAG_CHOOSER_DIALOG = "CHOOSER_DIALOG";
70
71 protected FileActivity mFileActivity = null;
72
73 /// Identifier of operation in progress which result shouldn't be lost
74 private long mWaitingForOpId = Long.MAX_VALUE;
75
76 public FileOperationsHelper(FileActivity fileActivity) {
77 mFileActivity = fileActivity;
78 }
79
80
81 public void openFile(OCFile file) {
82 if (file != null) {
83 String storagePath = file.getStoragePath();
84 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
85
86 Intent intentForSavedMimeType = new Intent(Intent.ACTION_VIEW);
87 intentForSavedMimeType.setDataAndType(Uri.parse("file://"+ encodedStoragePath), file.getMimetype());
88 intentForSavedMimeType.setFlags(
89 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
90 );
91
92 Intent intentForGuessedMimeType = null;
93 if (storagePath.lastIndexOf('.') >= 0) {
94 String guessedMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
95 storagePath.substring(storagePath.lastIndexOf('.') + 1)
96 );
97 if (guessedMimeType != null && !guessedMimeType.equals(file.getMimetype())) {
98 intentForGuessedMimeType = new Intent(Intent.ACTION_VIEW);
99 intentForGuessedMimeType.setDataAndType(Uri.parse("file://"+ encodedStoragePath), guessedMimeType);
100 intentForGuessedMimeType.setFlags(
101 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
102 );
103 }
104 }
105
106 Intent openFileWithIntent;
107 if (intentForGuessedMimeType != null) {
108 openFileWithIntent = intentForGuessedMimeType;
109 } else {
110 openFileWithIntent = intentForSavedMimeType;
111 }
112
113 List<ResolveInfo> launchables = mFileActivity.getPackageManager().
114 queryIntentActivities(openFileWithIntent, PackageManager.GET_INTENT_FILTERS);
115
116 if(launchables != null && launchables.size() > 0) {
117 try {
118 mFileActivity.startActivity(
119 Intent.createChooser(
120 openFileWithIntent, mFileActivity.getString(R.string.actionbar_open_with)
121 )
122 );
123 } catch (ActivityNotFoundException anfe) {
124 showNoAppForFileTypeToast(mFileActivity.getApplicationContext());
125 }
126 } else {
127 showNoAppForFileTypeToast(mFileActivity.getApplicationContext());
128 }
129
130 } else {
131 Log_OC.wtf(TAG, "Trying to open a NULL OCFile");
132 }
133 }
134
135 /**
136 * Displays a toast stating that no application could be found to open the file.
137 *
138 * @param context the context to be able to show a toast.
139 */
140 private void showNoAppForFileTypeToast(Context context) {
141 Toast.makeText(context,
142 R.string.file_list_no_app_for_file_type, Toast.LENGTH_SHORT)
143 .show();
144 }
145
146 public void shareFileWithLink(OCFile file) {
147
148 if (isSharedSupported()) {
149 if (file != null) {
150 String link = "https://fake.url";
151 Intent intent = createShareWithLinkIntent(link);
152 String[] packagesToExclude = new String[]{mFileActivity.getPackageName()};
153 DialogFragment chooserDialog = ShareLinkToDialog.newInstance(intent, packagesToExclude, file);
154 chooserDialog.show(mFileActivity.getSupportFragmentManager(), FTAG_CHOOSER_DIALOG);
155
156 } else {
157 Log_OC.wtf(TAG, "Trying to share a NULL OCFile");
158 }
159
160 } else {
161 // Show a Message
162 Toast t = Toast.makeText(
163 mFileActivity, mFileActivity.getString(R.string.share_link_no_support_share_api), Toast.LENGTH_LONG
164 );
165 t.show();
166 }
167 }
168
169
170 public void shareFileWithLinkToApp(OCFile file, String password, Intent sendIntent) {
171
172 if (file != null) {
173 mFileActivity.showLoadingDialog();
174
175 Intent service = new Intent(mFileActivity, OperationsService.class);
176 service.setAction(OperationsService.ACTION_CREATE_SHARE);
177 service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
178 service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
179 service.putExtra(OperationsService.EXTRA_PASSWORD_SHARE, password);
180 service.putExtra(OperationsService.EXTRA_SEND_INTENT, sendIntent);
181 mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
182
183 } else {
184 Log_OC.wtf(TAG, "Trying to open a NULL OCFile");
185 }
186 }
187
188
189 private Intent createShareWithLinkIntent(String link) {
190 Intent intentToShareLink = new Intent(Intent.ACTION_SEND);
191 intentToShareLink.putExtra(Intent.EXTRA_TEXT, link);
192 intentToShareLink.setType(HTTP.PLAIN_TEXT_TYPE);
193 return intentToShareLink;
194 }
195
196
197 /**
198 * @return 'True' if the server supports the Share API
199 */
200 public boolean isSharedSupported() {
201 if (mFileActivity.getAccount() != null) {
202 OwnCloudVersion serverVersion = AccountUtils.getServerVersion(mFileActivity.getAccount());
203 return (serverVersion != null && serverVersion.isSharedSupported());
204 }
205 return false;
206 }
207
208
209 public void unshareFileWithLink(OCFile file) {
210
211 if (isSharedSupported()) {
212 // Unshare the file
213 Intent service = new Intent(mFileActivity, OperationsService.class);
214 service.setAction(OperationsService.ACTION_UNSHARE);
215 service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
216 service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
217 mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
218
219 mFileActivity.showLoadingDialog();
220
221 } else {
222 // Show a Message
223 Toast t = Toast.makeText(mFileActivity, mFileActivity.getString(R.string.share_link_no_support_share_api), Toast.LENGTH_LONG);
224 t.show();
225
226 }
227 }
228
229 public void sendDownloadedFile(OCFile file) {
230 if (file != null) {
231 String storagePath = file.getStoragePath();
232 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
233 Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
234 // set MimeType
235 sendIntent.setType(file.getMimetype());
236 sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + encodedStoragePath));
237 sendIntent.putExtra(Intent.ACTION_SEND, true); // Send Action
238
239 // Show dialog, without the own app
240 String[] packagesToExclude = new String[]{mFileActivity.getPackageName()};
241 DialogFragment chooserDialog = ShareLinkToDialog.newInstance(sendIntent, packagesToExclude, file);
242 chooserDialog.show(mFileActivity.getSupportFragmentManager(), FTAG_CHOOSER_DIALOG);
243
244 } else {
245 Log_OC.wtf(TAG, "Trying to send a NULL OCFile");
246 }
247 }
248
249 public void sendCachedImage(OCFile file) {
250 if (file != null) {
251 Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
252 // set MimeType
253 sendIntent.setType(file.getMimetype());
254 // sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://" + DiskLruImageCacheFileProvider.AUTHORITY + "/#" + file.getRemoteId() + "#" + file.getFileName()));
255 sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://" + DiskLruImageCacheFileProvider.AUTHORITY + file.getRemotePath()));
256 sendIntent.putExtra(Intent.ACTION_SEND, true); // Send Action
257
258 // Show dialog, without the own app
259 String[] packagesToExclude = new String[] { mFileActivity.getPackageName() };
260 DialogFragment chooserDialog = ShareLinkToDialog.newInstance(sendIntent, packagesToExclude, file);
261 chooserDialog.show(mFileActivity.getSupportFragmentManager(), FTAG_CHOOSER_DIALOG);
262 } else {
263 Log_OC.wtf(TAG, "Trying to send a NULL OCFile");
264 }
265 }
266
267
268 public void syncFile(OCFile file) {
269
270 if (!file.isFolder()){
271 Intent intent = new Intent(mFileActivity, OperationsService.class);
272 intent.setAction(OperationsService.ACTION_SYNC_FILE);
273 intent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
274 intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
275 intent.putExtra(OperationsService.EXTRA_SYNC_FILE_CONTENTS, true);
276 mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(intent);
277 mFileActivity.showLoadingDialog();
278
279 } else {
280 Intent intent = new Intent(mFileActivity, OperationsService.class);
281 intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
282 intent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
283 intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
284 mFileActivity.startService(intent);
285 }
286 }
287
288 public void toggleFavorite(OCFile file, boolean isFavorite) {
289 file.setFavorite(isFavorite);
290 mFileActivity.getStorageManager().saveFile(file);
291
292 /// register the OCFile instance in the observer service to monitor local updates
293 Intent observedFileIntent = FileObserverService.makeObservedFileIntent(
294 mFileActivity,
295 file,
296 mFileActivity.getAccount(),
297 isFavorite);
298 mFileActivity.startService(observedFileIntent);
299
300 /// immediate content synchronization
301 if (file.isFavorite()) {
302 syncFile(file);
303 }
304 }
305
306 public void renameFile(OCFile file, String newFilename) {
307 // RenameFile
308 Intent service = new Intent(mFileActivity, OperationsService.class);
309 service.setAction(OperationsService.ACTION_RENAME);
310 service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
311 service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
312 service.putExtra(OperationsService.EXTRA_NEWNAME, newFilename);
313 mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
314
315 mFileActivity.showLoadingDialog();
316 }
317
318
319 public void removeFile(OCFile file, boolean onlyLocalCopy) {
320 // RemoveFile
321 Intent service = new Intent(mFileActivity, OperationsService.class);
322 service.setAction(OperationsService.ACTION_REMOVE);
323 service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
324 service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
325 service.putExtra(OperationsService.EXTRA_REMOVE_ONLY_LOCAL, onlyLocalCopy);
326 mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
327
328 mFileActivity.showLoadingDialog();
329 }
330
331
332 public void createFolder(String remotePath, boolean createFullPath) {
333 // Create Folder
334 Intent service = new Intent(mFileActivity, OperationsService.class);
335 service.setAction(OperationsService.ACTION_CREATE_FOLDER);
336 service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
337 service.putExtra(OperationsService.EXTRA_REMOTE_PATH, remotePath);
338 service.putExtra(OperationsService.EXTRA_CREATE_FULL_PATH, createFullPath);
339 mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
340
341 mFileActivity.showLoadingDialog();
342 }
343
344 /**
345 * Cancel the transference in downloads (files/folders) and file uploads
346 * @param file OCFile
347 */
348 public void cancelTransference(OCFile file) {
349 Account account = mFileActivity.getAccount();
350 if (file.isFolder()) {
351 OperationsService.OperationsServiceBinder opsBinder = mFileActivity.getOperationsServiceBinder();
352 if (opsBinder != null) {
353 opsBinder.cancel(account, file);
354 }
355 }
356
357 // for both files and folders
358 FileDownloaderBinder downloaderBinder = mFileActivity.getFileDownloaderBinder();
359 FileUploaderBinder uploaderBinder = mFileActivity.getFileUploaderBinder();
360 if (downloaderBinder != null && downloaderBinder.isDownloading(account, file)) {
361 downloaderBinder.cancel(account, file);
362
363 // TODO - review why is this here, and solve in a better way
364 // Remove etag for parent, if file is a favorite
365 if (file.isFavorite()) {
366 OCFile parent = mFileActivity.getStorageManager().getFileById(file.getParentId());
367 parent.setEtag("");
368 mFileActivity.getStorageManager().saveFile(parent);
369 }
370
371 } else if (uploaderBinder != null && uploaderBinder.isUploading(account, file)) {
372 uploaderBinder.cancel(account, file);
373 }
374 }
375
376 /**
377 * Start move file operation
378 *
379 * @param newfile File where it is going to be moved
380 * @param currentFile File with the previous info
381 */
382 public void moveFile(OCFile newfile, OCFile currentFile) {
383 // Move files
384 Intent service = new Intent(mFileActivity, OperationsService.class);
385 service.setAction(OperationsService.ACTION_MOVE_FILE);
386 service.putExtra(OperationsService.EXTRA_NEW_PARENT_PATH, newfile.getRemotePath());
387 service.putExtra(OperationsService.EXTRA_REMOTE_PATH, currentFile.getRemotePath());
388 service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
389 mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
390
391 mFileActivity.showLoadingDialog();
392 }
393
394 /**
395 * Start copy file operation
396 *
397 * @param newfile File where it is going to be moved
398 * @param currentFile File with the previous info
399 */
400 public void copyFile(OCFile newfile, OCFile currentFile) {
401 // Copy files
402 Intent service = new Intent(mFileActivity, OperationsService.class);
403 service.setAction(OperationsService.ACTION_COPY_FILE);
404 service.putExtra(OperationsService.EXTRA_NEW_PARENT_PATH, newfile.getRemotePath());
405 service.putExtra(OperationsService.EXTRA_REMOTE_PATH, currentFile.getRemotePath());
406 service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
407 mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
408
409 mFileActivity.showLoadingDialog();
410 }
411
412 public long getOpIdWaitingFor() {
413 return mWaitingForOpId;
414 }
415
416
417 public void setOpIdWaitingFor(long waitingForOpId) {
418 mWaitingForOpId = waitingForOpId;
419 }
420
421 /**
422 * @return 'True' if the server doesn't need to check forbidden characters
423 */
424 public boolean isVersionWithForbiddenCharacters() {
425 if (mFileActivity.getAccount() != null) {
426 OwnCloudVersion serverVersion = AccountUtils.getServerVersion(mFileActivity.getAccount());
427 return (serverVersion != null && serverVersion.isVersionWithForbiddenCharacters());
428 }
429 return false;
430 }
431 }