FileOperationsHelper.java 41 KB

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