UploadFileOperation.java 54 KB

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