UploadFileOperation.java 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * @author Chris Narkiewicz
  6. * Copyright (C) 2016 ownCloud GmbH.
  7. * Copyright (C) 2020 Chris Narkiewicz <hello@ezaquarii.com>
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. package com.owncloud.android.operations;
  22. import android.annotation.SuppressLint;
  23. import android.content.Context;
  24. import android.net.Uri;
  25. import android.text.TextUtils;
  26. import android.util.Pair;
  27. import com.nextcloud.client.account.User;
  28. import com.nextcloud.client.device.BatteryStatus;
  29. import com.nextcloud.client.device.PowerManagementService;
  30. import com.nextcloud.client.network.Connectivity;
  31. import com.nextcloud.client.network.ConnectivityService;
  32. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  33. import com.owncloud.android.datamodel.ArbitraryDataProviderImpl;
  34. import com.owncloud.android.datamodel.DecryptedFolderMetadata;
  35. import com.owncloud.android.datamodel.EncryptedFolderMetadata;
  36. import com.owncloud.android.datamodel.FileDataStorageManager;
  37. import com.owncloud.android.datamodel.OCFile;
  38. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  39. import com.owncloud.android.datamodel.UploadsStorageManager;
  40. import com.owncloud.android.db.OCUpload;
  41. import com.owncloud.android.files.services.FileUploader;
  42. import com.owncloud.android.files.services.NameCollisionPolicy;
  43. import com.owncloud.android.lib.common.OwnCloudClient;
  44. import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  45. import com.owncloud.android.lib.common.network.ProgressiveDataTransfer;
  46. import com.owncloud.android.lib.common.operations.OperationCancelledException;
  47. import com.owncloud.android.lib.common.operations.RemoteOperation;
  48. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  49. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  50. import com.owncloud.android.lib.common.utils.Log_OC;
  51. import com.owncloud.android.lib.resources.e2ee.UnlockFileRemoteOperation;
  52. import com.owncloud.android.lib.resources.files.ChunkedFileUploadRemoteOperation;
  53. import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
  54. import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation;
  55. import com.owncloud.android.lib.resources.files.UploadFileRemoteOperation;
  56. import com.owncloud.android.lib.resources.files.model.RemoteFile;
  57. import com.owncloud.android.operations.common.SyncOperation;
  58. import com.owncloud.android.utils.EncryptionUtils;
  59. import com.owncloud.android.utils.FileStorageUtils;
  60. import com.owncloud.android.utils.FileUtil;
  61. import com.owncloud.android.utils.MimeType;
  62. import com.owncloud.android.utils.MimeTypeUtil;
  63. import com.owncloud.android.utils.UriUtils;
  64. import org.apache.commons.httpclient.HttpStatus;
  65. import org.apache.commons.httpclient.methods.RequestEntity;
  66. import org.lukhnos.nnio.file.Files;
  67. import org.lukhnos.nnio.file.Paths;
  68. import java.io.File;
  69. import java.io.FileInputStream;
  70. import java.io.FileNotFoundException;
  71. import java.io.FileOutputStream;
  72. import java.io.IOException;
  73. import java.io.InputStream;
  74. import java.io.OutputStream;
  75. import java.io.RandomAccessFile;
  76. import java.nio.channels.FileChannel;
  77. import java.nio.channels.FileLock;
  78. import java.nio.channels.OverlappingFileLockException;
  79. import java.util.HashSet;
  80. import java.util.Set;
  81. import java.util.UUID;
  82. import java.util.concurrent.atomic.AtomicBoolean;
  83. import androidx.annotation.CheckResult;
  84. import androidx.annotation.Nullable;
  85. /**
  86. * Operation performing the update in the ownCloud server
  87. * of a file that was modified locally.
  88. */
  89. public class UploadFileOperation extends SyncOperation {
  90. private static final String TAG = UploadFileOperation.class.getSimpleName();
  91. public static final int CREATED_BY_USER = 0;
  92. public static final int CREATED_AS_INSTANT_PICTURE = 1;
  93. public static final int CREATED_AS_INSTANT_VIDEO = 2;
  94. /**
  95. * OCFile which is to be uploaded.
  96. */
  97. private OCFile mFile;
  98. /**
  99. * Original OCFile which is to be uploaded in case file had to be renamed (if nameCollisionPolicy==RENAME and remote
  100. * file already exists).
  101. */
  102. private OCFile mOldFile;
  103. private String mRemotePath;
  104. private String mFolderUnlockToken;
  105. private boolean mRemoteFolderToBeCreated;
  106. private NameCollisionPolicy mNameCollisionPolicy;
  107. private int mLocalBehaviour;
  108. private int mCreatedBy;
  109. private boolean mOnWifiOnly;
  110. private boolean mWhileChargingOnly;
  111. private boolean mIgnoringPowerSaveMode;
  112. private final boolean mDisableRetries;
  113. private boolean mWasRenamed;
  114. private long mOCUploadId;
  115. /**
  116. * Local path to file which is to be uploaded (before any possible renaming or moving).
  117. */
  118. private String mOriginalStoragePath;
  119. private final Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<>();
  120. private OnRenameListener mRenameUploadListener;
  121. private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
  122. private final AtomicBoolean mUploadStarted = new AtomicBoolean(false);
  123. private Context mContext;
  124. private UploadFileRemoteOperation mUploadOperation;
  125. private RequestEntity mEntity;
  126. private final User user;
  127. private final OCUpload mUpload;
  128. private final UploadsStorageManager uploadsStorageManager;
  129. private final ConnectivityService connectivityService;
  130. private final PowerManagementService powerManagementService;
  131. private boolean encryptedAncestor;
  132. public static OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType) {
  133. OCFile newFile = new OCFile(remotePath);
  134. newFile.setStoragePath(localPath);
  135. newFile.setLastSyncDateForProperties(0);
  136. newFile.setLastSyncDateForData(0);
  137. // size
  138. if (!TextUtils.isEmpty(localPath)) {
  139. File localFile = new File(localPath);
  140. newFile.setFileLength(localFile.length());
  141. newFile.setLastSyncDateForData(localFile.lastModified());
  142. } // don't worry about not assigning size, the problems with localPath
  143. // are checked when the UploadFileOperation instance is created
  144. // MIME type
  145. if (TextUtils.isEmpty(mimeType)) {
  146. newFile.setMimeType(MimeTypeUtil.getBestMimeTypeByFilename(localPath));
  147. } else {
  148. newFile.setMimeType(mimeType);
  149. }
  150. return newFile;
  151. }
  152. public UploadFileOperation(UploadsStorageManager uploadsStorageManager,
  153. ConnectivityService connectivityService,
  154. PowerManagementService powerManagementService,
  155. User user,
  156. OCFile file,
  157. OCUpload upload,
  158. NameCollisionPolicy nameCollisionPolicy,
  159. int localBehaviour,
  160. Context context,
  161. boolean onWifiOnly,
  162. boolean whileChargingOnly,
  163. FileDataStorageManager storageManager) {
  164. this(uploadsStorageManager,
  165. connectivityService,
  166. powerManagementService,
  167. user,
  168. file,
  169. upload,
  170. nameCollisionPolicy,
  171. localBehaviour,
  172. context,
  173. onWifiOnly,
  174. whileChargingOnly,
  175. true,
  176. storageManager);
  177. }
  178. public UploadFileOperation(UploadsStorageManager uploadsStorageManager,
  179. ConnectivityService connectivityService,
  180. PowerManagementService powerManagementService,
  181. User user,
  182. OCFile file,
  183. OCUpload upload,
  184. NameCollisionPolicy nameCollisionPolicy,
  185. int localBehaviour,
  186. Context context,
  187. boolean onWifiOnly,
  188. boolean whileChargingOnly,
  189. boolean disableRetries,
  190. FileDataStorageManager storageManager) {
  191. super(storageManager);
  192. if (upload == null) {
  193. throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
  194. }
  195. if (TextUtils.isEmpty(upload.getLocalPath())) {
  196. throw new IllegalArgumentException(
  197. "Illegal file in UploadFileOperation; storage path invalid: "
  198. + upload.getLocalPath());
  199. }
  200. this.uploadsStorageManager = uploadsStorageManager;
  201. this.connectivityService = connectivityService;
  202. this.powerManagementService = powerManagementService;
  203. this.user = user;
  204. mUpload = upload;
  205. if (file == null) {
  206. mFile = obtainNewOCFileToUpload(
  207. upload.getRemotePath(),
  208. upload.getLocalPath(),
  209. upload.getMimeType()
  210. );
  211. } else {
  212. mFile = file;
  213. }
  214. mOnWifiOnly = onWifiOnly;
  215. mWhileChargingOnly = whileChargingOnly;
  216. mRemotePath = upload.getRemotePath();
  217. mNameCollisionPolicy = nameCollisionPolicy;
  218. mLocalBehaviour = localBehaviour;
  219. mOriginalStoragePath = mFile.getStoragePath();
  220. mContext = context;
  221. mOCUploadId = upload.getUploadId();
  222. mCreatedBy = upload.getCreatedBy();
  223. mRemoteFolderToBeCreated = upload.isCreateRemoteFolder();
  224. // Ignore power save mode only if user explicitly created this upload
  225. mIgnoringPowerSaveMode = mCreatedBy == CREATED_BY_USER;
  226. mFolderUnlockToken = upload.getFolderUnlockToken();
  227. mDisableRetries = disableRetries;
  228. }
  229. public boolean isWifiRequired() {
  230. return mOnWifiOnly;
  231. }
  232. public boolean isChargingRequired() {
  233. return mWhileChargingOnly;
  234. }
  235. public boolean isIgnoringPowerSaveMode() { return mIgnoringPowerSaveMode; }
  236. public User getUser() {
  237. return user;
  238. }
  239. public String getFileName() {
  240. return (mFile != null) ? mFile.getFileName() : null;
  241. }
  242. public OCFile getFile() {
  243. return mFile;
  244. }
  245. /**
  246. * If remote file was renamed, return original OCFile which was uploaded. Is null is file was not renamed.
  247. */
  248. @Nullable
  249. public OCFile getOldFile() {
  250. return mOldFile;
  251. }
  252. public String getOriginalStoragePath() {
  253. return mOriginalStoragePath;
  254. }
  255. public String getStoragePath() {
  256. return mFile.getStoragePath();
  257. }
  258. public String getRemotePath() {
  259. return mFile.getRemotePath();
  260. }
  261. public String getDecryptedRemotePath() {
  262. return mFile.getDecryptedRemotePath();
  263. }
  264. public String getMimeType() {
  265. return mFile.getMimeType();
  266. }
  267. public int getLocalBehaviour() {
  268. return mLocalBehaviour;
  269. }
  270. public UploadFileOperation setRemoteFolderToBeCreated() {
  271. mRemoteFolderToBeCreated = true;
  272. return this;
  273. }
  274. public boolean wasRenamed() {
  275. return mWasRenamed;
  276. }
  277. public void setCreatedBy(int createdBy) {
  278. mCreatedBy = createdBy;
  279. if (createdBy < CREATED_BY_USER || CREATED_AS_INSTANT_VIDEO < createdBy) {
  280. mCreatedBy = CREATED_BY_USER;
  281. }
  282. }
  283. public int getCreatedBy() {
  284. return mCreatedBy;
  285. }
  286. public boolean isInstantPicture() {
  287. return mCreatedBy == CREATED_AS_INSTANT_PICTURE;
  288. }
  289. public boolean isInstantVideo() {
  290. return mCreatedBy == CREATED_AS_INSTANT_VIDEO;
  291. }
  292. public void setOCUploadId(long id) {
  293. mOCUploadId = id;
  294. }
  295. public long getOCUploadId() {
  296. return mOCUploadId;
  297. }
  298. public Set<OnDatatransferProgressListener> getDataTransferListeners() {
  299. return mDataTransferListeners;
  300. }
  301. public void addDataTransferProgressListener(OnDatatransferProgressListener listener) {
  302. synchronized (mDataTransferListeners) {
  303. mDataTransferListeners.add(listener);
  304. }
  305. if (mEntity != null) {
  306. ((ProgressiveDataTransfer) mEntity).addDataTransferProgressListener(listener);
  307. }
  308. if (mUploadOperation != null) {
  309. mUploadOperation.addDataTransferProgressListener(listener);
  310. }
  311. }
  312. public void removeDataTransferProgressListener(OnDatatransferProgressListener listener) {
  313. synchronized (mDataTransferListeners) {
  314. mDataTransferListeners.remove(listener);
  315. }
  316. if (mEntity != null) {
  317. ((ProgressiveDataTransfer) mEntity).removeDataTransferProgressListener(listener);
  318. }
  319. if (mUploadOperation != null) {
  320. mUploadOperation.removeDataTransferProgressListener(listener);
  321. }
  322. }
  323. public UploadFileOperation addRenameUploadListener(OnRenameListener listener) {
  324. mRenameUploadListener = listener;
  325. return this;
  326. }
  327. public Context getContext() {
  328. return mContext;
  329. }
  330. @Override
  331. @SuppressWarnings("PMD.AvoidDuplicateLiterals")
  332. protected RemoteOperationResult run(OwnCloudClient client) {
  333. mCancellationRequested.set(false);
  334. mUploadStarted.set(true);
  335. updateSize(0);
  336. String remoteParentPath = new File(getRemotePath()).getParent();
  337. remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ?
  338. remoteParentPath : remoteParentPath + OCFile.PATH_SEPARATOR;
  339. OCFile parent = getStorageManager().getFileByPath(remoteParentPath);
  340. // in case of a fresh upload with subfolder, where parent does not exist yet
  341. if (parent == null && (mFolderUnlockToken == null || mFolderUnlockToken.isEmpty())) {
  342. // try to create folder
  343. RemoteOperationResult result = grantFolderExistence(remoteParentPath, client);
  344. if (!result.isSuccess()) {
  345. return result;
  346. }
  347. parent = getStorageManager().getFileByPath(remoteParentPath);
  348. if (parent == null) {
  349. return new RemoteOperationResult(false, "Parent folder not found", HttpStatus.SC_NOT_FOUND);
  350. }
  351. }
  352. // parent file is not null anymore:
  353. // - it was created on fresh upload or
  354. // - resume of encrypted upload, then parent file exists already as unlock is only for direct parent
  355. mFile.setParentId(parent.getFileId());
  356. // try to unlock folder with stored token, e.g. when upload needs to be resumed or app crashed
  357. // the parent folder should exist as it is a resume of a broken upload
  358. if (mFolderUnlockToken != null && !mFolderUnlockToken.isEmpty()) {
  359. UnlockFileRemoteOperation unlockFileOperation = new UnlockFileRemoteOperation(parent.getLocalId(),
  360. mFolderUnlockToken);
  361. RemoteOperationResult unlockFileOperationResult = unlockFileOperation.execute(client);
  362. if (!unlockFileOperationResult.isSuccess()) {
  363. return unlockFileOperationResult;
  364. }
  365. }
  366. // check if any parent is encrypted
  367. encryptedAncestor = FileStorageUtils.checkEncryptionStatus(parent, getStorageManager());
  368. mFile.setEncrypted(encryptedAncestor);
  369. if (encryptedAncestor) {
  370. Log_OC.d(TAG, "encrypted upload");
  371. return encryptedUpload(client, parent);
  372. } else {
  373. Log_OC.d(TAG, "normal upload");
  374. return normalUpload(client);
  375. }
  376. }
  377. @SuppressLint("AndroidLintUseSparseArrays") // gson cannot handle sparse arrays easily, therefore use hashmap
  378. private RemoteOperationResult encryptedUpload(OwnCloudClient client, OCFile parentFile) {
  379. RemoteOperationResult result = null;
  380. File temporalFile = null;
  381. File originalFile = new File(mOriginalStoragePath);
  382. File expectedFile = null;
  383. FileLock fileLock = null;
  384. long size;
  385. boolean metadataExists = false;
  386. String token = null;
  387. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProviderImpl(getContext());
  388. String privateKey = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.PRIVATE_KEY);
  389. String publicKey = arbitraryDataProvider.getValue(user.getAccountName(), EncryptionUtils.PUBLIC_KEY);
  390. try {
  391. // check conditions
  392. result = checkConditions(originalFile);
  393. if (result != null) {
  394. return result;
  395. }
  396. /***** E2E *****/
  397. token = EncryptionUtils.lockFolder(parentFile, client);
  398. // immediately store it
  399. mUpload.setFolderUnlockToken(token);
  400. uploadsStorageManager.updateUpload(mUpload);
  401. // Update metadata
  402. Pair<Boolean, DecryptedFolderMetadata> metadataPair = EncryptionUtils.retrieveMetadata(parentFile,
  403. client,
  404. privateKey,
  405. publicKey);
  406. metadataExists = metadataPair.first;
  407. DecryptedFolderMetadata metadata = metadataPair.second;
  408. /**** E2E *****/
  409. // check name collision
  410. RemoteOperationResult collisionResult = checkNameCollision(client, metadata, parentFile.isEncrypted());
  411. if (collisionResult != null) {
  412. result = collisionResult;
  413. return collisionResult;
  414. }
  415. mFile.setDecryptedRemotePath(parentFile.getDecryptedRemotePath() + originalFile.getName());
  416. String expectedPath = FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), mFile);
  417. expectedFile = new File(expectedPath);
  418. result = copyFile(originalFile, expectedPath);
  419. if (!result.isSuccess()) {
  420. return result;
  421. }
  422. // Get the last modification date of the file from the file system
  423. String lastModifiedTimestamp = Long.toString(originalFile.lastModified() / 1000);
  424. Long creationTimestamp = FileUtil.getCreationTimestamp(originalFile);
  425. /***** E2E *****/
  426. // Key, always generate new one
  427. byte[] key = EncryptionUtils.generateKey();
  428. // IV, always generate new one
  429. byte[] iv = EncryptionUtils.randomBytes(EncryptionUtils.ivLength);
  430. EncryptionUtils.EncryptedFile encryptedFile = EncryptionUtils.encryptFile(mFile, key, iv);
  431. // new random file name, check if it exists in metadata
  432. String encryptedFileName = UUID.randomUUID().toString().replaceAll("-", "");
  433. while (metadata.getFiles().get(encryptedFileName) != null) {
  434. encryptedFileName = UUID.randomUUID().toString().replaceAll("-", "");
  435. }
  436. File encryptedTempFile = File.createTempFile("encFile", encryptedFileName);
  437. FileOutputStream fileOutputStream = new FileOutputStream(encryptedTempFile);
  438. fileOutputStream.write(encryptedFile.encryptedBytes);
  439. fileOutputStream.close();
  440. /***** E2E *****/
  441. FileChannel channel = null;
  442. try {
  443. channel = new RandomAccessFile(mFile.getStoragePath(), "rw").getChannel();
  444. fileLock = channel.tryLock();
  445. } catch (FileNotFoundException e) {
  446. // this basically means that the file is on SD card
  447. // try to copy file to temporary dir if it doesn't exist
  448. String temporalPath = FileStorageUtils.getInternalTemporalPath(user.getAccountName(), mContext) +
  449. mFile.getRemotePath();
  450. mFile.setStoragePath(temporalPath);
  451. temporalFile = new File(temporalPath);
  452. Files.deleteIfExists(Paths.get(temporalPath));
  453. result = copy(originalFile, temporalFile);
  454. if (result.isSuccess()) {
  455. if (temporalFile.length() == originalFile.length()) {
  456. channel = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw").getChannel();
  457. fileLock = channel.tryLock();
  458. } else {
  459. result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
  460. }
  461. }
  462. }
  463. try {
  464. size = channel.size();
  465. } catch (IOException e1) {
  466. size = new File(mFile.getStoragePath()).length();
  467. }
  468. updateSize(size);
  469. /// perform the upload
  470. if (size > ChunkedFileUploadRemoteOperation.CHUNK_SIZE_MOBILE) {
  471. boolean onWifiConnection = connectivityService.getConnectivity().isWifi();
  472. mUploadOperation = new ChunkedFileUploadRemoteOperation(encryptedTempFile.getAbsolutePath(),
  473. mFile.getParentRemotePath() + encryptedFileName,
  474. mFile.getMimeType(),
  475. mFile.getEtagInConflict(),
  476. lastModifiedTimestamp,
  477. onWifiConnection,
  478. token,
  479. creationTimestamp,
  480. mDisableRetries
  481. );
  482. } else {
  483. mUploadOperation = new UploadFileRemoteOperation(encryptedTempFile.getAbsolutePath(),
  484. mFile.getParentRemotePath() + encryptedFileName,
  485. mFile.getMimeType(),
  486. mFile.getEtagInConflict(),
  487. lastModifiedTimestamp,
  488. creationTimestamp,
  489. token,
  490. mDisableRetries
  491. );
  492. }
  493. for (OnDatatransferProgressListener mDataTransferListener : mDataTransferListeners) {
  494. mUploadOperation.addDataTransferProgressListener(mDataTransferListener);
  495. }
  496. if (mCancellationRequested.get()) {
  497. throw new OperationCancelledException();
  498. }
  499. result = mUploadOperation.execute(client);
  500. /// move local temporal file or original file to its corresponding
  501. // location in the Nextcloud local folder
  502. if (!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
  503. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  504. }
  505. if (result.isSuccess()) {
  506. mFile.setDecryptedRemotePath(parentFile.getDecryptedRemotePath() + originalFile.getName());
  507. mFile.setRemotePath(parentFile.getRemotePath() + encryptedFileName);
  508. // update metadata
  509. DecryptedFolderMetadata.DecryptedFile decryptedFile = new DecryptedFolderMetadata.DecryptedFile();
  510. DecryptedFolderMetadata.Data data = new DecryptedFolderMetadata.Data();
  511. data.setFilename(mFile.getDecryptedFileName());
  512. data.setMimetype(mFile.getMimeType());
  513. data.setKey(EncryptionUtils.encodeBytesToBase64String(key));
  514. decryptedFile.setEncrypted(data);
  515. decryptedFile.setInitializationVector(EncryptionUtils.encodeBytesToBase64String(iv));
  516. decryptedFile.setAuthenticationTag(encryptedFile.authenticationTag);
  517. metadata.getFiles().put(encryptedFileName, decryptedFile);
  518. EncryptedFolderMetadata encryptedFolderMetadata = EncryptionUtils.encryptFolderMetadata(metadata,
  519. privateKey);
  520. String serializedFolderMetadata = EncryptionUtils.serializeJSON(encryptedFolderMetadata);
  521. // upload metadata
  522. EncryptionUtils.uploadMetadata(parentFile,
  523. serializedFolderMetadata,
  524. token,
  525. client,
  526. metadataExists);
  527. // unlock
  528. result = EncryptionUtils.unlockFolder(parentFile, client, token);
  529. if (result.isSuccess()) {
  530. token = null;
  531. }
  532. }
  533. } catch (FileNotFoundException e) {
  534. Log_OC.d(TAG, mFile.getStoragePath() + " not exists anymore");
  535. result = new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
  536. } catch (OverlappingFileLockException e) {
  537. Log_OC.d(TAG, "Overlapping file lock exception");
  538. result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
  539. } catch (Exception e) {
  540. result = new RemoteOperationResult(e);
  541. } finally {
  542. mUploadStarted.set(false);
  543. if (fileLock != null) {
  544. try {
  545. fileLock.release();
  546. } catch (IOException e) {
  547. Log_OC.e(TAG, "Failed to unlock file with path " + mFile.getStoragePath());
  548. }
  549. }
  550. if (temporalFile != null && !originalFile.equals(temporalFile)) {
  551. temporalFile.delete();
  552. }
  553. if (result == null) {
  554. result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  555. }
  556. logResult(result, mFile.getStoragePath(), mFile.getRemotePath());
  557. }
  558. if (result.isSuccess()) {
  559. handleSuccessfulUpload(temporalFile, expectedFile, originalFile, client);
  560. } else if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  561. getStorageManager().saveConflict(mFile, mFile.getEtagInConflict());
  562. }
  563. // unlock must be done always
  564. if (token != null) {
  565. RemoteOperationResult unlockFolderResult = EncryptionUtils.unlockFolder(parentFile,
  566. client,
  567. token);
  568. if (!unlockFolderResult.isSuccess()) {
  569. return unlockFolderResult;
  570. }
  571. }
  572. // delete temporal file
  573. if (temporalFile != null && temporalFile.exists() && !temporalFile.delete()) {
  574. Log_OC.e(TAG, "Could not delete temporal file " + temporalFile.getAbsolutePath());
  575. }
  576. return result;
  577. }
  578. private RemoteOperationResult checkConditions(File originalFile) {
  579. RemoteOperationResult remoteOperationResult = null;
  580. // check that connectivity conditions are met and delays the upload otherwise
  581. Connectivity connectivity = connectivityService.getConnectivity();
  582. if (mOnWifiOnly && (!connectivity.isWifi() || connectivity.isMetered())) {
  583. Log_OC.d(TAG, "Upload delayed until WiFi is available: " + getRemotePath());
  584. remoteOperationResult = new RemoteOperationResult(ResultCode.DELAYED_FOR_WIFI);
  585. }
  586. // check if charging conditions are met and delays the upload otherwise
  587. final BatteryStatus battery = powerManagementService.getBattery();
  588. if (mWhileChargingOnly && !battery.isCharging()) {
  589. Log_OC.d(TAG, "Upload delayed until the device is charging: " + getRemotePath());
  590. remoteOperationResult = new RemoteOperationResult(ResultCode.DELAYED_FOR_CHARGING);
  591. }
  592. // check that device is not in power save mode
  593. if (!mIgnoringPowerSaveMode && powerManagementService.isPowerSavingEnabled()) {
  594. Log_OC.d(TAG, "Upload delayed because device is in power save mode: " + getRemotePath());
  595. remoteOperationResult = new RemoteOperationResult(ResultCode.DELAYED_IN_POWER_SAVE_MODE);
  596. }
  597. // check if the file continues existing before schedule the operation
  598. if (!originalFile.exists()) {
  599. Log_OC.d(TAG, mOriginalStoragePath + " not exists anymore");
  600. remoteOperationResult = new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
  601. }
  602. // check that internet is not behind walled garden
  603. if (!connectivityService.getConnectivity().isConnected() || connectivityService.isInternetWalled()) {
  604. remoteOperationResult = new RemoteOperationResult(ResultCode.NO_NETWORK_CONNECTION);
  605. }
  606. return remoteOperationResult;
  607. }
  608. private RemoteOperationResult normalUpload(OwnCloudClient client) {
  609. RemoteOperationResult result = null;
  610. File temporalFile = null;
  611. File originalFile = new File(mOriginalStoragePath);
  612. File expectedFile = null;
  613. FileLock fileLock = null;
  614. FileChannel channel = null;
  615. long size;
  616. try {
  617. // check conditions
  618. result = checkConditions(originalFile);
  619. if (result != null) {
  620. return result;
  621. }
  622. // check name collision
  623. RemoteOperationResult collisionResult = checkNameCollision(client, null, false);
  624. if (collisionResult != null) {
  625. result = collisionResult;
  626. return collisionResult;
  627. }
  628. String expectedPath = FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), mFile);
  629. expectedFile = new File(expectedPath);
  630. result = copyFile(originalFile, expectedPath);
  631. if (!result.isSuccess()) {
  632. return result;
  633. }
  634. // Get the last modification date of the file from the file system
  635. String lastModifiedTimestamp = Long.toString(originalFile.lastModified() / 1000);
  636. final Long creationTimestamp = FileUtil.getCreationTimestamp(originalFile);
  637. try {
  638. channel = new RandomAccessFile(mFile.getStoragePath(), "rw").getChannel();
  639. fileLock = channel.tryLock();
  640. } catch (FileNotFoundException e) {
  641. // this basically means that the file is on SD card
  642. // try to copy file to temporary dir if it doesn't exist
  643. String temporalPath = FileStorageUtils.getInternalTemporalPath(user.getAccountName(), mContext) +
  644. mFile.getRemotePath();
  645. mFile.setStoragePath(temporalPath);
  646. temporalFile = new File(temporalPath);
  647. Files.deleteIfExists(Paths.get(temporalPath));
  648. result = copy(originalFile, temporalFile);
  649. if (result.isSuccess()) {
  650. if (temporalFile.length() == originalFile.length()) {
  651. channel = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw").getChannel();
  652. fileLock = channel.tryLock();
  653. } else {
  654. result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
  655. }
  656. }
  657. }
  658. try {
  659. size = channel.size();
  660. } catch (Exception e1) {
  661. size = new File(mFile.getStoragePath()).length();
  662. }
  663. updateSize(size);
  664. // perform the upload
  665. if (size > ChunkedFileUploadRemoteOperation.CHUNK_SIZE_MOBILE) {
  666. boolean onWifiConnection = connectivityService.getConnectivity().isWifi();
  667. mUploadOperation = new ChunkedFileUploadRemoteOperation(mFile.getStoragePath(),
  668. mFile.getRemotePath(),
  669. mFile.getMimeType(),
  670. mFile.getEtagInConflict(),
  671. lastModifiedTimestamp,
  672. creationTimestamp,
  673. onWifiConnection,
  674. mDisableRetries);
  675. } else {
  676. mUploadOperation = new UploadFileRemoteOperation(mFile.getStoragePath(),
  677. mFile.getRemotePath(),
  678. mFile.getMimeType(),
  679. mFile.getEtagInConflict(),
  680. lastModifiedTimestamp,
  681. creationTimestamp,
  682. mDisableRetries);
  683. }
  684. for (OnDatatransferProgressListener mDataTransferListener : mDataTransferListeners) {
  685. mUploadOperation.addDataTransferProgressListener(mDataTransferListener);
  686. }
  687. if (mCancellationRequested.get()) {
  688. throw new OperationCancelledException();
  689. }
  690. if (result.isSuccess() && mUploadOperation != null) {
  691. result = mUploadOperation.execute(client);
  692. /// move local temporal file or original file to its corresponding
  693. // location in the Nextcloud local folder
  694. if (!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
  695. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  696. }
  697. }
  698. } catch (FileNotFoundException e) {
  699. Log_OC.d(TAG, mOriginalStoragePath + " not exists anymore");
  700. result = new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
  701. } catch (OverlappingFileLockException e) {
  702. Log_OC.d(TAG, "Overlapping file lock exception");
  703. result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
  704. } catch (Exception e) {
  705. result = new RemoteOperationResult(e);
  706. } finally {
  707. mUploadStarted.set(false);
  708. if (fileLock != null) {
  709. try {
  710. fileLock.release();
  711. } catch (IOException e) {
  712. Log_OC.e(TAG, "Failed to unlock file with path " + mOriginalStoragePath);
  713. }
  714. }
  715. if (channel != null) {
  716. try {
  717. channel.close();
  718. } catch (IOException e) {
  719. Log_OC.w(TAG, "Failed to close file channel");
  720. }
  721. }
  722. if (temporalFile != null && !originalFile.equals(temporalFile)) {
  723. temporalFile.delete();
  724. }
  725. if (result == null) {
  726. result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  727. }
  728. logResult(result, mOriginalStoragePath, mRemotePath);
  729. }
  730. if (result.isSuccess()) {
  731. handleSuccessfulUpload(temporalFile, expectedFile, originalFile, client);
  732. } else if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  733. getStorageManager().saveConflict(mFile, mFile.getEtagInConflict());
  734. }
  735. // delete temporal file
  736. if (temporalFile != null && temporalFile.exists() && !temporalFile.delete()) {
  737. Log_OC.e(TAG, "Could not delete temporal file " + temporalFile.getAbsolutePath());
  738. }
  739. return result;
  740. }
  741. private void updateSize(long size) {
  742. OCUpload ocUpload = uploadsStorageManager.getUploadById(getOCUploadId());
  743. if(ocUpload != null){
  744. ocUpload.setFileSize(size);
  745. uploadsStorageManager.updateUpload(ocUpload);
  746. }
  747. }
  748. private void logResult(RemoteOperationResult result, String sourcePath, String targetPath) {
  749. if (result.isSuccess()) {
  750. Log_OC.i(TAG, "Upload of " + sourcePath + " to " + targetPath + ": " + result.getLogMessage());
  751. } else {
  752. if (result.getException() != null) {
  753. if (result.isCancelled()) {
  754. Log_OC.w(TAG, "Upload of " + sourcePath + " to " + targetPath + ": "
  755. + result.getLogMessage());
  756. } else {
  757. Log_OC.e(TAG, "Upload of " + sourcePath + " to " + targetPath + ": "
  758. + result.getLogMessage(), result.getException());
  759. }
  760. } else {
  761. Log_OC.e(TAG, "Upload of " + sourcePath + " to " + targetPath + ": " + result.getLogMessage());
  762. }
  763. }
  764. }
  765. private RemoteOperationResult copyFile(File originalFile, String expectedPath) throws OperationCancelledException,
  766. IOException {
  767. if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY && !mOriginalStoragePath.equals(expectedPath)) {
  768. String temporalPath = FileStorageUtils.getInternalTemporalPath(user.getAccountName(), mContext) +
  769. mFile.getRemotePath();
  770. mFile.setStoragePath(temporalPath);
  771. File temporalFile = new File(temporalPath);
  772. return copy(originalFile, temporalFile);
  773. }
  774. if (mCancellationRequested.get()) {
  775. throw new OperationCancelledException();
  776. }
  777. return new RemoteOperationResult(ResultCode.OK);
  778. }
  779. @CheckResult
  780. private RemoteOperationResult checkNameCollision(OwnCloudClient client,
  781. DecryptedFolderMetadata metadata,
  782. boolean encrypted)
  783. throws OperationCancelledException {
  784. Log_OC.d(TAG, "Checking name collision in server");
  785. if (existsFile(client, mRemotePath, metadata, encrypted)) {
  786. switch (mNameCollisionPolicy) {
  787. case CANCEL:
  788. Log_OC.d(TAG, "File exists; canceling");
  789. throw new OperationCancelledException();
  790. case RENAME:
  791. mRemotePath = getNewAvailableRemotePath(client, mRemotePath, metadata, encrypted);
  792. mWasRenamed = true;
  793. createNewOCFile(mRemotePath);
  794. Log_OC.d(TAG, "File renamed as " + mRemotePath);
  795. if (mRenameUploadListener != null) {
  796. mRenameUploadListener.onRenameUpload();
  797. }
  798. break;
  799. case OVERWRITE:
  800. Log_OC.d(TAG, "Overwriting file");
  801. break;
  802. case ASK_USER:
  803. Log_OC.d(TAG, "Name collision; asking the user what to do");
  804. return new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  805. }
  806. }
  807. if (mCancellationRequested.get()) {
  808. throw new OperationCancelledException();
  809. }
  810. return null;
  811. }
  812. private void handleSuccessfulUpload(File temporalFile,
  813. File expectedFile,
  814. File originalFile,
  815. OwnCloudClient client) {
  816. switch (mLocalBehaviour) {
  817. case FileUploader.LOCAL_BEHAVIOUR_FORGET:
  818. default:
  819. mFile.setStoragePath("");
  820. saveUploadedFile(client);
  821. break;
  822. case FileUploader.LOCAL_BEHAVIOUR_DELETE:
  823. originalFile.delete();
  824. mFile.setStoragePath("");
  825. getStorageManager().deleteFileInMediaScan(originalFile.getAbsolutePath());
  826. saveUploadedFile(client);
  827. break;
  828. case FileUploader.LOCAL_BEHAVIOUR_COPY:
  829. if (temporalFile != null) {
  830. try {
  831. move(temporalFile, expectedFile);
  832. } catch (IOException e) {
  833. Log_OC.e(TAG, e.getMessage());
  834. }
  835. } else if (originalFile != null) {
  836. try {
  837. copy(originalFile, expectedFile);
  838. } catch (IOException e) {
  839. Log_OC.e(TAG, e.getMessage());
  840. }
  841. }
  842. mFile.setStoragePath(expectedFile.getAbsolutePath());
  843. saveUploadedFile(client);
  844. if (MimeTypeUtil.isMedia(mFile.getMimeType())) {
  845. FileDataStorageManager.triggerMediaScan(expectedFile.getAbsolutePath());
  846. }
  847. break;
  848. case FileUploader.LOCAL_BEHAVIOUR_MOVE:
  849. String expectedPath = FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), mFile);
  850. File newFile = new File(expectedPath);
  851. try {
  852. move(originalFile, newFile);
  853. } catch (IOException e) {
  854. Log_OC.e(TAG, "Error moving file", e);
  855. }
  856. getStorageManager().deleteFileInMediaScan(originalFile.getAbsolutePath());
  857. mFile.setStoragePath(newFile.getAbsolutePath());
  858. saveUploadedFile(client);
  859. if (MimeTypeUtil.isMedia(mFile.getMimeType())) {
  860. FileDataStorageManager.triggerMediaScan(newFile.getAbsolutePath());
  861. }
  862. break;
  863. }
  864. }
  865. /**
  866. * Checks the existence of the folder where the current file will be uploaded both
  867. * in the remote server and in the local database.
  868. * <p/>
  869. * If the upload is set to enforce the creation of the folder, the method tries to
  870. * create it both remote and locally.
  871. *
  872. * @param pathToGrant Full remote path whose existence will be granted.
  873. * @return An {@link OCFile} instance corresponding to the folder where the file
  874. * will be uploaded.
  875. */
  876. private RemoteOperationResult grantFolderExistence(String pathToGrant, OwnCloudClient client) {
  877. RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, false);
  878. RemoteOperationResult result = operation.execute(client);
  879. if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND && mRemoteFolderToBeCreated) {
  880. SyncOperation syncOp = new CreateFolderOperation(pathToGrant, user, getContext(), getStorageManager());
  881. result = syncOp.execute(client);
  882. }
  883. if (result.isSuccess()) {
  884. OCFile parentDir = getStorageManager().getFileByPath(pathToGrant);
  885. if (parentDir == null) {
  886. parentDir = createLocalFolder(pathToGrant);
  887. }
  888. if (parentDir != null) {
  889. result = new RemoteOperationResult(ResultCode.OK);
  890. } else {
  891. result = new RemoteOperationResult(ResultCode.CANNOT_CREATE_FILE);
  892. }
  893. }
  894. return result;
  895. }
  896. private OCFile createLocalFolder(String remotePath) {
  897. String parentPath = new File(remotePath).getParent();
  898. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ?
  899. parentPath : parentPath + OCFile.PATH_SEPARATOR;
  900. OCFile parent = getStorageManager().getFileByPath(parentPath);
  901. if (parent == null) {
  902. parent = createLocalFolder(parentPath);
  903. }
  904. if (parent != null) {
  905. OCFile createdFolder = new OCFile(remotePath);
  906. createdFolder.setMimeType(MimeType.DIRECTORY);
  907. createdFolder.setParentId(parent.getFileId());
  908. getStorageManager().saveFile(createdFolder);
  909. return createdFolder;
  910. }
  911. return null;
  912. }
  913. /**
  914. * Create a new OCFile mFile with new remote path. This is required if nameCollisionPolicy==RENAME. New file is
  915. * stored as mFile, original as mOldFile.
  916. *
  917. * @param newRemotePath new remote path
  918. */
  919. private void createNewOCFile(String newRemotePath) {
  920. // a new OCFile instance must be created for a new remote path
  921. OCFile newFile = new OCFile(newRemotePath);
  922. newFile.setCreationTimestamp(mFile.getCreationTimestamp());
  923. newFile.setFileLength(mFile.getFileLength());
  924. newFile.setMimeType(mFile.getMimeType());
  925. newFile.setModificationTimestamp(mFile.getModificationTimestamp());
  926. newFile.setModificationTimestampAtLastSyncForData(
  927. mFile.getModificationTimestampAtLastSyncForData()
  928. );
  929. newFile.setEtag(mFile.getEtag());
  930. newFile.setLastSyncDateForProperties(mFile.getLastSyncDateForProperties());
  931. newFile.setLastSyncDateForData(mFile.getLastSyncDateForData());
  932. newFile.setStoragePath(mFile.getStoragePath());
  933. newFile.setParentId(mFile.getParentId());
  934. mOldFile = mFile;
  935. mFile = newFile;
  936. }
  937. /**
  938. * Returns a new and available (does not exists on the server) remotePath.
  939. * This adds an incremental suffix.
  940. *
  941. * @param client OwnCloud client
  942. * @param remotePath remote path of the file
  943. * @param metadata metadata of encrypted folder
  944. * @return new remote path
  945. */
  946. private String getNewAvailableRemotePath(OwnCloudClient client, String remotePath, DecryptedFolderMetadata metadata,
  947. boolean encrypted) {
  948. int extPos = remotePath.lastIndexOf('.');
  949. String suffix;
  950. String extension = "";
  951. String remotePathWithoutExtension = "";
  952. if (extPos >= 0) {
  953. extension = remotePath.substring(extPos + 1);
  954. remotePathWithoutExtension = remotePath.substring(0, extPos);
  955. }
  956. int count = 2;
  957. boolean exists;
  958. String newPath;
  959. do {
  960. suffix = " (" + count + ")";
  961. newPath = extPos >= 0 ? remotePathWithoutExtension + suffix + "." + extension : remotePath + suffix;
  962. exists = existsFile(client, newPath, metadata, encrypted);
  963. count++;
  964. } while (exists);
  965. return newPath;
  966. }
  967. private boolean existsFile(OwnCloudClient client, String remotePath, DecryptedFolderMetadata metadata,
  968. boolean encrypted) {
  969. if (encrypted) {
  970. String fileName = new File(remotePath).getName();
  971. for (DecryptedFolderMetadata.DecryptedFile file : metadata.getFiles().values()) {
  972. if (file.getEncrypted().getFilename().equalsIgnoreCase(fileName)) {
  973. return true;
  974. }
  975. }
  976. return false;
  977. } else {
  978. ExistenceCheckRemoteOperation existsOperation = new ExistenceCheckRemoteOperation(remotePath, false);
  979. RemoteOperationResult result = existsOperation.execute(client);
  980. return result.isSuccess();
  981. }
  982. }
  983. /**
  984. * Allows to cancel the actual upload operation. If actual upload operating
  985. * is in progress it is cancelled, if upload preparation is being performed
  986. * upload will not take place.
  987. */
  988. public void cancel(ResultCode cancellationReason) {
  989. if (mUploadOperation == null) {
  990. if (mUploadStarted.get()) {
  991. Log_OC.d(TAG, "Cancelling upload during upload preparations.");
  992. mCancellationRequested.set(true);
  993. } else {
  994. Log_OC.e(TAG, "No upload in progress. This should not happen.");
  995. }
  996. } else {
  997. Log_OC.d(TAG, "Cancelling upload during actual upload operation.");
  998. mUploadOperation.cancel(cancellationReason);
  999. }
  1000. }
  1001. /**
  1002. * As soon as this method return true, upload can be cancel via cancel().
  1003. */
  1004. public boolean isUploadInProgress() {
  1005. return mUploadStarted.get();
  1006. }
  1007. /**
  1008. * TODO rewrite with homogeneous fail handling, remove dependency on {@link RemoteOperationResult},
  1009. * TODO use Exceptions instead
  1010. *
  1011. * @param sourceFile Source file to copy.
  1012. * @param targetFile Target location to copy the file.
  1013. * @return {@link RemoteOperationResult}
  1014. * @throws IOException exception if file cannot be accessed
  1015. */
  1016. private RemoteOperationResult copy(File sourceFile, File targetFile) throws IOException {
  1017. Log_OC.d(TAG, "Copying local file");
  1018. if (FileStorageUtils.getUsableSpace() < sourceFile.length()) {
  1019. return new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL); // error when the file should be copied
  1020. } else {
  1021. Log_OC.d(TAG, "Creating temporal folder");
  1022. File temporalParent = targetFile.getParentFile();
  1023. if (!temporalParent.mkdirs() && !temporalParent.isDirectory()) {
  1024. return new RemoteOperationResult(ResultCode.CANNOT_CREATE_FILE);
  1025. }
  1026. Log_OC.d(TAG, "Creating temporal file");
  1027. if (!targetFile.createNewFile() && !targetFile.isFile()) {
  1028. return new RemoteOperationResult(ResultCode.CANNOT_CREATE_FILE);
  1029. }
  1030. Log_OC.d(TAG, "Copying file contents");
  1031. InputStream in = null;
  1032. OutputStream out = null;
  1033. try {
  1034. if (!mOriginalStoragePath.equals(targetFile.getAbsolutePath())) {
  1035. // In case document provider schema as 'content://'
  1036. if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
  1037. Uri uri = Uri.parse(mOriginalStoragePath);
  1038. in = mContext.getContentResolver().openInputStream(uri);
  1039. } else {
  1040. in = new FileInputStream(sourceFile);
  1041. }
  1042. out = new FileOutputStream(targetFile);
  1043. int nRead;
  1044. byte[] buf = new byte[4096];
  1045. while (!mCancellationRequested.get() &&
  1046. (nRead = in.read(buf)) > -1) {
  1047. out.write(buf, 0, nRead);
  1048. }
  1049. out.flush();
  1050. } // else: weird but possible situation, nothing to copy
  1051. if (mCancellationRequested.get()) {
  1052. return new RemoteOperationResult(new OperationCancelledException());
  1053. }
  1054. } catch (Exception e) {
  1055. return new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
  1056. } finally {
  1057. try {
  1058. if (in != null) {
  1059. in.close();
  1060. }
  1061. } catch (Exception e) {
  1062. Log_OC.d(TAG, "Weird exception while closing input stream for " +
  1063. mOriginalStoragePath + " (ignoring)", e);
  1064. }
  1065. try {
  1066. if (out != null) {
  1067. out.close();
  1068. }
  1069. } catch (Exception e) {
  1070. Log_OC.d(TAG, "Weird exception while closing output stream for " +
  1071. targetFile.getAbsolutePath() + " (ignoring)", e);
  1072. }
  1073. }
  1074. }
  1075. return new RemoteOperationResult(ResultCode.OK);
  1076. }
  1077. /**
  1078. * TODO rewrite with homogeneous fail handling, remove dependency on {@link RemoteOperationResult},
  1079. * TODO use Exceptions instead
  1080. * TODO refactor both this and 'copy' in a single method
  1081. *
  1082. * @param sourceFile Source file to move.
  1083. * @param targetFile Target location to move the file.
  1084. * @throws IOException exception if file cannot be read/wrote
  1085. */
  1086. private void move(File sourceFile, File targetFile) throws IOException {
  1087. if (!targetFile.equals(sourceFile)) {
  1088. File expectedFolder = targetFile.getParentFile();
  1089. expectedFolder.mkdirs();
  1090. if (expectedFolder.isDirectory()) {
  1091. if (!sourceFile.renameTo(targetFile)) {
  1092. // try to copy and then delete
  1093. targetFile.createNewFile();
  1094. FileChannel inChannel = new FileInputStream(sourceFile).getChannel();
  1095. FileChannel outChannel = new FileOutputStream(targetFile).getChannel();
  1096. try {
  1097. inChannel.transferTo(0, inChannel.size(), outChannel);
  1098. sourceFile.delete();
  1099. } catch (Exception e) {
  1100. mFile.setStoragePath(""); // forget the local file
  1101. // by now, treat this as a success; the file was uploaded
  1102. // the best option could be show a warning message
  1103. } finally {
  1104. if (inChannel != null) {
  1105. inChannel.close();
  1106. }
  1107. if (outChannel != null) {
  1108. outChannel.close();
  1109. }
  1110. }
  1111. }
  1112. } else {
  1113. mFile.setStoragePath("");
  1114. }
  1115. }
  1116. }
  1117. /**
  1118. * Saves a OC File after a successful upload.
  1119. * <p>
  1120. * A PROPFIND is necessary to keep the props in the local database
  1121. * synchronized with the server, specially the modification time and Etag
  1122. * (where available)
  1123. */
  1124. private void saveUploadedFile(OwnCloudClient client) {
  1125. OCFile file = mFile;
  1126. if (file.fileExists()) {
  1127. file = getStorageManager().getFileById(file.getFileId());
  1128. }
  1129. if (file == null) {
  1130. // this can happen e.g. when the file gets deleted during upload
  1131. return;
  1132. }
  1133. long syncDate = System.currentTimeMillis();
  1134. file.setLastSyncDateForData(syncDate);
  1135. // new PROPFIND to keep data consistent with server
  1136. // in theory, should return the same we already have
  1137. // TODO from the appropriate OC server version, get data from last PUT response headers, instead
  1138. // TODO of a new PROPFIND; the latter may fail, specially for chunked uploads
  1139. String path;
  1140. if (encryptedAncestor) {
  1141. path = file.getParentRemotePath() + mFile.getEncryptedFileName();
  1142. } else {
  1143. path = getRemotePath();
  1144. }
  1145. ReadFileRemoteOperation operation = new ReadFileRemoteOperation(path);
  1146. RemoteOperationResult result = operation.execute(client);
  1147. if (result.isSuccess()) {
  1148. updateOCFile(file, (RemoteFile) result.getData().get(0));
  1149. file.setLastSyncDateForProperties(syncDate);
  1150. } else {
  1151. Log_OC.e(TAG, "Error reading properties of file after successful upload; this is gonna hurt...");
  1152. }
  1153. if (mWasRenamed) {
  1154. OCFile oldFile = getStorageManager().getFileByPath(mOldFile.getRemotePath());
  1155. if (oldFile != null) {
  1156. oldFile.setStoragePath(null);
  1157. getStorageManager().saveFile(oldFile);
  1158. getStorageManager().saveConflict(oldFile, null);
  1159. }
  1160. // else: it was just an automatic renaming due to a name
  1161. // coincidence; nothing else is needed, the storagePath is right
  1162. // in the instance returned by mCurrentUpload.getFile()
  1163. }
  1164. file.setUpdateThumbnailNeeded(true);
  1165. getStorageManager().saveFile(file);
  1166. getStorageManager().saveConflict(file, null);
  1167. if (MimeTypeUtil.isMedia(file.getMimeType())) {
  1168. FileDataStorageManager.triggerMediaScan(file.getStoragePath(), file);
  1169. }
  1170. // generate new Thumbnail
  1171. final ThumbnailsCacheManager.ThumbnailGenerationTask task =
  1172. new ThumbnailsCacheManager.ThumbnailGenerationTask(getStorageManager(), user);
  1173. task.execute(new ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file, file.getRemoteId()));
  1174. }
  1175. private void updateOCFile(OCFile file, RemoteFile remoteFile) {
  1176. file.setCreationTimestamp(remoteFile.getCreationTimestamp());
  1177. file.setFileLength(remoteFile.getLength());
  1178. file.setMimeType(remoteFile.getMimeType());
  1179. file.setModificationTimestamp(remoteFile.getModifiedTimestamp());
  1180. file.setModificationTimestampAtLastSyncForData(remoteFile.getModifiedTimestamp());
  1181. file.setEtag(remoteFile.getEtag());
  1182. file.setRemoteId(remoteFile.getRemoteId());
  1183. }
  1184. public interface OnRenameListener {
  1185. void onRenameUpload();
  1186. }
  1187. }