UploadFileOperation.java 56 KB

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