FileOperationsHelper.java 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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.services.FileDownloader.FileDownloaderBinder;
  49. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  50. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  51. import com.owncloud.android.lib.common.utils.Log_OC;
  52. import com.owncloud.android.lib.resources.files.CheckEtagOperation;
  53. import com.owncloud.android.lib.resources.files.FileVersion;
  54. import com.owncloud.android.lib.resources.shares.OCShare;
  55. import com.owncloud.android.lib.resources.shares.ShareType;
  56. import com.owncloud.android.lib.resources.status.OCCapability;
  57. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  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. /**
  314. * Helper method to share a file via a public link. Starts a request to do it in {@link OperationsService}
  315. *
  316. * @param file The file to share.
  317. * @param password Optional password to protect the public share.
  318. */
  319. public void shareFileViaLink(OCFile file, String password) {
  320. if (file != null) {
  321. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  322. Intent service = new Intent(mFileActivity, OperationsService.class);
  323. service.setAction(OperationsService.ACTION_CREATE_SHARE_VIA_LINK);
  324. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  325. if (password != null && password.length() > 0) {
  326. service.putExtra(OperationsService.EXTRA_SHARE_PASSWORD, password);
  327. }
  328. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  329. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  330. } else {
  331. Log_OC.e(TAG, "Trying to share a NULL OCFile");
  332. // TODO user-level error?
  333. }
  334. }
  335. public void getFileWithLink(OCFile file) {
  336. if (file != null) {
  337. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  338. getString(R.string.wait_a_moment));
  339. Intent service = new Intent(mFileActivity, OperationsService.class);
  340. service.setAction(OperationsService.ACTION_CREATE_SHARE_VIA_LINK);
  341. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  342. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  343. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  344. } else {
  345. Log_OC.e(TAG, "Trying to share a NULL OCFile");
  346. }
  347. }
  348. /**
  349. * Helper method to share a file with a known sharee. Starts a request to do it in {@link OperationsService}
  350. *
  351. * @param file The file to share.
  352. * @param shareeName Name (user name or group name) of the target sharee.
  353. * @param shareType The share type determines the sharee type.
  354. * @param permissions Permissions to grant to sharee on the shared file.
  355. */
  356. public void shareFileWithSharee(OCFile file, String shareeName, ShareType shareType, int permissions) {
  357. if (file != null) {
  358. // TODO check capability?
  359. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  360. getString(R.string.wait_a_moment));
  361. Intent service = new Intent(mFileActivity, OperationsService.class);
  362. service.setAction(OperationsService.ACTION_CREATE_SHARE_WITH_SHAREE);
  363. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  364. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  365. service.putExtra(OperationsService.EXTRA_SHARE_WITH, shareeName);
  366. service.putExtra(OperationsService.EXTRA_SHARE_TYPE, shareType);
  367. service.putExtra(OperationsService.EXTRA_SHARE_PERMISSIONS, permissions);
  368. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  369. } else {
  370. Log_OC.e(TAG, "Trying to share a NULL OCFile");
  371. }
  372. }
  373. /**
  374. * Helper method to revert to a file version. Starts a request to do it in {@link OperationsService}
  375. *
  376. * @param fileVersion The file version to restore
  377. * @param userId userId of current account
  378. */
  379. public void restoreFileVersion(FileVersion fileVersion, String userId) {
  380. if (fileVersion != null) {
  381. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  382. getString(R.string.wait_a_moment));
  383. Intent service = new Intent(mFileActivity, OperationsService.class);
  384. service.setAction(OperationsService.ACTION_RESTORE_VERSION);
  385. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  386. service.putExtra(OperationsService.EXTRA_FILE_VERSION, fileVersion);
  387. service.putExtra(OperationsService.EXTRA_USER_ID, userId);
  388. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  389. } else {
  390. Log_OC.e(TAG, "Trying to restore a NULL FileVersion");
  391. }
  392. }
  393. /**
  394. * @return 'True' if the server supports the Share API
  395. */
  396. public boolean isSharedSupported() {
  397. return mFileActivity.getAccount() != null &&
  398. AccountUtils.getServerVersion(mFileActivity.getAccount()).isSharedSupported();
  399. }
  400. /**
  401. * Helper method to unshare a file publicly shared via link.
  402. * Starts a request to do it in {@link OperationsService}
  403. *
  404. * @param file The file to unshare.
  405. */
  406. public void unshareFileViaLink(OCFile file) {
  407. // Unshare the file: Create the intent
  408. Intent unshareService = new Intent(mFileActivity, OperationsService.class);
  409. unshareService.setAction(OperationsService.ACTION_UNSHARE);
  410. unshareService.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  411. unshareService.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  412. unshareService.putExtra(OperationsService.EXTRA_SHARE_TYPE, ShareType.PUBLIC_LINK);
  413. unshareService.putExtra(OperationsService.EXTRA_SHARE_WITH, "");
  414. queueShareIntent(unshareService);
  415. }
  416. public void unshareFileWithUserOrGroup(OCFile file, ShareType shareType, String userOrGroup) {
  417. // Unshare the file: Create the intent
  418. Intent unshareService = new Intent(mFileActivity, OperationsService.class);
  419. unshareService.setAction(OperationsService.ACTION_UNSHARE);
  420. unshareService.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  421. unshareService.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  422. unshareService.putExtra(OperationsService.EXTRA_SHARE_TYPE, shareType);
  423. unshareService.putExtra(OperationsService.EXTRA_SHARE_WITH, userOrGroup);
  424. queueShareIntent(unshareService);
  425. }
  426. private void queueShareIntent(Intent shareIntent) {
  427. // Unshare the file
  428. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(shareIntent);
  429. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().getString(R.string.wait_a_moment));
  430. }
  431. /**
  432. * Show an instance of {@link ShareType} for sharing or unsharing the {@link OCFile} received as parameter.
  433. *
  434. * @param file File to share or unshare.
  435. */
  436. public void showShareFile(OCFile file) {
  437. Intent intent = new Intent(mFileActivity, ShareActivity.class);
  438. intent.putExtra(FileActivity.EXTRA_FILE, file);
  439. intent.putExtra(FileActivity.EXTRA_ACCOUNT, mFileActivity.getAccount());
  440. mFileActivity.startActivity(intent);
  441. }
  442. /**
  443. * Updates a public share on a file to set its password.
  444. * Starts a request to do it in {@link OperationsService}
  445. *
  446. * @param file File which public share will be protected with a password.
  447. * @param password Password to set for the public link; null or empty string to clear
  448. * the current password
  449. */
  450. public void setPasswordToShareViaLink(OCFile file, String password) {
  451. // Set password updating share
  452. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  453. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  454. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  455. updateShareIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  456. updateShareIntent.putExtra(
  457. OperationsService.EXTRA_SHARE_PASSWORD,
  458. (password == null) ? "" : password
  459. );
  460. queueShareIntent(updateShareIntent);
  461. }
  462. /**
  463. * Updates a share on a file to set its password.
  464. * Starts a request to do it in {@link OperationsService}
  465. *
  466. * @param share File which share will be protected with a password.
  467. * @param password Password to set for the public link; null or empty string to clear
  468. * the current password
  469. */
  470. public void setPasswordToShare(OCShare share, String password) {
  471. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  472. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  473. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  474. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  475. updateShareIntent.putExtra(
  476. OperationsService.EXTRA_SHARE_PASSWORD,
  477. (password == null) ? "" : password
  478. );
  479. queueShareIntent(updateShareIntent);
  480. }
  481. /**
  482. * Updates a public share on a file to set its expiration date.
  483. * Starts a request to do it in {@link OperationsService}
  484. *
  485. * @param file File which public share will be constrained with an expiration date.
  486. * @param expirationTimeInMillis Expiration date to set. A negative value clears the current expiration
  487. * date, leaving the link unrestricted. Zero makes no change.
  488. */
  489. public void setExpirationDateToShareViaLink(OCFile file, long expirationTimeInMillis) {
  490. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  491. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  492. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  493. updateShareIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  494. updateShareIntent.putExtra(
  495. OperationsService.EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS,
  496. expirationTimeInMillis
  497. );
  498. queueShareIntent(updateShareIntent);
  499. }
  500. /**
  501. * Updates a public share on a file to set its expiration date.
  502. * Starts a request to do it in {@link OperationsService}
  503. *
  504. * @param share {@link OCShare} instance which permissions will be updated.
  505. * @param expirationTimeInMillis Expiration date to set. A negative value clears the current expiration
  506. * date, leaving the link unrestricted. Zero makes no change.
  507. */
  508. public void setExpirationDateToShare(OCShare share, long expirationTimeInMillis) {
  509. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  510. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  511. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  512. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  513. updateShareIntent.putExtra(
  514. OperationsService.EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS,
  515. expirationTimeInMillis
  516. );
  517. updateShareIntent.putExtra(
  518. OperationsService.EXTRA_SHARE_PERMISSIONS,
  519. 0
  520. );
  521. queueShareIntent(updateShareIntent);
  522. }
  523. /**
  524. * Updates a share on a file to set its access permissions.
  525. * Starts a request to do it in {@link OperationsService}
  526. *
  527. * @param share {@link OCShare} instance which permissions will be updated.
  528. * @param permissions New permissions to set. A value <= 0 makes no update.
  529. */
  530. public void setPermissionsToShare(OCShare share, int permissions) {
  531. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  532. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  533. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  534. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  535. updateShareIntent.putExtra(
  536. OperationsService.EXTRA_SHARE_PERMISSIONS,
  537. permissions
  538. );
  539. queueShareIntent(updateShareIntent);
  540. }
  541. /**
  542. * Updates a public share on a folder to set its editing permission.
  543. * Starts a request to do it in {@link OperationsService}
  544. *
  545. * @param folder Folder which editing permission of his public share will be modified.
  546. * @param uploadPermission New state of the permission for editing the folder shared via link.
  547. */
  548. public void setUploadPermissionsToShare(OCFile folder, boolean uploadPermission) {
  549. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  550. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  551. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  552. updateShareIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, folder.getRemotePath());
  553. updateShareIntent.putExtra(
  554. OperationsService.EXTRA_SHARE_PUBLIC_UPLOAD,
  555. uploadPermission
  556. );
  557. queueShareIntent(updateShareIntent);
  558. }
  559. /**
  560. * Updates a public share on a folder to set its hide file listing permission.
  561. * Starts a request to do it in {@link OperationsService}
  562. *
  563. * @param share {@link OCShare} instance which permissions will be updated.
  564. * @param hideFileListing New state of the permission for editing the folder shared via link.
  565. */
  566. public void setHideFileListingPermissionsToShare(OCShare share, boolean hideFileListing) {
  567. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  568. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  569. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  570. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  571. if (hideFileListing) {
  572. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_PERMISSIONS, OCShare.CREATE_PERMISSION_FLAG);
  573. } else {
  574. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_PERMISSIONS,
  575. OCShare.FEDERATED_PERMISSIONS_FOR_FOLDER_AFTER_OC9);
  576. }
  577. queueShareIntent(updateShareIntent);
  578. }
  579. public void sendShareFile(OCFile file, boolean hideNcSharingOptions) {
  580. // Show dialog
  581. FragmentManager fm = mFileActivity.getSupportFragmentManager();
  582. FragmentTransaction ft = fm.beginTransaction();
  583. ft.addToBackStack(null);
  584. OCCapability capability = mFileActivity.getStorageManager().getCapability(mFileActivity.getAccount().name);
  585. SendShareDialog mSendShareDialog;
  586. if (capability != null) {
  587. mSendShareDialog = SendShareDialog.newInstance(file, hideNcSharingOptions,
  588. capability.getFilesSharingPublicPasswordEnforced().isTrue());
  589. } else {
  590. mSendShareDialog = SendShareDialog.newInstance(file, hideNcSharingOptions, false);
  591. }
  592. mSendShareDialog.setFileOperationsHelper(this);
  593. mSendShareDialog.show(ft, "TAG_SEND_SHARE_DIALOG");
  594. }
  595. public void sendShareFile(OCFile file) {
  596. sendShareFile(file, false);
  597. }
  598. public void syncFiles(Collection<OCFile> files) {
  599. for (OCFile file : files) {
  600. syncFile(file);
  601. }
  602. }
  603. public void sendCachedImage(OCFile file, String packageName, String activityName) {
  604. if (file != null) {
  605. Context context = MainApp.getAppContext();
  606. Intent sendIntent = new Intent(Intent.ACTION_SEND);
  607. // set MimeType
  608. sendIntent.setType(file.getMimeType());
  609. sendIntent.setComponent(new ComponentName(packageName, activityName));
  610. sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://" +
  611. context.getResources().getString(R.string.image_cache_provider_authority) +
  612. file.getRemotePath()));
  613. sendIntent.putExtra(Intent.ACTION_SEND, true); // Send Action
  614. mFileActivity.startActivity(Intent.createChooser(sendIntent,
  615. context.getString(R.string.actionbar_send_file)));
  616. } else {
  617. Log_OC.wtf(TAG, "Trying to send a NULL OCFile");
  618. }
  619. }
  620. public void setPictureAs(OCFile file, View view) {
  621. if (file != null) {
  622. Context context = MainApp.getAppContext();
  623. Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
  624. Uri uri;
  625. try {
  626. if (file.isDown()) {
  627. File externalFile = new File(file.getStoragePath());
  628. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  629. intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
  630. uri = FileProvider.getUriForFile(context,
  631. context.getResources().getString(R.string.file_provider_authority), externalFile);
  632. } else {
  633. uri = Uri.fromFile(externalFile);
  634. }
  635. } else {
  636. uri = Uri.parse(UriUtils.URI_CONTENT_SCHEME +
  637. context.getResources().getString(R.string.image_cache_provider_authority) +
  638. file.getRemotePath());
  639. }
  640. intent.setDataAndType(uri, file.getMimeType());
  641. mFileActivity.startActivityForResult(Intent.createChooser(intent,
  642. mFileActivity.getString(R.string.set_as)), 200);
  643. intent.setDataAndType(uri, file.getMimeType());
  644. } catch (ActivityNotFoundException exception) {
  645. DisplayUtils.showSnackMessage(view, R.string.picture_set_as_no_app);
  646. }
  647. } else {
  648. Log_OC.wtf(TAG, "Trying to send a NULL OCFile");
  649. }
  650. }
  651. /**
  652. * Request the synchronization of a file or folder with the OC server, including its contents.
  653. *
  654. * @param file The file or folder to synchronize
  655. */
  656. public void syncFile(OCFile file) {
  657. if (!file.isFolder()) {
  658. Intent intent = new Intent(mFileActivity, OperationsService.class);
  659. intent.setAction(OperationsService.ACTION_SYNC_FILE);
  660. intent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  661. intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  662. intent.putExtra(OperationsService.EXTRA_SYNC_FILE_CONTENTS, true);
  663. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(intent);
  664. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  665. getString(R.string.wait_a_moment));
  666. } else {
  667. Intent intent = new Intent(mFileActivity, OperationsService.class);
  668. intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
  669. intent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  670. intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  671. mFileActivity.startService(intent);
  672. }
  673. }
  674. public void toggleFavoriteFiles(Collection<OCFile> files, boolean shouldBeFavorite) {
  675. List<OCFile> alreadyRightStateList = new ArrayList<>();
  676. for (OCFile file : files) {
  677. if (file.getIsFavorite() == shouldBeFavorite) {
  678. alreadyRightStateList.add(file);
  679. }
  680. }
  681. files.removeAll(alreadyRightStateList);
  682. for (OCFile file : files) {
  683. toggleFavoriteFile(file, shouldBeFavorite);
  684. }
  685. }
  686. public void toggleFavoriteFile(OCFile file, boolean shouldBeFavorite) {
  687. if (file.getIsFavorite() != shouldBeFavorite) {
  688. EventBus.getDefault().post(new FavoriteEvent(file.getRemotePath(), shouldBeFavorite, file.getRemoteId()));
  689. }
  690. }
  691. public void toggleEncryption(OCFile file, boolean shouldBeEncrypted) {
  692. if (file.isEncrypted() != shouldBeEncrypted) {
  693. EventBus.getDefault().post(new EncryptionEvent(file.getLocalId(), file.getRemoteId(), file.getRemotePath(),
  694. shouldBeEncrypted));
  695. }
  696. }
  697. public void toggleOfflineFiles(Collection<OCFile> files, boolean isAvailableOffline) {
  698. List<OCFile> alreadyRightStateList = new ArrayList<>();
  699. for (OCFile file : files) {
  700. if (file.isAvailableOffline() == isAvailableOffline) {
  701. alreadyRightStateList.add(file);
  702. }
  703. }
  704. files.removeAll(alreadyRightStateList);
  705. for (OCFile file : files) {
  706. toggleOfflineFile(file, isAvailableOffline);
  707. }
  708. }
  709. public void toggleOfflineFile(OCFile file, boolean isAvailableOffline) {
  710. if (file.isAvailableOffline() != isAvailableOffline) {
  711. file.setAvailableOffline(isAvailableOffline);
  712. mFileActivity.getStorageManager().saveFile(file);
  713. /// immediate content synchronization
  714. if (file.isAvailableOffline()) {
  715. syncFile(file);
  716. }
  717. }
  718. }
  719. public void renameFile(OCFile file, String newFilename) {
  720. // RenameFile
  721. Intent service = new Intent(mFileActivity, OperationsService.class);
  722. service.setAction(OperationsService.ACTION_RENAME);
  723. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  724. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  725. service.putExtra(OperationsService.EXTRA_NEWNAME, newFilename);
  726. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  727. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  728. }
  729. /**
  730. * Start operations to delete one or several files
  731. *
  732. * @param files Files to delete
  733. * @param onlyLocalCopy When 'true' only local copy of the files is removed; otherwise files are also deleted
  734. * in the server.
  735. * @param inBackground When 'true', do not show any loading dialog
  736. */
  737. public void removeFiles(Collection<OCFile> files, boolean onlyLocalCopy, boolean inBackground) {
  738. for (OCFile file : files) {
  739. // RemoveFile
  740. Intent service = new Intent(mFileActivity, OperationsService.class);
  741. service.setAction(OperationsService.ACTION_REMOVE);
  742. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  743. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  744. service.putExtra(OperationsService.EXTRA_REMOVE_ONLY_LOCAL, onlyLocalCopy);
  745. service.putExtra(OperationsService.EXTRA_IN_BACKGROUND, inBackground);
  746. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  747. }
  748. if (!inBackground) {
  749. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  750. }
  751. }
  752. public void createFolder(String remotePath, boolean createFullPath) {
  753. // Create Folder
  754. Intent service = new Intent(mFileActivity, OperationsService.class);
  755. service.setAction(OperationsService.ACTION_CREATE_FOLDER);
  756. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  757. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, remotePath);
  758. service.putExtra(OperationsService.EXTRA_CREATE_FULL_PATH, createFullPath);
  759. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  760. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  761. }
  762. /**
  763. * Cancel the transference in downloads (files/folders) and file uploads
  764. *
  765. * @param file OCFile
  766. */
  767. public void cancelTransference(OCFile file) {
  768. Account account = mFileActivity.getAccount();
  769. if (file.isFolder()) {
  770. OperationsService.OperationsServiceBinder opsBinder =
  771. mFileActivity.getOperationsServiceBinder();
  772. if (opsBinder != null) {
  773. opsBinder.cancel(account, file);
  774. }
  775. }
  776. // for both files and folders
  777. FileDownloaderBinder downloaderBinder = mFileActivity.getFileDownloaderBinder();
  778. if (downloaderBinder != null && downloaderBinder.isDownloading(account, file)) {
  779. downloaderBinder.cancel(account, file);
  780. }
  781. FileUploaderBinder uploaderBinder = mFileActivity.getFileUploaderBinder();
  782. if (uploaderBinder != null && uploaderBinder.isUploading(account, file)) {
  783. uploaderBinder.cancel(account, file);
  784. }
  785. }
  786. /**
  787. * Start operations to move one or several files
  788. *
  789. * @param files Files to move
  790. * @param targetFolder Folder where the files while be moved into
  791. */
  792. public void moveFiles(Collection<OCFile> files, OCFile targetFolder) {
  793. for (OCFile file : files) {
  794. Intent service = new Intent(mFileActivity, OperationsService.class);
  795. service.setAction(OperationsService.ACTION_MOVE_FILE);
  796. service.putExtra(OperationsService.EXTRA_NEW_PARENT_PATH, targetFolder.getRemotePath());
  797. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  798. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  799. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  800. }
  801. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  802. }
  803. /**
  804. * Start operations to copy one or several files
  805. *
  806. * @param files Files to copy
  807. * @param targetFolder Folder where the files while be copied into
  808. */
  809. public void copyFiles(Collection<OCFile> files, OCFile targetFolder) {
  810. for (OCFile file : files) {
  811. Intent service = new Intent(mFileActivity, OperationsService.class);
  812. service.setAction(OperationsService.ACTION_COPY_FILE);
  813. service.putExtra(OperationsService.EXTRA_NEW_PARENT_PATH, targetFolder.getRemotePath());
  814. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  815. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  816. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  817. }
  818. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  819. }
  820. public long getOpIdWaitingFor() {
  821. return mWaitingForOpId;
  822. }
  823. public void setOpIdWaitingFor(long waitingForOpId) {
  824. mWaitingForOpId = waitingForOpId;
  825. }
  826. /**
  827. * Starts a check of the currently stored credentials for the given account.
  828. *
  829. * @param account OC account which credentials will be checked.
  830. */
  831. public void checkCurrentCredentials(Account account) {
  832. Intent service = new Intent(mFileActivity, OperationsService.class);
  833. service.setAction(OperationsService.ACTION_CHECK_CURRENT_CREDENTIALS);
  834. service.putExtra(OperationsService.EXTRA_ACCOUNT, account);
  835. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  836. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_checking_credentials));
  837. }
  838. }