FileOperationsHelper.java 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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.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. final Intent openFileWithIntent = createOpenFileIntent(file);
  215. List<ResolveInfo> launchables = mFileActivity.getPackageManager().
  216. queryIntentActivities(openFileWithIntent, PackageManager.GET_RESOLVED_FILTER);
  217. mFileActivity.showLoadingDialog(mFileActivity.getResources().getString(R.string.sync_in_progress));
  218. new Thread(new Runnable() {
  219. @Override
  220. public void run() {
  221. Account account = AccountUtils.getCurrentOwnCloudAccount(mFileActivity);
  222. FileDataStorageManager storageManager =
  223. new FileDataStorageManager(account, mFileActivity.getContentResolver());
  224. // a fresh object is needed; many things could have occurred to the file
  225. // since it was registered to observe again, assuming that local files
  226. // are linked to a remote file AT MOST, SOMETHING TO BE DONE;
  227. SynchronizeFileOperation sfo =
  228. new SynchronizeFileOperation(file, null, account, true, mFileActivity);
  229. RemoteOperationResult result = sfo.execute(storageManager, mFileActivity);
  230. mFileActivity.dismissLoadingDialog();
  231. if (result.getCode() == RemoteOperationResult.ResultCode.SYNC_CONFLICT) {
  232. // ISSUE 5: if the user is not running the app (this is a service!),
  233. // this can be very intrusive; a notification should be preferred
  234. Intent i = new Intent(mFileActivity, ConflictsResolveActivity.class);
  235. i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
  236. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, file);
  237. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, account);
  238. mFileActivity.startActivity(i);
  239. } else {
  240. if (launchables != null && launchables.size() > 0) {
  241. try {
  242. if (!result.isSuccess()) {
  243. DisplayUtils.showSnackMessage(mFileActivity, R.string.file_not_synced);
  244. try {
  245. Thread.sleep(3000);
  246. } catch (InterruptedException e) {
  247. Log.e(TAG, "Failed to sleep");
  248. }
  249. }
  250. mFileActivity.startActivity(
  251. Intent.createChooser(
  252. openFileWithIntent,
  253. mFileActivity.getString(R.string.actionbar_open_with)
  254. )
  255. );
  256. } catch (ActivityNotFoundException exception) {
  257. DisplayUtils.showSnackMessage(mFileActivity, R.string.file_list_no_app_for_file_type);
  258. }
  259. } else {
  260. DisplayUtils.showSnackMessage(mFileActivity, R.string.file_list_no_app_for_file_type);
  261. }
  262. }
  263. }
  264. }).start();
  265. } else {
  266. Log_OC.e(TAG, "Trying to open a NULL OCFile");
  267. }
  268. }
  269. @NonNull
  270. private Intent createOpenFileIntent(OCFile file) {
  271. String storagePath = file.getStoragePath();
  272. Uri fileUri = getFileUri(file, MainApp.getAppContext().getResources().getStringArray(R.array
  273. .ms_office_extensions));
  274. Intent openFileWithIntent = null;
  275. int lastIndexOfDot = storagePath.lastIndexOf('.');
  276. if (lastIndexOfDot >= 0) {
  277. String fileExt = storagePath.substring(lastIndexOfDot + 1);
  278. String guessedMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExt);
  279. if (guessedMimeType != null) {
  280. openFileWithIntent = new Intent(Intent.ACTION_VIEW);
  281. openFileWithIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  282. openFileWithIntent.setDataAndType(
  283. fileUri,
  284. guessedMimeType
  285. );
  286. }
  287. }
  288. if (openFileWithIntent == null) {
  289. openFileWithIntent = createIntentFromFile(storagePath);
  290. }
  291. if (openFileWithIntent == null) {
  292. openFileWithIntent = new Intent(Intent.ACTION_VIEW);
  293. openFileWithIntent.setDataAndType(
  294. fileUri,
  295. file.getMimetype()
  296. );
  297. }
  298. openFileWithIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  299. return openFileWithIntent;
  300. }
  301. private Uri getFileUri(OCFile file, String[] officeExtensions) {
  302. if (file.getFileName().contains(".") &&
  303. Arrays.asList(officeExtensions).contains(file.getFileName().substring(file.getFileName().
  304. lastIndexOf(".") + 1, file.getFileName().length())) &&
  305. !file.getStoragePath().startsWith(MainApp.getAppContext().getFilesDir().getAbsolutePath())) {
  306. return file.getLegacyExposedFileUri(mFileActivity);
  307. } else {
  308. return file.getExposedFileUri(mFileActivity);
  309. }
  310. }
  311. /**
  312. * Helper method to share a file via a public link. Starts a request to do it in {@link OperationsService}
  313. *
  314. * @param file The file to share.
  315. * @param password Optional password to protect the public share.
  316. */
  317. public void shareFileViaLink(OCFile file, String password) {
  318. if (isSharedSupported()) {
  319. if (file != null) {
  320. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  321. Intent service = new Intent(mFileActivity, OperationsService.class);
  322. service.setAction(OperationsService.ACTION_CREATE_SHARE_VIA_LINK);
  323. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  324. if (password != null && password.length() > 0) {
  325. service.putExtra(OperationsService.EXTRA_SHARE_PASSWORD, password);
  326. }
  327. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  328. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  329. } else {
  330. Log_OC.e(TAG, "Trying to share a NULL OCFile");
  331. // TODO user-level error?
  332. }
  333. } else {
  334. // Show a Message
  335. DisplayUtils.showSnackMessage(mFileActivity, R.string.share_link_no_support_share_api);
  336. }
  337. }
  338. public void getFileWithLink(OCFile file) {
  339. if (isSharedSupported()) {
  340. if (file != null) {
  341. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  342. getString(R.string.wait_a_moment));
  343. Intent service = new Intent(mFileActivity, OperationsService.class);
  344. service.setAction(OperationsService.ACTION_CREATE_SHARE_VIA_LINK);
  345. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  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. }
  351. } else {
  352. // Show a Message
  353. DisplayUtils.showSnackMessage(mFileActivity, R.string.share_link_no_support_share_api);
  354. }
  355. }
  356. /**
  357. * Helper method to share a file with a known sharee. Starts a request to do it in {@link OperationsService}
  358. *
  359. * @param file The file to share.
  360. * @param shareeName Name (user name or group name) of the target sharee.
  361. * @param shareType The share type determines the sharee type.
  362. * @param permissions Permissions to grant to sharee on the shared file.
  363. */
  364. public void shareFileWithSharee(OCFile file, String shareeName, ShareType shareType, int permissions) {
  365. if (file != null) {
  366. // TODO check capability?
  367. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  368. getString(R.string.wait_a_moment));
  369. Intent service = new Intent(mFileActivity, OperationsService.class);
  370. service.setAction(OperationsService.ACTION_CREATE_SHARE_WITH_SHAREE);
  371. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  372. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  373. service.putExtra(OperationsService.EXTRA_SHARE_WITH, shareeName);
  374. service.putExtra(OperationsService.EXTRA_SHARE_TYPE, shareType);
  375. service.putExtra(OperationsService.EXTRA_SHARE_PERMISSIONS, permissions);
  376. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  377. } else {
  378. Log_OC.e(TAG, "Trying to share a NULL OCFile");
  379. }
  380. }
  381. /**
  382. * @return 'True' if the server supports the Share API
  383. */
  384. public boolean isSharedSupported() {
  385. if (mFileActivity.getAccount() != null) {
  386. return AccountUtils.getServerVersion(mFileActivity.getAccount()).isSharedSupported();
  387. }
  388. return false;
  389. }
  390. /**
  391. * Helper method to unshare a file publicly shared via link.
  392. * Starts a request to do it in {@link OperationsService}
  393. *
  394. * @param file The file to unshare.
  395. */
  396. public void unshareFileViaLink(OCFile file) {
  397. // Unshare the file: Create the intent
  398. Intent unshareService = new Intent(mFileActivity, OperationsService.class);
  399. unshareService.setAction(OperationsService.ACTION_UNSHARE);
  400. unshareService.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  401. unshareService.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  402. unshareService.putExtra(OperationsService.EXTRA_SHARE_TYPE, ShareType.PUBLIC_LINK);
  403. unshareService.putExtra(OperationsService.EXTRA_SHARE_WITH, "");
  404. queueShareIntent(unshareService);
  405. }
  406. public void unshareFileWithUserOrGroup(OCFile file, ShareType shareType, String userOrGroup) {
  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);
  413. unshareService.putExtra(OperationsService.EXTRA_SHARE_WITH, userOrGroup);
  414. queueShareIntent(unshareService);
  415. }
  416. private void queueShareIntent(Intent shareIntent) {
  417. if (isSharedSupported()) {
  418. // Unshare the file
  419. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().
  420. queueNewOperation(shareIntent);
  421. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  422. getString(R.string.wait_a_moment));
  423. } else {
  424. // Show a Message
  425. DisplayUtils.showSnackMessage(mFileActivity, R.string.share_link_no_support_share_api);
  426. }
  427. }
  428. /**
  429. * Show an instance of {@link ShareType} for sharing or unsharing the {@link OCFile} received as parameter.
  430. *
  431. * @param file File to share or unshare.
  432. */
  433. public void showShareFile(OCFile file) {
  434. Intent intent = new Intent(mFileActivity, ShareActivity.class);
  435. intent.putExtra(FileActivity.EXTRA_FILE, file);
  436. intent.putExtra(FileActivity.EXTRA_ACCOUNT, mFileActivity.getAccount());
  437. mFileActivity.startActivity(intent);
  438. }
  439. /**
  440. * Updates a public share on a file to set its password.
  441. * Starts a request to do it in {@link OperationsService}
  442. *
  443. * @param file File which public share will be protected with a password.
  444. * @param password Password to set for the public link; null or empty string to clear
  445. * the current password
  446. */
  447. public void setPasswordToShareViaLink(OCFile file, String password) {
  448. // Set password updating share
  449. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  450. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  451. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  452. updateShareIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  453. updateShareIntent.putExtra(
  454. OperationsService.EXTRA_SHARE_PASSWORD,
  455. (password == null) ? "" : password
  456. );
  457. queueShareIntent(updateShareIntent);
  458. }
  459. /**
  460. * Updates a share on a file to set its password.
  461. * Starts a request to do it in {@link OperationsService}
  462. *
  463. * @param share File which share will be protected with a password.
  464. * @param password Password to set for the public link; null or empty string to clear
  465. * the current password
  466. */
  467. public void setPasswordToShare(OCShare share, String password) {
  468. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  469. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  470. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  471. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  472. updateShareIntent.putExtra(
  473. OperationsService.EXTRA_SHARE_PASSWORD,
  474. (password == null) ? "" : password
  475. );
  476. queueShareIntent(updateShareIntent);
  477. }
  478. /**
  479. * Updates a public share on a file to set its expiration date.
  480. * Starts a request to do it in {@link OperationsService}
  481. *
  482. * @param file File which public share will be constrained with an expiration date.
  483. * @param expirationTimeInMillis Expiration date to set. A negative value clears the current expiration
  484. * date, leaving the link unrestricted. Zero makes no change.
  485. */
  486. public void setExpirationDateToShareViaLink(OCFile file, long expirationTimeInMillis) {
  487. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  488. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  489. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  490. updateShareIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  491. updateShareIntent.putExtra(
  492. OperationsService.EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS,
  493. expirationTimeInMillis
  494. );
  495. queueShareIntent(updateShareIntent);
  496. }
  497. /**
  498. * Updates a public share on a file to set its expiration date.
  499. * Starts a request to do it in {@link OperationsService}
  500. *
  501. * @param share {@link OCShare} instance which permissions will be updated.
  502. * @param expirationTimeInMillis Expiration date to set. A negative value clears the current expiration
  503. * date, leaving the link unrestricted. Zero makes no change.
  504. */
  505. public void setExpirationDateToShare(OCShare share, long expirationTimeInMillis) {
  506. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  507. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  508. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  509. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  510. updateShareIntent.putExtra(
  511. OperationsService.EXTRA_SHARE_EXPIRATION_DATE_IN_MILLIS,
  512. expirationTimeInMillis
  513. );
  514. updateShareIntent.putExtra(
  515. OperationsService.EXTRA_SHARE_PERMISSIONS,
  516. 0
  517. );
  518. queueShareIntent(updateShareIntent);
  519. }
  520. /**
  521. * Updates a share on a file to set its access permissions.
  522. * Starts a request to do it in {@link OperationsService}
  523. *
  524. * @param share {@link OCShare} instance which permissions will be updated.
  525. * @param permissions New permissions to set. A value <= 0 makes no update.
  526. */
  527. public void setPermissionsToShare(OCShare share, int permissions) {
  528. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  529. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  530. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  531. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  532. updateShareIntent.putExtra(
  533. OperationsService.EXTRA_SHARE_PERMISSIONS,
  534. permissions
  535. );
  536. queueShareIntent(updateShareIntent);
  537. }
  538. /**
  539. * Updates a public share on a folder to set its editing permission.
  540. * Starts a request to do it in {@link OperationsService}
  541. *
  542. * @param folder Folder which editing permission of his public share will be modified.
  543. * @param uploadPermission New state of the permission for editing the folder shared via link.
  544. */
  545. public void setUploadPermissionsToShare(OCFile folder, boolean uploadPermission) {
  546. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  547. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  548. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  549. updateShareIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, folder.getRemotePath());
  550. updateShareIntent.putExtra(
  551. OperationsService.EXTRA_SHARE_PUBLIC_UPLOAD,
  552. uploadPermission
  553. );
  554. queueShareIntent(updateShareIntent);
  555. }
  556. /**
  557. * Updates a public share on a folder to set its hide file listing permission.
  558. * Starts a request to do it in {@link OperationsService}
  559. *
  560. * @param share {@link OCShare} instance which permissions will be updated.
  561. * @param hideFileListing New state of the permission for editing the folder shared via link.
  562. */
  563. public void setHideFileListingPermissionsToShare(OCShare share, boolean hideFileListing) {
  564. Intent updateShareIntent = new Intent(mFileActivity, OperationsService.class);
  565. updateShareIntent.setAction(OperationsService.ACTION_UPDATE_SHARE);
  566. updateShareIntent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  567. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_ID, share.getId());
  568. if (hideFileListing) {
  569. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_PERMISSIONS, OCShare.CREATE_PERMISSION_FLAG);
  570. } else {
  571. if (AccountUtils.getServerVersion(mFileActivity.getAccount()).isNotReshareableFederatedSupported()) {
  572. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_PERMISSIONS,
  573. OCShare.FEDERATED_PERMISSIONS_FOR_FOLDER_AFTER_OC9);
  574. } else {
  575. updateShareIntent.putExtra(OperationsService.EXTRA_SHARE_PERMISSIONS,
  576. OCShare.FEDERATED_PERMISSIONS_FOR_FOLDER_UP_TO_OC9);
  577. }
  578. }
  579. queueShareIntent(updateShareIntent);
  580. }
  581. /**
  582. * @return 'True' if the server supports the Search Users API
  583. */
  584. public boolean isSearchUserSupportedSupported() {
  585. if (mFileActivity.getAccount() != null) {
  586. OwnCloudVersion serverVersion = AccountUtils.getServerVersion(mFileActivity.getAccount());
  587. return serverVersion.isSearchUsersSupported();
  588. }
  589. return false;
  590. }
  591. public void sendShareFile(OCFile file, boolean hideNcSharingOptions) {
  592. // Show dialog
  593. FragmentManager fm = mFileActivity.getSupportFragmentManager();
  594. FragmentTransaction ft = fm.beginTransaction();
  595. ft.addToBackStack(null);
  596. SendShareDialog mSendShareDialog = SendShareDialog.newInstance(file, hideNcSharingOptions);
  597. mSendShareDialog.setFileOperationsHelper(this);
  598. mSendShareDialog.show(ft, "TAG_SEND_SHARE_DIALOG");
  599. }
  600. public void sendShareFile(OCFile file) {
  601. sendShareFile(file, false);
  602. }
  603. public void syncFiles(Collection<OCFile> files) {
  604. for (OCFile file : files) {
  605. syncFile(file);
  606. }
  607. }
  608. public void sendCachedImage(OCFile file, String packageName, String activityName) {
  609. if (file != null) {
  610. Context context = MainApp.getAppContext();
  611. Intent sendIntent = new Intent(Intent.ACTION_SEND);
  612. // set MimeType
  613. sendIntent.setType(file.getMimetype());
  614. sendIntent.setComponent(new ComponentName(packageName, activityName));
  615. sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://" +
  616. context.getResources().getString(R.string.image_cache_provider_authority) +
  617. file.getRemotePath()));
  618. sendIntent.putExtra(Intent.ACTION_SEND, true); // Send Action
  619. mFileActivity.startActivity(Intent.createChooser(sendIntent,
  620. context.getString(R.string.actionbar_send_file)));
  621. } else {
  622. Log_OC.wtf(TAG, "Trying to send a NULL OCFile");
  623. }
  624. }
  625. public void setPictureAs(OCFile file, View view) {
  626. if (file != null) {
  627. Context context = MainApp.getAppContext();
  628. Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
  629. Uri uri;
  630. try {
  631. if (file.isDown()) {
  632. File externalFile = new File(file.getStoragePath());
  633. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  634. intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
  635. uri = FileProvider.getUriForFile(context,
  636. context.getResources().getString(R.string.file_provider_authority), externalFile);
  637. } else {
  638. uri = Uri.fromFile(externalFile);
  639. }
  640. } else {
  641. uri = Uri.parse(UriUtils.URI_CONTENT_SCHEME +
  642. context.getResources().getString(R.string.image_cache_provider_authority) +
  643. file.getRemotePath());
  644. }
  645. intent.setDataAndType(uri, file.getMimetype());
  646. mFileActivity.startActivityForResult(Intent.createChooser(intent,
  647. mFileActivity.getString(R.string.set_as)), 200);
  648. intent.setDataAndType(uri, file.getMimetype());
  649. } catch (ActivityNotFoundException exception) {
  650. DisplayUtils.showSnackMessage(view, R.string.picture_set_as_no_app);
  651. }
  652. } else {
  653. Log_OC.wtf(TAG, "Trying to send a NULL OCFile");
  654. }
  655. }
  656. /**
  657. * Request the synchronization of a file or folder with the OC server, including its contents.
  658. *
  659. * @param file The file or folder to synchronize
  660. */
  661. public void syncFile(OCFile file) {
  662. if (!file.isFolder()) {
  663. Intent intent = new Intent(mFileActivity, OperationsService.class);
  664. intent.setAction(OperationsService.ACTION_SYNC_FILE);
  665. intent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  666. intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  667. intent.putExtra(OperationsService.EXTRA_SYNC_FILE_CONTENTS, true);
  668. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(intent);
  669. mFileActivity.showLoadingDialog(mFileActivity.getApplicationContext().
  670. getString(R.string.wait_a_moment));
  671. } else {
  672. Intent intent = new Intent(mFileActivity, OperationsService.class);
  673. intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
  674. intent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  675. intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  676. mFileActivity.startService(intent);
  677. }
  678. }
  679. public void toggleFavoriteFiles(Collection<OCFile> files, boolean shouldBeFavorite) {
  680. List<OCFile> alreadyRightStateList = new ArrayList<>();
  681. for (OCFile file : files) {
  682. if (file.getIsFavorite() == shouldBeFavorite) {
  683. alreadyRightStateList.add(file);
  684. }
  685. }
  686. files.removeAll(alreadyRightStateList);
  687. for (OCFile file : files) {
  688. toggleFavoriteFile(file, shouldBeFavorite);
  689. }
  690. }
  691. public void toggleFavoriteFile(OCFile file, boolean shouldBeFavorite) {
  692. if (file.getIsFavorite() != shouldBeFavorite) {
  693. EventBus.getDefault().post(new FavoriteEvent(file.getRemotePath(), shouldBeFavorite, file.getRemoteId()));
  694. }
  695. }
  696. public void toggleEncryption(OCFile file, boolean shouldBeEncrypted) {
  697. if (file.isEncrypted() != shouldBeEncrypted) {
  698. EventBus.getDefault().post(new EncryptionEvent(file.getLocalId(), file.getRemoteId(), file.getRemotePath(),
  699. shouldBeEncrypted));
  700. }
  701. }
  702. public void toggleOfflineFiles(Collection<OCFile> files, boolean isAvailableOffline) {
  703. List<OCFile> alreadyRightStateList = new ArrayList<>();
  704. for (OCFile file : files) {
  705. if (file.isAvailableOffline() == isAvailableOffline) {
  706. alreadyRightStateList.add(file);
  707. }
  708. }
  709. files.removeAll(alreadyRightStateList);
  710. for (OCFile file : files) {
  711. toggleOfflineFile(file, isAvailableOffline);
  712. }
  713. }
  714. public void toggleOfflineFile(OCFile file, boolean isAvailableOffline) {
  715. if (file.isAvailableOffline() != isAvailableOffline) {
  716. file.setAvailableOffline(isAvailableOffline);
  717. mFileActivity.getStorageManager().saveFile(file);
  718. /// immediate content synchronization
  719. if (file.isAvailableOffline()) {
  720. syncFile(file);
  721. }
  722. }
  723. }
  724. public void renameFile(OCFile file, String newFilename) {
  725. // RenameFile
  726. Intent service = new Intent(mFileActivity, OperationsService.class);
  727. service.setAction(OperationsService.ACTION_RENAME);
  728. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  729. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  730. service.putExtra(OperationsService.EXTRA_NEWNAME, newFilename);
  731. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  732. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  733. }
  734. /**
  735. * Start operations to delete one or several files
  736. *
  737. * @param files Files to delete
  738. * @param onlyLocalCopy When 'true' only local copy of the files is removed; otherwise files are also deleted
  739. * in the server.
  740. */
  741. public void removeFiles(Collection<OCFile> files, boolean onlyLocalCopy) {
  742. for (OCFile file : files) {
  743. // RemoveFile
  744. Intent service = new Intent(mFileActivity, OperationsService.class);
  745. service.setAction(OperationsService.ACTION_REMOVE);
  746. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  747. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  748. service.putExtra(OperationsService.EXTRA_REMOVE_ONLY_LOCAL, onlyLocalCopy);
  749. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  750. }
  751. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  752. }
  753. public void createFolder(String remotePath, boolean createFullPath) {
  754. // Create Folder
  755. Intent service = new Intent(mFileActivity, OperationsService.class);
  756. service.setAction(OperationsService.ACTION_CREATE_FOLDER);
  757. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  758. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, remotePath);
  759. service.putExtra(OperationsService.EXTRA_CREATE_FULL_PATH, createFullPath);
  760. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  761. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  762. }
  763. /**
  764. * Cancel the transference in downloads (files/folders) and file uploads
  765. *
  766. * @param file OCFile
  767. */
  768. public void cancelTransference(OCFile file) {
  769. Account account = mFileActivity.getAccount();
  770. if (file.isFolder()) {
  771. OperationsService.OperationsServiceBinder opsBinder =
  772. mFileActivity.getOperationsServiceBinder();
  773. if (opsBinder != null) {
  774. opsBinder.cancel(account, file);
  775. }
  776. }
  777. // for both files and folders
  778. FileDownloaderBinder downloaderBinder = mFileActivity.getFileDownloaderBinder();
  779. if (downloaderBinder != null && downloaderBinder.isDownloading(account, file)) {
  780. downloaderBinder.cancel(account, file);
  781. }
  782. FileUploaderBinder uploaderBinder = mFileActivity.getFileUploaderBinder();
  783. if (uploaderBinder != null && uploaderBinder.isUploading(account, file)) {
  784. uploaderBinder.cancel(account, file);
  785. }
  786. }
  787. /**
  788. * Start operations to move one or several files
  789. *
  790. * @param files Files to move
  791. * @param targetFolder Folder where the files while be moved into
  792. */
  793. public void moveFiles(Collection<OCFile> files, OCFile targetFolder) {
  794. for (OCFile file : files) {
  795. Intent service = new Intent(mFileActivity, OperationsService.class);
  796. service.setAction(OperationsService.ACTION_MOVE_FILE);
  797. service.putExtra(OperationsService.EXTRA_NEW_PARENT_PATH, targetFolder.getRemotePath());
  798. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  799. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  800. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  801. }
  802. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  803. }
  804. /**
  805. * Start operations to copy one or several files
  806. *
  807. * @param files Files to copy
  808. * @param targetFolder Folder where the files while be copied into
  809. */
  810. public void copyFiles(Collection<OCFile> files, OCFile targetFolder) {
  811. for (OCFile file : files) {
  812. Intent service = new Intent(mFileActivity, OperationsService.class);
  813. service.setAction(OperationsService.ACTION_COPY_FILE);
  814. service.putExtra(OperationsService.EXTRA_NEW_PARENT_PATH, targetFolder.getRemotePath());
  815. service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
  816. service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
  817. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  818. }
  819. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_a_moment));
  820. }
  821. public long getOpIdWaitingFor() {
  822. return mWaitingForOpId;
  823. }
  824. public void setOpIdWaitingFor(long waitingForOpId) {
  825. mWaitingForOpId = waitingForOpId;
  826. }
  827. /**
  828. * @return 'True' if the server doesn't need to check forbidden characters
  829. */
  830. public boolean isVersionWithForbiddenCharacters() {
  831. if (mFileActivity.getAccount() != null) {
  832. return AccountUtils.getServerVersion(mFileActivity.getAccount()).isVersionWithForbiddenCharacters();
  833. }
  834. return false;
  835. }
  836. /**
  837. * Starts a check of the currently stored credentials for the given account.
  838. *
  839. * @param account OC account which credentials will be checked.
  840. */
  841. public void checkCurrentCredentials(Account account) {
  842. Intent service = new Intent(mFileActivity, OperationsService.class);
  843. service.setAction(OperationsService.ACTION_CHECK_CURRENT_CREDENTIALS);
  844. service.putExtra(OperationsService.EXTRA_ACCOUNT, account);
  845. mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);
  846. mFileActivity.showLoadingDialog(mFileActivity.getString(R.string.wait_checking_credentials));
  847. }
  848. }