FileOperationsHelper.java 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author masensio
  5. * @author David A. Velasco
  6. * @author Juan Carlos González Cabrero
  7. * @author Andy Scherzinger
  8. * Copyright (C) 2015 ownCloud Inc.
  9. * Copyright (C) 2018 Andy Scherzinger
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License version 2,
  13. * as published by the Free Software Foundation.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. package com.owncloud.android.ui.helpers;
  24. import android.accounts.Account;
  25. import android.content.ActivityNotFoundException;
  26. import android.content.ComponentName;
  27. import android.content.Context;
  28. import android.content.Intent;
  29. import android.content.pm.PackageManager;
  30. import android.content.pm.ResolveInfo;
  31. import android.net.Uri;
  32. import android.os.Build;
  33. import android.support.annotation.NonNull;
  34. import android.support.annotation.Nullable;
  35. import android.support.v4.app.FragmentManager;
  36. import android.support.v4.app.FragmentTransaction;
  37. import android.support.v4.content.FileProvider;
  38. import android.util.Log;
  39. import android.view.View;
  40. import android.webkit.MimeTypeMap;
  41. import com.evernote.android.job.JobRequest;
  42. import com.evernote.android.job.util.Device;
  43. import com.owncloud.android.MainApp;
  44. import com.owncloud.android.R;
  45. import com.owncloud.android.authentication.AccountUtils;
  46. import com.owncloud.android.datamodel.FileDataStorageManager;
  47. import com.owncloud.android.datamodel.OCFile;
  48. import com.owncloud.android.files.StreamMediaFileOperation;
  49. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  50. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  51. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  52. import com.owncloud.android.lib.common.utils.Log_OC;
  53. import com.owncloud.android.lib.resources.files.CheckEtagOperation;
  54. import com.owncloud.android.lib.resources.files.FileVersion;
  55. import com.owncloud.android.lib.resources.shares.OCShare;
  56. import com.owncloud.android.lib.resources.shares.ShareType;
  57. import com.owncloud.android.lib.resources.status.OCCapability;
  58. import com.owncloud.android.operations.SynchronizeFileOperation;
  59. import com.owncloud.android.services.OperationsService;
  60. import com.owncloud.android.ui.activity.ConflictsResolveActivity;
  61. import com.owncloud.android.ui.activity.FileActivity;
  62. import com.owncloud.android.ui.activity.ShareActivity;
  63. import com.owncloud.android.ui.dialog.SendShareDialog;
  64. import com.owncloud.android.ui.events.EncryptionEvent;
  65. import com.owncloud.android.ui.events.FavoriteEvent;
  66. import com.owncloud.android.ui.events.SyncEventFinished;
  67. import com.owncloud.android.utils.ConnectivityUtils;
  68. import com.owncloud.android.utils.DisplayUtils;
  69. import com.owncloud.android.utils.FileStorageUtils;
  70. import com.owncloud.android.utils.UriUtils;
  71. import org.greenrobot.eventbus.EventBus;
  72. import java.io.BufferedReader;
  73. import java.io.File;
  74. import java.io.FileInputStream;
  75. import java.io.IOException;
  76. import java.io.InputStreamReader;
  77. import java.util.ArrayList;
  78. import java.util.Arrays;
  79. import java.util.Collection;
  80. import java.util.List;
  81. import java.util.regex.Matcher;
  82. import java.util.regex.Pattern;
  83. /**
  84. * Helper implementation for file operations locally and remote.
  85. */
  86. public class FileOperationsHelper {
  87. private static final String TAG = FileOperationsHelper.class.getSimpleName();
  88. private static final Pattern mPatternUrl = Pattern.compile("^URL=(.+)$");
  89. private static final Pattern mPatternString = Pattern.compile("<string>(.+)</string>");
  90. private FileActivity mFileActivity;
  91. /// Identifier of operation in progress which result shouldn't be lost
  92. private long mWaitingForOpId = Long.MAX_VALUE;
  93. public FileOperationsHelper(FileActivity fileActivity) {
  94. mFileActivity = fileActivity;
  95. }
  96. @Nullable
  97. private String getUrlFromFile(String storagePath, Pattern pattern) {
  98. String url = null;
  99. InputStreamReader fr = null;
  100. BufferedReader br = null;
  101. try {
  102. fr = new InputStreamReader(new FileInputStream(storagePath), "UTF8");
  103. br = new BufferedReader(fr);
  104. String line;
  105. while ((line = br.readLine()) != null) {
  106. Matcher m = pattern.matcher(line);
  107. if (m.find()) {
  108. url = m.group(1);
  109. break;
  110. }
  111. }
  112. } catch (IOException e) {
  113. Log_OC.d(TAG, e.getMessage());
  114. } finally {
  115. if (br != null) {
  116. try {
  117. br.close();
  118. } catch (IOException e) {
  119. Log_OC.d(TAG, "Error closing buffered reader for URL file", e);
  120. }
  121. }
  122. if (fr != null) {
  123. try {
  124. fr.close();
  125. } catch (IOException e) {
  126. Log_OC.d(TAG, "Error closing file reader for URL file", e);
  127. }
  128. }
  129. }
  130. return url;
  131. }
  132. @Nullable
  133. private Intent createIntentFromFile(String storagePath) {
  134. String url = null;
  135. int lastIndexOfDot = storagePath.lastIndexOf('.');
  136. if (lastIndexOfDot >= 0) {
  137. String fileExt = storagePath.substring(lastIndexOfDot + 1);
  138. if (fileExt.equalsIgnoreCase("url") || fileExt.equalsIgnoreCase("desktop")) {
  139. // Windows internet shortcut file .url
  140. // Ubuntu internet shortcut file .desktop
  141. url = getUrlFromFile(storagePath, mPatternUrl);
  142. } else if (fileExt.equalsIgnoreCase("webloc")) {
  143. // mac internet shortcut file .webloc
  144. url = getUrlFromFile(storagePath, mPatternString);
  145. }
  146. }
  147. if (url == null) {
  148. return null;
  149. }
  150. return new Intent(Intent.ACTION_VIEW, Uri.parse(url));
  151. }
  152. public void startSyncForFileAndIntent(OCFile file, Intent intent) {
  153. new Thread(() -> {
  154. Account account = mFileActivity.getAccount();
  155. FileDataStorageManager storageManager = new FileDataStorageManager(mFileActivity.getAccount(),
  156. mFileActivity.getContentResolver());
  157. // check if file is in conflict (this is known due to latest folder refresh)
  158. if (file.isInConflict()) {
  159. syncFile(file, account, storageManager);
  160. EventBus.getDefault().post(new SyncEventFinished(intent));
  161. return;
  162. }
  163. // check if latest sync is >30s ago
  164. OCFile parent = storageManager.getFileById(file.getParentId());
  165. if (parent.getLastSyncDateForData() + 30 * 1000 > System.currentTimeMillis()) {
  166. EventBus.getDefault().post(new SyncEventFinished(intent));
  167. return;
  168. }
  169. // if offline or walled garden, show old version with warning
  170. if (Device.getNetworkType(mFileActivity).equals(JobRequest.NetworkType.ANY) ||
  171. ConnectivityUtils.isInternetWalled(mFileActivity)) {
  172. DisplayUtils.showSnackMessage(mFileActivity, R.string.file_not_synced);
  173. EventBus.getDefault().post(new SyncEventFinished(intent));
  174. return;
  175. }
  176. // check for changed eTag
  177. CheckEtagOperation checkEtagOperation = new CheckEtagOperation(file.getRemotePath(), file.getEtag());
  178. RemoteOperationResult result = checkEtagOperation.execute(account, mFileActivity);
  179. // eTag changed, sync file
  180. if (result.getCode() == RemoteOperationResult.ResultCode.ETAG_CHANGED) {
  181. syncFile(file, account, storageManager);
  182. }
  183. EventBus.getDefault().post(new SyncEventFinished(intent));
  184. }).start();
  185. }
  186. private void syncFile(OCFile file, Account account, FileDataStorageManager storageManager) {
  187. mFileActivity.runOnUiThread(() -> mFileActivity.showLoadingDialog(mFileActivity.getResources()
  188. .getString(R.string.sync_in_progress)));
  189. SynchronizeFileOperation sfo = new SynchronizeFileOperation(file, null, account, true, mFileActivity);
  190. RemoteOperationResult result = sfo.execute(storageManager, mFileActivity);
  191. if (result.getCode() == RemoteOperationResult.ResultCode.SYNC_CONFLICT) {
  192. // ISSUE 5: if the user is not running the app (this is a service!),
  193. // this can be very intrusive; a notification should be preferred
  194. Intent i = new Intent(mFileActivity, ConflictsResolveActivity.class);
  195. i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
  196. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, file);
  197. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, account);
  198. mFileActivity.startActivity(i);
  199. } else {
  200. if (file.isDown()) {
  201. FileStorageUtils.checkIfFileFinishedSaving(file);
  202. if (!result.isSuccess()) {
  203. DisplayUtils.showSnackMessage(mFileActivity, R.string.file_not_synced);
  204. try {
  205. Thread.sleep(3000);
  206. } catch (InterruptedException e) {
  207. Log.e(TAG, "Failed to sleep for a bit");
  208. }
  209. }
  210. }
  211. }
  212. mFileActivity.dismissLoadingDialog();
  213. }
  214. public void openFile(OCFile file) {
  215. if (file != null) {
  216. final Intent openFileWithIntent = createOpenFileIntent(file);
  217. List<ResolveInfo> launchables = mFileActivity.getPackageManager().
  218. queryIntentActivities(openFileWithIntent, PackageManager.GET_RESOLVED_FILTER);
  219. mFileActivity.showLoadingDialog(mFileActivity.getResources().getString(R.string.sync_in_progress));
  220. new Thread(new Runnable() {
  221. @Override
  222. public void run() {
  223. Account account = AccountUtils.getCurrentOwnCloudAccount(mFileActivity);
  224. FileDataStorageManager storageManager =
  225. new FileDataStorageManager(account, mFileActivity.getContentResolver());
  226. // a fresh object is needed; many things could have occurred to the file
  227. // since it was registered to observe again, assuming that local files
  228. // are linked to a remote file AT MOST, SOMETHING TO BE DONE;
  229. SynchronizeFileOperation sfo =
  230. new SynchronizeFileOperation(file, null, account, true, mFileActivity);
  231. RemoteOperationResult result = sfo.execute(storageManager, mFileActivity);
  232. mFileActivity.dismissLoadingDialog();
  233. if (result.getCode() == RemoteOperationResult.ResultCode.SYNC_CONFLICT) {
  234. // ISSUE 5: if the user is not running the app (this is a service!),
  235. // this can be very intrusive; a notification should be preferred
  236. Intent i = new Intent(mFileActivity, ConflictsResolveActivity.class);
  237. i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
  238. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, file);
  239. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, account);
  240. mFileActivity.startActivity(i);
  241. } else {
  242. if (launchables != null && launchables.size() > 0) {
  243. try {
  244. if (!result.isSuccess()) {
  245. DisplayUtils.showSnackMessage(mFileActivity, R.string.file_not_synced);
  246. try {
  247. Thread.sleep(3000);
  248. } catch (InterruptedException e) {
  249. Log.e(TAG, "Failed to sleep");
  250. }
  251. }
  252. mFileActivity.startActivity(
  253. Intent.createChooser(
  254. openFileWithIntent,
  255. mFileActivity.getString(R.string.actionbar_open_with)
  256. )
  257. );
  258. } catch (ActivityNotFoundException exception) {
  259. DisplayUtils.showSnackMessage(mFileActivity, R.string.file_list_no_app_for_file_type);
  260. }
  261. } else {
  262. DisplayUtils.showSnackMessage(mFileActivity, R.string.file_list_no_app_for_file_type);
  263. }
  264. }
  265. }
  266. }).start();
  267. } else {
  268. Log_OC.e(TAG, "Trying to open a NULL OCFile");
  269. }
  270. }
  271. @NonNull
  272. private Intent createOpenFileIntent(OCFile file) {
  273. String storagePath = file.getStoragePath();
  274. Uri fileUri = getFileUri(file, MainApp.getAppContext().getResources().getStringArray(R.array
  275. .ms_office_extensions));
  276. Intent openFileWithIntent = null;
  277. int lastIndexOfDot = storagePath.lastIndexOf('.');
  278. if (lastIndexOfDot >= 0) {
  279. String fileExt = storagePath.substring(lastIndexOfDot + 1);
  280. String guessedMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExt);
  281. if (guessedMimeType != null) {
  282. openFileWithIntent = new Intent(Intent.ACTION_VIEW);
  283. openFileWithIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  284. openFileWithIntent.setDataAndType(
  285. fileUri,
  286. guessedMimeType
  287. );
  288. }
  289. }
  290. if (openFileWithIntent == null) {
  291. openFileWithIntent = createIntentFromFile(storagePath);
  292. }
  293. if (openFileWithIntent == null) {
  294. openFileWithIntent = new Intent(Intent.ACTION_VIEW);
  295. openFileWithIntent.setDataAndType(
  296. fileUri,
  297. file.getMimeType()
  298. );
  299. }
  300. openFileWithIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  301. return openFileWithIntent;
  302. }
  303. private Uri getFileUri(OCFile file, String[] officeExtensions) {
  304. if (file.getFileName().contains(".") &&
  305. Arrays.asList(officeExtensions).contains(file.getFileName().substring(file.getFileName().
  306. lastIndexOf(".") + 1, file.getFileName().length())) &&
  307. !file.getStoragePath().startsWith(MainApp.getAppContext().getFilesDir().getAbsolutePath())) {
  308. return file.getLegacyExposedFileUri(mFileActivity);
  309. } else {
  310. return file.getExposedFileUri(mFileActivity);
  311. }
  312. }
  313. public void streamMediaFile(OCFile file) {
  314. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  315. new Thread(() -> {
  316. Account account = AccountUtils.getCurrentOwnCloudAccount(mFileActivity);
  317. StreamMediaFileOperation sfo = new StreamMediaFileOperation(file.getLocalId());
  318. RemoteOperationResult result = sfo.execute(account, mFileActivity);
  319. mFileActivity.dismissLoadingDialog();
  320. if (!result.isSuccess()) {
  321. DisplayUtils.showSnackMessage(mFileActivity, R.string.stream_not_possible_headline);
  322. return;
  323. }
  324. Intent openFileWithIntent = new Intent(Intent.ACTION_VIEW);
  325. Uri uri = Uri.parse((String) result.getData().get(0));
  326. openFileWithIntent.setDataAndType(uri, file.getMimeType());
  327. mFileActivity.startActivity(Intent.createChooser(openFileWithIntent,
  328. mFileActivity.getString(R.string.stream)));
  329. }).start();
  330. }
  331. /**
  332. * Helper method to share a file via a public link. Starts a request to do it in {@link OperationsService}
  333. *
  334. * @param file The file to share.
  335. * @param password Optional password to protect the public share.
  336. */
  337. public void shareFileViaLink(OCFile file, String password) {
  338. if (file != null) {
  339. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  340. Intent service = new Intent(mFileActivity, OperationsService.class);
  341. service.setAction(OperationsService.ACTION_CREATE_SHARE_VIA_LINK);
  342. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  343. if (password != null && password.length() > 0) {
  344. service.putExtra(OperationsService.EXTRA_SHARE_PASSWORD, password);
  345. }
  346. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  347. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  348. } else {
  349. Log_OC.e(TAG, "Trying to share a NULL OCFile");
  350. // TODO user-level error?
  351. }
  352. }
  353. public void getFileWithLink(OCFile file) {
  354. if (file != null) {
  355. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  356. getString(R.string.wait_a_moment));
  357. Intent service = new Intent(mFileActivity, OperationsService.class);
  358. service.setAction(OperationsService.ACTION_CREATE_SHARE_VIA_LINK);
  359. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  360. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  361. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  362. } else {
  363. Log_OC.e(TAG, "Trying to share a NULL OCFile");
  364. }
  365. }
  366. /**
  367. * Helper method to share a file with a known sharee. Starts a request to do it in {@link OperationsService}
  368. *
  369. * @param file The file to share.
  370. * @param shareeName Name (user name or group name) of the target sharee.
  371. * @param shareType The share type determines the sharee type.
  372. * @param permissions Permissions to grant to sharee on the shared file.
  373. */
  374. public void shareFileWithSharee(OCFile file, String shareeName, ShareType shareType, int permissions) {
  375. if (file != null) {
  376. // TODO check capability?
  377. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  378. getString(R.string.wait_a_moment));
  379. Intent service = new Intent(mFileActivity, OperationsService.class);
  380. service.setAction(OperationsService.ACTION_CREATE_SHARE_WITH_SHAREE);
  381. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  382. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  383. service.putExtra(OperationsService.EXTRA_SHARE_WITH, shareeName);
  384. service.putExtra(OperationsService.EXTRA_SHARE_TYPE, shareType);
  385. service.putExtra(OperationsService.EXTRA_SHARE_PERMISSIONS, permissions);
  386. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  387. } else {
  388. Log_OC.e(TAG, "Trying to share a NULL OCFile");
  389. }
  390. }
  391. /**
  392. * Helper method to revert to a file version. Starts a request to do it in {@link OperationsService}
  393. *
  394. * @param fileVersion The file version to restore
  395. * @param userId userId of current account
  396. */
  397. public void restoreFileVersion(FileVersion fileVersion, String userId) {
  398. if (fileVersion != null) {
  399. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  400. getString(R.string.wait_a_moment));
  401. Intent service = new Intent(mFileActivity, OperationsService.class);
  402. service.setAction(OperationsService.ACTION_RESTORE_VERSION);
  403. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  404. service.putExtra(OperationsService.EXTRA_FILE_VERSION, fileVersion);
  405. service.putExtra(OperationsService.EXTRA_USER_ID, userId);
  406. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  407. } else {
  408. Log_OC.e(TAG, "Trying to restore a NULL FileVersion");
  409. }
  410. }
  411. /**
  412. * Helper method to unshare a file publicly shared via link.
  413. * Starts a request to do it in {@link OperationsService}
  414. *
  415. * @param file The file to unshare.
  416. */
  417. public void unshareFileViaLink(OCFile file) {
  418. // Unshare the file: Create the intent
  419. Intent unshareService = new Intent(mFileActivity, OperationsService.class);
  420. unshareService.setAction(OperationsService.ACTION_UNSHARE);
  421. unshareService.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  422. unshareService.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  423. unshareService.putExtra(OperationsService.EXTRA_SHARE_TYPE, ShareType.PUBLIC_LINK);
  424. unshareService.putExtra(OperationsService.EXTRA_SHARE_WITH, "");
  425. queueShareIntent(unshareService);
  426. }
  427. public void unshareFileWithUserOrGroup(OCFile file, ShareType shareType, String userOrGroup) {
  428. // Unshare the file: Create the intent
  429. Intent unshareService = new Intent(mFileActivity, OperationsService.class);
  430. unshareService.setAction(OperationsService.ACTION_UNSHARE);
  431. unshareService.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  432. unshareService.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  433. unshareService.putExtra(OperationsService.EXTRA_SHARE_TYPE, shareType);
  434. unshareService.putExtra(OperationsService.EXTRA_SHARE_WITH, userOrGroup);
  435. queueShareIntent(unshareService);
  436. }
  437. private void queueShareIntent(Intent shareIntent) {
  438. // Unshare the file
  439. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(shareIntent);
  440. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().getString(R.string.wait_a_moment));
  441. }
  442. /**
  443. * Show an instance of {@link ShareType} for sharing or unsharing the {@link OCFile} received as parameter.
  444. *
  445. * @param file File to share or unshare.
  446. */
  447. public void showShareFile(OCFile file) {
  448. Intent intent = new Intent(mFileActivity, ShareActivity.class);
  449. intent.putExtra(FileActivity.EXTRA_FILE, file);
  450. intent.putExtra(FileActivity.EXTRA_ACCOUNT, mFileActivity.getAccount());
  451. mFileActivity.startActivity(intent);
  452. }
  453. /**
  454. * Updates a public share on a file to set its password.
  455. * Starts a request to do it in {@link OperationsService}
  456. *
  457. * @param file File which public share will be protected with a password.
  458. * @param password Password to set for the public link; null or empty string to clear
  459. * the current password
  460. */
  461. public void setPasswordToShareViaLink(OCFile file, String password) {
  462. // Set password updating share
  463. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  464. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  465. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  466. updateShareIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  467. updateShareIntent.putExtra(
  468. OperationsService.EXTRA_SHARE_PASSWORD,
  469. (password == null) ? "" : password
  470. );
  471. queueShareIntent(updateShareIntent);
  472. }
  473. /**
  474. * Updates a share on a file to set its password.
  475. * Starts a request to do it in {@link OperationsService}
  476. *
  477. * @param share File which share will be protected with a password.
  478. * @param password Password to set for the public link; null or empty string to clear
  479. * the current password
  480. */
  481. public void setPasswordToShare(OCShare share, String password) {
  482. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  483. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  484. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  485. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  486. updateShareIntent.putExtra(
  487. OperationsService.EXTRA_SHARE_PASSWORD,
  488. (password == null) ? "" : password
  489. );
  490. queueShareIntent(updateShareIntent);
  491. }
  492. /**
  493. * Updates a public share on a file to set its expiration date.
  494. * Starts a request to do it in {@link OperationsService}
  495. *
  496. * @param file File which public share will be constrained with an expiration date.
  497. * @param expirationTimeInMillis Expiration date to set. A negative value clears the current expiration
  498. * date, leaving the link unrestricted. Zero makes no change.
  499. */
  500. public void setExpirationDateToShareViaLink(OCFile file, long expirationTimeInMillis) {
  501. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  502. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  503. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  504. updateShareIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  505. updateShareIntent.putExtra(
  506. OperationsService.EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS,
  507. expirationTimeInMillis
  508. );
  509. queueShareIntent(updateShareIntent);
  510. }
  511. /**
  512. * Updates a public share on a file to set its expiration date.
  513. * Starts a request to do it in {@link OperationsService}
  514. *
  515. * @param share {@link OCShare} instance which permissions will be updated.
  516. * @param expirationTimeInMillis Expiration date to set. A negative value clears the current expiration
  517. * date, leaving the link unrestricted. Zero makes no change.
  518. */
  519. public void setExpirationDateToShare(OCShare share, long expirationTimeInMillis) {
  520. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  521. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  522. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  523. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  524. updateShareIntent.putExtra(
  525. OperationsService.EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS,
  526. expirationTimeInMillis
  527. );
  528. updateShareIntent.putExtra(
  529. OperationsService.EXTRA_SHARE_PERMISSIONS,
  530. 0
  531. );
  532. queueShareIntent(updateShareIntent);
  533. }
  534. /**
  535. * Updates a share on a file to set its access permissions.
  536. * Starts a request to do it in {@link OperationsService}
  537. *
  538. * @param share {@link OCShare} instance which permissions will be updated.
  539. * @param permissions New permissions to set. A value <= 0 makes no update.
  540. */
  541. public void setPermissionsToShare(OCShare share, int permissions) {
  542. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  543. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  544. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  545. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  546. updateShareIntent.putExtra(
  547. OperationsService.EXTRA_SHARE_PERMISSIONS,
  548. permissions
  549. );
  550. queueShareIntent(updateShareIntent);
  551. }
  552. /**
  553. * Updates a public share on a folder to set its editing permission.
  554. * Starts a request to do it in {@link OperationsService}
  555. *
  556. * @param folder Folder which editing permission of his public share will be modified.
  557. * @param uploadPermission New state of the permission for editing the folder shared via link.
  558. */
  559. public void setUploadPermissionsToShare(OCFile folder, boolean uploadPermission) {
  560. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  561. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  562. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  563. updateShareIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, folder.getRemotePath());
  564. updateShareIntent.putExtra(
  565. OperationsService.EXTRA_SHARE_PUBLIC_UPLOAD,
  566. uploadPermission
  567. );
  568. queueShareIntent(updateShareIntent);
  569. }
  570. /**
  571. * Updates a public share on a folder to set its hide file listing permission.
  572. * Starts a request to do it in {@link OperationsService}
  573. *
  574. * @param share {@link OCShare} instance which permissions will be updated.
  575. * @param hideFileListing New state of the permission for editing the folder shared via link.
  576. */
  577. public void setHideFileListingPermissionsToShare(OCShare share, boolean hideFileListing) {
  578. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  579. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  580. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  581. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  582. if (hideFileListing) {
  583. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_PERMISSIONS, OCShare.CREATE_PERMISSION_FLAG);
  584. } else {
  585. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_PERMISSIONS,
  586. OCShare.FEDERATED_PERMISSIONS_FOR_FOLDER_AFTER_OC9);
  587. }
  588. queueShareIntent(updateShareIntent);
  589. }
  590. public void sendShareFile(OCFile file, boolean hideNcSharingOptions) {
  591. // Show dialog
  592. FragmentManager fm = mFileActivity.getSupportFragmentManager();
  593. FragmentTransaction ft = fm.beginTransaction();
  594. ft.addToBackStack(null);
  595. OCCapability capability = mFileActivity.getStorageManager().getCapability(mFileActivity.getAccount().name);
  596. SendShareDialog mSendShareDialog;
  597. if (capability != null) {
  598. mSendShareDialog = SendShareDialog.newInstance(file, hideNcSharingOptions,
  599. capability.getFilesSharingPublicPasswordEnforced().isTrue());
  600. } else {
  601. mSendShareDialog = SendShareDialog.newInstance(file, hideNcSharingOptions, false);
  602. }
  603. mSendShareDialog.setFileOperationsHelper(this);
  604. mSendShareDialog.show(ft, "TAG_SEND_SHARE_DIALOG");
  605. }
  606. public void sendShareFile(OCFile file) {
  607. sendShareFile(file, false);
  608. }
  609. public void syncFiles(Collection<OCFile> files) {
  610. for (OCFile file : files) {
  611. syncFile(file);
  612. }
  613. }
  614. public void sendCachedImage(OCFile file, String packageName, String activityName) {
  615. if (file != null) {
  616. Context context = MainApp.getAppContext();
  617. Intent sendIntent = new Intent(Intent.ACTION_SEND);
  618. // set MimeType
  619. sendIntent.setType(file.getMimeType());
  620. sendIntent.setComponent(new ComponentName(packageName, activityName));
  621. sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://" +
  622. context.getResources().getString(R.string.image_cache_provider_authority) +
  623. file.getRemotePath()));
  624. sendIntent.putExtra(Intent.ACTION_SEND, true); // Send Action
  625. mFileActivity.startActivity(Intent.createChooser(sendIntent,
  626. context.getString(R.string.actionbar_send_file)));
  627. } else {
  628. Log_OC.wtf(TAG, "Trying to send a NULL OCFile");
  629. }
  630. }
  631. public void setPictureAs(OCFile file, View view) {
  632. if (file != null) {
  633. Context context = MainApp.getAppContext();
  634. Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
  635. Uri uri;
  636. try {
  637. if (file.isDown()) {
  638. File externalFile = new File(file.getStoragePath());
  639. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  640. intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
  641. uri = FileProvider.getUriForFile(context,
  642. context.getResources().getString(R.string.file_provider_authority), externalFile);
  643. } else {
  644. uri = Uri.fromFile(externalFile);
  645. }
  646. } else {
  647. uri = Uri.parse(UriUtils.URI_CONTENT_SCHEME +
  648. context.getResources().getString(R.string.image_cache_provider_authority) +
  649. file.getRemotePath());
  650. }
  651. intent.setDataAndType(uri, file.getMimeType());
  652. mFileActivity.startActivityForResult(Intent.createChooser(intent,
  653. mFileActivity.getString(R.string.set_as)), 200);
  654. intent.setDataAndType(uri, file.getMimeType());
  655. } catch (ActivityNotFoundException exception) {
  656. DisplayUtils.showSnackMessage(view, R.string.picture_set_as_no_app);
  657. }
  658. } else {
  659. Log_OC.wtf(TAG, "Trying to send a NULL OCFile");
  660. }
  661. }
  662. /**
  663. * Request the synchronization of a file or folder with the OC server, including its contents.
  664. *
  665. * @param file The file or folder to synchronize
  666. */
  667. public void syncFile(OCFile file) {
  668. if (!file.isFolder()) {
  669. Intent intent = new Intent(mFileActivity, OperationsService.class);
  670. intent.setAction(OperationsService.ACTION_SYNC_FILE);
  671. intent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  672. intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  673. intent.putExtra(OperationsService.EXTRA_SYNC_FILE_CONTENTS, true);
  674. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(intent);
  675. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  676. getString(R.string.wait_a_moment));
  677. } else {
  678. Intent intent = new Intent(mFileActivity, OperationsService.class);
  679. intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
  680. intent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  681. intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  682. mFileActivity.startService(intent);
  683. }
  684. }
  685. public void toggleFavoriteFiles(Collection<OCFile> files, boolean shouldBeFavorite) {
  686. List<OCFile> alreadyRightStateList = new ArrayList<>();
  687. for (OCFile file : files) {
  688. if (file.getIsFavorite() == shouldBeFavorite) {
  689. alreadyRightStateList.add(file);
  690. }
  691. }
  692. files.removeAll(alreadyRightStateList);
  693. for (OCFile file : files) {
  694. toggleFavoriteFile(file, shouldBeFavorite);
  695. }
  696. }
  697. public void toggleFavoriteFile(OCFile file, boolean shouldBeFavorite) {
  698. if (file.getIsFavorite() != shouldBeFavorite) {
  699. EventBus.getDefault().post(new FavoriteEvent(file.getRemotePath(), shouldBeFavorite, file.getRemoteId()));
  700. }
  701. }
  702. public void toggleEncryption(OCFile file, boolean shouldBeEncrypted) {
  703. if (file.isEncrypted() != shouldBeEncrypted) {
  704. EventBus.getDefault().post(new EncryptionEvent(file.getLocalId(), file.getRemoteId(), file.getRemotePath(),
  705. shouldBeEncrypted));
  706. }
  707. }
  708. public void toggleOfflineFiles(Collection<OCFile> files, boolean isAvailableOffline) {
  709. List<OCFile> alreadyRightStateList = new ArrayList<>();
  710. for (OCFile file : files) {
  711. if (file.isAvailableOffline() == isAvailableOffline) {
  712. alreadyRightStateList.add(file);
  713. }
  714. }
  715. files.removeAll(alreadyRightStateList);
  716. for (OCFile file : files) {
  717. toggleOfflineFile(file, isAvailableOffline);
  718. }
  719. }
  720. public void toggleOfflineFile(OCFile file, boolean isAvailableOffline) {
  721. if (file.isAvailableOffline() != isAvailableOffline) {
  722. file.setAvailableOffline(isAvailableOffline);
  723. mFileActivity.getStorageManager().saveFile(file);
  724. /// immediate content synchronization
  725. if (file.isAvailableOffline()) {
  726. syncFile(file);
  727. }
  728. }
  729. }
  730. public void renameFile(OCFile file, String newFilename) {
  731. // RenameFile
  732. Intent service = new Intent(mFileActivity, OperationsService.class);
  733. service.setAction(OperationsService.ACTION_RENAME);
  734. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  735. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  736. service.putExtra(OperationsService.EXTRA_NEWNAME, newFilename);
  737. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  738. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  739. }
  740. /**
  741. * Start operations to delete one or several files
  742. *
  743. * @param files Files to delete
  744. * @param onlyLocalCopy When 'true' only local copy of the files is removed; otherwise files are also deleted
  745. * in the server.
  746. * @param inBackground When 'true', do not show any loading dialog
  747. */
  748. public void removeFiles(Collection<OCFile> files, boolean onlyLocalCopy, boolean inBackground) {
  749. for (OCFile file : files) {
  750. // RemoveFile
  751. Intent service = new Intent(mFileActivity, OperationsService.class);
  752. service.setAction(OperationsService.ACTION_REMOVE);
  753. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  754. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  755. service.putExtra(OperationsService.EXTRA_REMOVE_ONLY_LOCAL, onlyLocalCopy);
  756. service.putExtra(OperationsService.EXTRA_IN_BACKGROUND, inBackground);
  757. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  758. }
  759. if (!inBackground) {
  760. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  761. }
  762. }
  763. public void createFolder(String remotePath, boolean createFullPath) {
  764. // Create Folder
  765. Intent service = new Intent(mFileActivity, OperationsService.class);
  766. service.setAction(OperationsService.ACTION_CREATE_FOLDER);
  767. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  768. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, remotePath);
  769. service.putExtra(OperationsService.EXTRA_CREATE_FULL_PATH, createFullPath);
  770. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  771. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  772. }
  773. /**
  774. * Cancel the transference in downloads (files/folders) and file uploads
  775. *
  776. * @param file OCFile
  777. */
  778. public void cancelTransference(OCFile file) {
  779. Account account = mFileActivity.getAccount();
  780. if (file.isFolder()) {
  781. OperationsService.OperationsServiceBinder opsBinder =
  782. mFileActivity.getOperationsServiceBinder();
  783. if (opsBinder != null) {
  784. opsBinder.cancel(account, file);
  785. }
  786. }
  787. // for both files and folders
  788. FileDownloaderBinder downloaderBinder = mFileActivity.getFileDownloaderBinder();
  789. if (downloaderBinder != null && downloaderBinder.isDownloading(account, file)) {
  790. downloaderBinder.cancel(account, file);
  791. }
  792. FileUploaderBinder uploaderBinder = mFileActivity.getFileUploaderBinder();
  793. if (uploaderBinder != null && uploaderBinder.isUploading(account, file)) {
  794. uploaderBinder.cancel(account, file);
  795. }
  796. }
  797. /**
  798. * Start operations to move one or several files
  799. *
  800. * @param files Files to move
  801. * @param targetFolder Folder where the files while be moved into
  802. */
  803. public void moveFiles(Collection<OCFile> files, OCFile targetFolder) {
  804. for (OCFile file : files) {
  805. Intent service = new Intent(mFileActivity, OperationsService.class);
  806. service.setAction(OperationsService.ACTION_MOVE_FILE);
  807. service.putExtra(OperationsService.EXTRA_NEW_PARENT_PATH, targetFolder.getRemotePath());
  808. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  809. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  810. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  811. }
  812. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  813. }
  814. /**
  815. * Start operations to copy one or several files
  816. *
  817. * @param files Files to copy
  818. * @param targetFolder Folder where the files while be copied into
  819. */
  820. public void copyFiles(Collection<OCFile> files, OCFile targetFolder) {
  821. for (OCFile file : files) {
  822. Intent service = new Intent(mFileActivity, OperationsService.class);
  823. service.setAction(OperationsService.ACTION_COPY_FILE);
  824. service.putExtra(OperationsService.EXTRA_NEW_PARENT_PATH, targetFolder.getRemotePath());
  825. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  826. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  827. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  828. }
  829. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  830. }
  831. public long getOpIdWaitingFor() {
  832. return mWaitingForOpId;
  833. }
  834. public void setOpIdWaitingFor(long waitingForOpId) {
  835. mWaitingForOpId = waitingForOpId;
  836. }
  837. /**
  838. * Starts a check of the currently stored credentials for the given account.
  839. *
  840. * @param account OC account which credentials will be checked.
  841. */
  842. public void checkCurrentCredentials(Account account) {
  843. Intent service = new Intent(mFileActivity, OperationsService.class);
  844. service.setAction(OperationsService.ACTION_CHECK_CURRENT_CREDENTIALS);
  845. service.putExtra(OperationsService.EXTRA_ACCOUNT, account);
  846. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  847. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_checking_credentials));
  848. }
  849. }