UploadFileOperation.java 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * Copyright (C) 2016 ownCloud GmbH.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2,
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.owncloud.android.operations;
  20. import android.accounts.Account;
  21. import android.content.Context;
  22. import android.net.Uri;
  23. import com.evernote.android.job.JobRequest;
  24. import com.evernote.android.job.util.Device;
  25. import com.owncloud.android.datamodel.FileDataStorageManager;
  26. import com.owncloud.android.datamodel.OCFile;
  27. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  28. import com.owncloud.android.datamodel.UploadsStorageManager;
  29. import com.owncloud.android.db.OCUpload;
  30. import com.owncloud.android.files.services.FileUploader;
  31. import com.owncloud.android.lib.common.OwnCloudClient;
  32. import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  33. import com.owncloud.android.lib.common.network.ProgressiveDataTransferer;
  34. import com.owncloud.android.lib.common.operations.OperationCancelledException;
  35. import com.owncloud.android.lib.common.operations.RemoteOperation;
  36. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  37. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  38. import com.owncloud.android.lib.common.utils.Log_OC;
  39. import com.owncloud.android.lib.resources.files.ChunkedUploadRemoteFileOperation;
  40. import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
  41. import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
  42. import com.owncloud.android.lib.resources.files.RemoteFile;
  43. import com.owncloud.android.lib.resources.files.UploadRemoteFileOperation;
  44. import com.owncloud.android.operations.common.SyncOperation;
  45. import com.owncloud.android.utils.ConnectivityUtils;
  46. import com.owncloud.android.utils.FileStorageUtils;
  47. import com.owncloud.android.utils.MimeType;
  48. import com.owncloud.android.utils.MimeTypeUtil;
  49. import com.owncloud.android.utils.PowerUtils;
  50. import com.owncloud.android.utils.UriUtils;
  51. import org.apache.commons.httpclient.HttpStatus;
  52. import org.apache.commons.httpclient.methods.RequestEntity;
  53. import org.lukhnos.nnio.file.Files;
  54. import org.lukhnos.nnio.file.Paths;
  55. import java.io.File;
  56. import java.io.FileInputStream;
  57. import java.io.FileNotFoundException;
  58. import java.io.FileOutputStream;
  59. import java.io.IOException;
  60. import java.io.InputStream;
  61. import java.io.OutputStream;
  62. import java.io.RandomAccessFile;
  63. import java.nio.channels.FileChannel;
  64. import java.nio.channels.FileLock;
  65. import java.nio.channels.OverlappingFileLockException;
  66. import java.util.HashSet;
  67. import java.util.Iterator;
  68. import java.util.Set;
  69. import java.util.concurrent.atomic.AtomicBoolean;
  70. /**
  71. * Operation performing the update in the ownCloud server
  72. * of a file that was modified locally.
  73. */
  74. public class UploadFileOperation extends SyncOperation {
  75. private static final String TAG = UploadFileOperation.class.getSimpleName();
  76. public static final int CREATED_BY_USER = 0;
  77. public static final int CREATED_AS_INSTANT_PICTURE = 1;
  78. public static final int CREATED_AS_INSTANT_VIDEO = 2;
  79. /**
  80. * OCFile which is to be uploaded.
  81. */
  82. private OCFile mFile;
  83. /**
  84. * Original OCFile which is to be uploaded in case file had to be renamed
  85. * (if forceOverwrite==false and remote file already exists).
  86. */
  87. private OCFile mOldFile;
  88. private String mRemotePath = null;
  89. private boolean mChunked = false;
  90. private boolean mRemoteFolderToBeCreated = false;
  91. private boolean mForceOverwrite = false;
  92. private int mLocalBehaviour = FileUploader.LOCAL_BEHAVIOUR_COPY;
  93. private int mCreatedBy = CREATED_BY_USER;
  94. private boolean mOnWifiOnly = false;
  95. private boolean mWhileChargingOnly = false;
  96. private boolean mIgnoringPowerSaveMode = false;
  97. private boolean mWasRenamed = false;
  98. private long mOCUploadId = -1;
  99. /**
  100. * Local path to file which is to be uploaded (before any possible renaming or moving).
  101. */
  102. private String mOriginalStoragePath = null;
  103. private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
  104. private OnRenameListener mRenameUploadListener;
  105. private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
  106. private final AtomicBoolean mUploadStarted = new AtomicBoolean(false);
  107. private Context mContext;
  108. private UploadRemoteFileOperation mUploadOperation;
  109. protected RequestEntity mEntity = null;
  110. private Account mAccount;
  111. public static OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType) {
  112. // MIME type
  113. if (mimeType == null || mimeType.length() <= 0) {
  114. mimeType = MimeTypeUtil.getBestMimeTypeByFilename(localPath);
  115. }
  116. OCFile newFile = new OCFile(remotePath);
  117. newFile.setStoragePath(localPath);
  118. newFile.setLastSyncDateForProperties(0);
  119. newFile.setLastSyncDateForData(0);
  120. // size
  121. if (localPath != null && localPath.length() > 0) {
  122. File localFile = new File(localPath);
  123. newFile.setFileLength(localFile.length());
  124. newFile.setLastSyncDateForData(localFile.lastModified());
  125. } // don't worry about not assigning size, the problems with localPath
  126. // are checked when the UploadFileOperation instance is created
  127. newFile.setMimetype(mimeType);
  128. return newFile;
  129. }
  130. public UploadFileOperation(Account account,
  131. OCFile file,
  132. OCUpload upload,
  133. boolean chunked,
  134. boolean forceOverwrite,
  135. int localBehaviour,
  136. Context context,
  137. boolean onWifiOnly,
  138. boolean whileChargingOnly
  139. ) {
  140. if (account == null) {
  141. throw new IllegalArgumentException("Illegal NULL account in UploadFileOperation " + "creation");
  142. }
  143. if (upload == null) {
  144. throw new IllegalArgumentException("Illegal NULL file in UploadFileOperation creation");
  145. }
  146. if (upload.getLocalPath() == null || upload.getLocalPath().length() <= 0) {
  147. throw new IllegalArgumentException(
  148. "Illegal file in UploadFileOperation; storage path invalid: "
  149. + upload.getLocalPath());
  150. }
  151. mAccount = account;
  152. if (file == null) {
  153. mFile = obtainNewOCFileToUpload(
  154. upload.getRemotePath(),
  155. upload.getLocalPath(),
  156. upload.getMimeType()
  157. );
  158. } else {
  159. mFile = file;
  160. }
  161. mOnWifiOnly = onWifiOnly;
  162. mWhileChargingOnly = whileChargingOnly;
  163. mRemotePath = upload.getRemotePath();
  164. mChunked = chunked;
  165. mForceOverwrite = forceOverwrite;
  166. mLocalBehaviour = localBehaviour;
  167. mOriginalStoragePath = mFile.getStoragePath();
  168. mContext = context;
  169. mOCUploadId = upload.getUploadId();
  170. mCreatedBy = upload.getCreadtedBy();
  171. mRemoteFolderToBeCreated = upload.isCreateRemoteFolder();
  172. // Ignore power save mode only if user explicitly created this upload
  173. mIgnoringPowerSaveMode = (mCreatedBy == CREATED_BY_USER);
  174. }
  175. public boolean getIsWifiRequired() {
  176. return mOnWifiOnly;
  177. }
  178. public boolean getIsChargingRequired() {
  179. return mWhileChargingOnly;
  180. }
  181. public boolean getIsIgnoringPowerSaveMode() { return mIgnoringPowerSaveMode; }
  182. public Account getAccount() {
  183. return mAccount;
  184. }
  185. public String getFileName() {
  186. return (mFile != null) ? mFile.getFileName() : null;
  187. }
  188. public OCFile getFile() {
  189. return mFile;
  190. }
  191. /**
  192. * If remote file was renamed, return original OCFile which was uploaded. Is
  193. * null is file was not renamed.
  194. */
  195. public OCFile getOldFile() {
  196. return mOldFile;
  197. }
  198. public String getOriginalStoragePath() {
  199. return mOriginalStoragePath;
  200. }
  201. public String getStoragePath() {
  202. return mFile.getStoragePath();
  203. }
  204. public String getRemotePath() {
  205. return mFile.getRemotePath();
  206. }
  207. public String getMimeType() {
  208. return mFile.getMimetype();
  209. }
  210. public int getLocalBehaviour() {
  211. return mLocalBehaviour;
  212. }
  213. public void setRemoteFolderToBeCreated() {
  214. mRemoteFolderToBeCreated = true;
  215. }
  216. public boolean wasRenamed() {
  217. return mWasRenamed;
  218. }
  219. public void setCreatedBy(int createdBy) {
  220. mCreatedBy = createdBy;
  221. if (createdBy < CREATED_BY_USER || CREATED_AS_INSTANT_VIDEO < createdBy) {
  222. mCreatedBy = CREATED_BY_USER;
  223. }
  224. }
  225. public int getCreatedBy() {
  226. return mCreatedBy;
  227. }
  228. public boolean isInstantPicture() {
  229. return mCreatedBy == CREATED_AS_INSTANT_PICTURE;
  230. }
  231. public boolean isInstantVideo() {
  232. return mCreatedBy == CREATED_AS_INSTANT_VIDEO;
  233. }
  234. public void setOCUploadId(long id) {
  235. mOCUploadId = id;
  236. }
  237. public long getOCUploadId() {
  238. return mOCUploadId;
  239. }
  240. public Set<OnDatatransferProgressListener> getDataTransferListeners() {
  241. return mDataTransferListeners;
  242. }
  243. public void addDatatransferProgressListener(OnDatatransferProgressListener listener) {
  244. synchronized (mDataTransferListeners) {
  245. mDataTransferListeners.add(listener);
  246. }
  247. if (mEntity != null) {
  248. ((ProgressiveDataTransferer) mEntity).addDatatransferProgressListener(listener);
  249. }
  250. if (mUploadOperation != null) {
  251. mUploadOperation.addDatatransferProgressListener(listener);
  252. }
  253. }
  254. public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
  255. synchronized (mDataTransferListeners) {
  256. mDataTransferListeners.remove(listener);
  257. }
  258. if (mEntity != null) {
  259. ((ProgressiveDataTransferer) mEntity).removeDatatransferProgressListener(listener);
  260. }
  261. if (mUploadOperation != null) {
  262. mUploadOperation.removeDatatransferProgressListener(listener);
  263. }
  264. }
  265. public void addRenameUploadListener(OnRenameListener listener) {
  266. mRenameUploadListener = listener;
  267. }
  268. @Override
  269. @SuppressWarnings("PMD.AvoidDuplicateLiterals")
  270. protected RemoteOperationResult run(OwnCloudClient client) {
  271. mCancellationRequested.set(false);
  272. mUploadStarted.set(true);
  273. RemoteOperationResult result = null;
  274. File temporalFile = null;
  275. File originalFile = new File(mOriginalStoragePath);
  276. File expectedFile = null;
  277. FileLock fileLock = null;
  278. UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(mContext.getContentResolver(),
  279. mContext);
  280. long size = 0;
  281. for (OCUpload ocUpload : uploadsStorageManager.getAllStoredUploads()) {
  282. if (ocUpload.getUploadId() == getOCUploadId()) {
  283. ocUpload.setFileSize(size);
  284. uploadsStorageManager.updateUpload(ocUpload);
  285. break;
  286. }
  287. }
  288. try {
  289. if (Device.getNetworkType(mContext).equals(JobRequest.NetworkType.ANY) ||
  290. ConnectivityUtils.isInternetWalled(mContext)) {
  291. return new RemoteOperationResult(ResultCode.NO_NETWORK_CONNECTION);
  292. }
  293. /// Check that connectivity conditions are met and delays the upload otherwise
  294. if (mOnWifiOnly && !Device.getNetworkType(mContext).equals(JobRequest.NetworkType.UNMETERED)) {
  295. Log_OC.d(TAG, "Upload delayed until WiFi is available: " + getRemotePath());
  296. return new RemoteOperationResult(ResultCode.DELAYED_FOR_WIFI);
  297. }
  298. // Check if charging conditions are met and delays the upload otherwise
  299. if (mWhileChargingOnly && !Device.getBatteryStatus(mContext).isCharging()) {
  300. Log_OC.d(TAG, "Upload delayed until the device is charging: " + getRemotePath());
  301. return new RemoteOperationResult(ResultCode.DELAYED_FOR_CHARGING);
  302. }
  303. // Check that device is not in power save mode
  304. if (!mIgnoringPowerSaveMode && PowerUtils.isPowerSaveMode(mContext)) {
  305. Log_OC.d(TAG, "Upload delayed because device is in power save mode: " + getRemotePath());
  306. return new RemoteOperationResult(ResultCode.DELAYED_IN_POWER_SAVE_MODE);
  307. }
  308. /// check if the file continues existing before schedule the operation
  309. if (!originalFile.exists()) {
  310. Log_OC.d(TAG, mOriginalStoragePath + " not exists anymore");
  311. return new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
  312. }
  313. /// check the existence of the parent folder for the file to upload
  314. String remoteParentPath = new File(getRemotePath()).getParent();
  315. remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ?
  316. remoteParentPath : remoteParentPath + OCFile.PATH_SEPARATOR;
  317. result = grantFolderExistence(remoteParentPath, client);
  318. if (!result.isSuccess()) {
  319. return result;
  320. }
  321. /// set parent local id in uploading file
  322. OCFile parent = getStorageManager().getFileByPath(remoteParentPath);
  323. mFile.setParentId(parent.getFileId());
  324. /// automatic rename of file to upload in case of name collision in server
  325. Log_OC.d(TAG, "Checking name collision in server");
  326. if (!mForceOverwrite) {
  327. String remotePath = getAvailableRemotePath(client, mRemotePath);
  328. mWasRenamed = !remotePath.equals(mRemotePath);
  329. if (mWasRenamed) {
  330. createNewOCFile(remotePath);
  331. Log_OC.d(TAG, "File renamed as " + remotePath);
  332. }
  333. mRemotePath = remotePath;
  334. mRenameUploadListener.onRenameUpload();
  335. }
  336. if (mCancellationRequested.get()) {
  337. throw new OperationCancelledException();
  338. }
  339. String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);
  340. expectedFile = new File(expectedPath);
  341. /// copy the file locally before uploading
  342. if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY &&
  343. !mOriginalStoragePath.equals(expectedPath)) {
  344. String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
  345. mFile.setStoragePath(temporalPath);
  346. temporalFile = new File(temporalPath);
  347. result = copy(originalFile, temporalFile);
  348. if (result != null) {
  349. return result;
  350. }
  351. }
  352. if (mCancellationRequested.get()) {
  353. throw new OperationCancelledException();
  354. }
  355. // Get the last modification date of the file from the file system
  356. Long timeStampLong = originalFile.lastModified() / 1000;
  357. String timeStamp = timeStampLong.toString();
  358. FileChannel channel = null;
  359. try {
  360. channel = new RandomAccessFile(mFile.getStoragePath(), "rw").getChannel();
  361. fileLock = channel.tryLock();
  362. } catch (FileNotFoundException e) {
  363. // this basically means that the file is on SD card
  364. // try to copy file to temporary dir if it doesn't exist
  365. String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
  366. mFile.setStoragePath(temporalPath);
  367. temporalFile = new File(temporalPath);
  368. Files.deleteIfExists(Paths.get(temporalPath));
  369. result = copy(originalFile, temporalFile);
  370. if (result == null) {
  371. if (temporalFile.length() == originalFile.length()) {
  372. channel = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw").getChannel();
  373. fileLock = channel.tryLock();
  374. } else {
  375. result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
  376. }
  377. }
  378. }
  379. try {
  380. size = channel.size();
  381. } catch (IOException e1) {
  382. size = new File(mFile.getStoragePath()).length();
  383. }
  384. for (OCUpload ocUpload : uploadsStorageManager.getAllStoredUploads()) {
  385. if (ocUpload.getUploadId() == getOCUploadId()) {
  386. ocUpload.setFileSize(size);
  387. uploadsStorageManager.updateUpload(ocUpload);
  388. break;
  389. }
  390. }
  391. /// perform the upload
  392. if (mChunked &&
  393. (size > ChunkedUploadRemoteFileOperation.CHUNK_SIZE)) {
  394. mUploadOperation = new ChunkedUploadRemoteFileOperation(mContext, mFile.getStoragePath(),
  395. mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict(), timeStamp);
  396. } else {
  397. mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(),
  398. mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict(), timeStamp);
  399. }
  400. Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
  401. while (listener.hasNext()) {
  402. mUploadOperation.addDatatransferProgressListener(listener.next());
  403. }
  404. if (mCancellationRequested.get()) {
  405. throw new OperationCancelledException();
  406. }
  407. if (result == null || result.isSuccess() && mUploadOperation != null) {
  408. result = mUploadOperation.execute(client);
  409. /// move local temporal file or original file to its corresponding
  410. // location in the ownCloud local folder
  411. if (!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
  412. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  413. }
  414. }
  415. } catch (FileNotFoundException e) {
  416. Log_OC.d(TAG, mOriginalStoragePath + " not exists anymore");
  417. result = new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
  418. } catch (OverlappingFileLockException e) {
  419. Log_OC.d(TAG, "Overlapping file lock exception");
  420. result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
  421. } catch (Exception e) {
  422. result = new RemoteOperationResult(e);
  423. } finally {
  424. mUploadStarted.set(false);
  425. if (fileLock != null) {
  426. try {
  427. fileLock.release();
  428. } catch (IOException e) {
  429. Log_OC.e(TAG, "Failed to unlock file with path " + mOriginalStoragePath);
  430. }
  431. }
  432. if (temporalFile != null && !originalFile.equals(temporalFile)) {
  433. temporalFile.delete();
  434. }
  435. if (result == null) {
  436. result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  437. }
  438. if (result.isSuccess()) {
  439. Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " +
  440. result.getLogMessage());
  441. } else {
  442. if (result.getException() != null) {
  443. if (result.isCancelled()) {
  444. Log_OC.w(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath +
  445. ": " + result.getLogMessage());
  446. } else {
  447. Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath +
  448. ": " + result.getLogMessage(), result.getException());
  449. }
  450. } else {
  451. Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath +
  452. ": " + result.getLogMessage());
  453. }
  454. }
  455. }
  456. if (result.isSuccess()) {
  457. if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) {
  458. String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
  459. if (mOriginalStoragePath.equals(temporalPath)) {
  460. // delete local file is was pre-copied in temporary folder (see .ui.helpers.UriUploader)
  461. temporalFile = new File(temporalPath);
  462. temporalFile.delete();
  463. }
  464. mFile.setStoragePath("");
  465. saveUploadedFile(client);
  466. } else if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_DELETE) {
  467. originalFile.delete();
  468. getStorageManager().deleteFileInMediaScan(originalFile.getAbsolutePath());
  469. saveUploadedFile(client);
  470. } else {
  471. if (temporalFile != null) { // FileUploader.LOCAL_BEHAVIOUR_COPY
  472. try {
  473. move(temporalFile, expectedFile);
  474. } catch (IOException e) {
  475. e.printStackTrace();
  476. }
  477. } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
  478. try {
  479. move(originalFile, expectedFile);
  480. } catch (IOException e) {
  481. e.printStackTrace();
  482. }
  483. getStorageManager().deleteFileInMediaScan(originalFile.getAbsolutePath());
  484. }
  485. mFile.setStoragePath(expectedFile.getAbsolutePath());
  486. saveUploadedFile(client);
  487. FileDataStorageManager.triggerMediaScan(expectedFile.getAbsolutePath());
  488. }
  489. } else if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  490. getStorageManager().saveConflict(mFile, mFile.getEtagInConflict());
  491. }
  492. return result;
  493. }
  494. /**
  495. * Checks the existence of the folder where the current file will be uploaded both
  496. * in the remote server and in the local database.
  497. * <p/>
  498. * If the upload is set to enforce the creation of the folder, the method tries to
  499. * create it both remote and locally.
  500. *
  501. * @param pathToGrant Full remote path whose existence will be granted.
  502. * @return An {@link OCFile} instance corresponding to the folder where the file
  503. * will be uploaded.
  504. */
  505. private RemoteOperationResult grantFolderExistence(String pathToGrant, OwnCloudClient client) {
  506. RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, mContext, false);
  507. RemoteOperationResult result = operation.execute(client);
  508. if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND && mRemoteFolderToBeCreated) {
  509. SyncOperation syncOp = new CreateFolderOperation(pathToGrant, true);
  510. result = syncOp.execute(client, getStorageManager());
  511. }
  512. if (result.isSuccess()) {
  513. OCFile parentDir = getStorageManager().getFileByPath(pathToGrant);
  514. if (parentDir == null) {
  515. parentDir = createLocalFolder(pathToGrant);
  516. }
  517. if (parentDir != null) {
  518. result = new RemoteOperationResult(ResultCode.OK);
  519. } else {
  520. result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  521. }
  522. }
  523. return result;
  524. }
  525. private OCFile createLocalFolder(String remotePath) {
  526. String parentPath = new File(remotePath).getParent();
  527. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ?
  528. parentPath : parentPath + OCFile.PATH_SEPARATOR;
  529. OCFile parent = getStorageManager().getFileByPath(parentPath);
  530. if (parent == null) {
  531. parent = createLocalFolder(parentPath);
  532. }
  533. if (parent != null) {
  534. OCFile createdFolder = new OCFile(remotePath);
  535. createdFolder.setMimetype(MimeType.DIRECTORY);
  536. createdFolder.setParentId(parent.getFileId());
  537. getStorageManager().saveFile(createdFolder);
  538. return createdFolder;
  539. }
  540. return null;
  541. }
  542. /**
  543. * Create a new OCFile mFile with new remote path. This is required if forceOverwrite==false.
  544. * New file is stored as mFile, original as mOldFile.
  545. *
  546. * @param newRemotePath new remote path
  547. */
  548. private void createNewOCFile(String newRemotePath) {
  549. // a new OCFile instance must be created for a new remote path
  550. OCFile newFile = new OCFile(newRemotePath);
  551. newFile.setCreationTimestamp(mFile.getCreationTimestamp());
  552. newFile.setFileLength(mFile.getFileLength());
  553. newFile.setMimetype(mFile.getMimetype());
  554. newFile.setModificationTimestamp(mFile.getModificationTimestamp());
  555. newFile.setModificationTimestampAtLastSyncForData(
  556. mFile.getModificationTimestampAtLastSyncForData()
  557. );
  558. newFile.setEtag(mFile.getEtag());
  559. newFile.setAvailableOffline(mFile.isAvailableOffline());
  560. newFile.setLastSyncDateForProperties(mFile.getLastSyncDateForProperties());
  561. newFile.setLastSyncDateForData(mFile.getLastSyncDateForData());
  562. newFile.setStoragePath(mFile.getStoragePath());
  563. newFile.setParentId(mFile.getParentId());
  564. mOldFile = mFile;
  565. mFile = newFile;
  566. }
  567. /**
  568. * Checks if remotePath does not exist in the server and returns it, or adds
  569. * a suffix to it in order to avoid the server file is overwritten.
  570. *
  571. * @param wc
  572. * @param remotePath
  573. * @return
  574. */
  575. private String getAvailableRemotePath(OwnCloudClient wc, String remotePath) {
  576. boolean check = existsFile(wc, remotePath);
  577. if (!check) {
  578. return remotePath;
  579. }
  580. int pos = remotePath.lastIndexOf('.');
  581. String suffix = "";
  582. String extension = "";
  583. if (pos >= 0) {
  584. extension = remotePath.substring(pos + 1);
  585. remotePath = remotePath.substring(0, pos);
  586. }
  587. int count = 2;
  588. do {
  589. suffix = " (" + count + ")";
  590. if (pos >= 0) {
  591. check = existsFile(wc, remotePath + suffix + "." + extension);
  592. } else {
  593. check = existsFile(wc, remotePath + suffix);
  594. }
  595. count++;
  596. } while (check);
  597. if (pos >= 0) {
  598. return remotePath + suffix + "." + extension;
  599. } else {
  600. return remotePath + suffix;
  601. }
  602. }
  603. private boolean existsFile(OwnCloudClient client, String remotePath) {
  604. ExistenceCheckRemoteOperation existsOperation =
  605. new ExistenceCheckRemoteOperation(remotePath, mContext, false);
  606. RemoteOperationResult result = existsOperation.execute(client);
  607. return result.isSuccess();
  608. }
  609. /**
  610. * Allows to cancel the actual upload operation. If actual upload operating
  611. * is in progress it is cancelled, if upload preparation is being performed
  612. * upload will not take place.
  613. */
  614. public void cancel() {
  615. if (mUploadOperation == null) {
  616. if (mUploadStarted.get()) {
  617. Log_OC.d(TAG, "Cancelling upload during upload preparations.");
  618. mCancellationRequested.set(true);
  619. } else {
  620. Log_OC.e(TAG, "No upload in progress. This should not happen.");
  621. }
  622. } else {
  623. Log_OC.d(TAG, "Cancelling upload during actual upload operation.");
  624. mUploadOperation.cancel();
  625. }
  626. }
  627. /**
  628. * As soon as this method return true, upload can be cancel via cancel().
  629. */
  630. public boolean isUploadInProgress() {
  631. return mUploadStarted.get();
  632. }
  633. /**
  634. * TODO rewrite with homogeneous fail handling, remove dependency on {@link RemoteOperationResult},
  635. * TODO use Exceptions instead
  636. *
  637. * @param sourceFile Source file to copy.
  638. * @param targetFile Target location to copy the file.
  639. * @return {@link RemoteOperationResult}
  640. * @throws IOException
  641. */
  642. private RemoteOperationResult copy(File sourceFile, File targetFile) throws IOException {
  643. Log_OC.d(TAG, "Copying local file");
  644. RemoteOperationResult result = null;
  645. if (FileStorageUtils.getUsableSpace(mAccount.name) < sourceFile.length()) {
  646. result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
  647. return result; // error condition when the file should be copied
  648. } else {
  649. Log_OC.d(TAG, "Creating temporal folder");
  650. File temporalParent = targetFile.getParentFile();
  651. temporalParent.mkdirs();
  652. if (!temporalParent.isDirectory()) {
  653. throw new IOException(
  654. "Unexpected error: parent directory could not be created");
  655. }
  656. Log_OC.d(TAG, "Creating temporal file");
  657. targetFile.createNewFile();
  658. if (!targetFile.isFile()) {
  659. throw new IOException(
  660. "Unexpected error: target file could not be created");
  661. }
  662. Log_OC.d(TAG, "Copying file contents");
  663. InputStream in = null;
  664. OutputStream out = null;
  665. try {
  666. if (!mOriginalStoragePath.equals(targetFile.getAbsolutePath())) {
  667. // In case document provider schema as 'content://'
  668. if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
  669. Uri uri = Uri.parse(mOriginalStoragePath);
  670. in = mContext.getContentResolver().openInputStream(uri);
  671. } else {
  672. in = new FileInputStream(sourceFile);
  673. }
  674. out = new FileOutputStream(targetFile);
  675. int nRead;
  676. byte[] buf = new byte[4096];
  677. while (!mCancellationRequested.get() &&
  678. (nRead = in.read(buf)) > -1) {
  679. out.write(buf, 0, nRead);
  680. }
  681. out.flush();
  682. } // else: weird but possible situation, nothing to copy
  683. if (mCancellationRequested.get()) {
  684. result = new RemoteOperationResult(new OperationCancelledException());
  685. return result;
  686. }
  687. } catch (Exception e) {
  688. result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
  689. return result;
  690. } finally {
  691. try {
  692. if (in != null) {
  693. in.close();
  694. }
  695. } catch (Exception e) {
  696. Log_OC.d(TAG, "Weird exception while closing input stream for " +
  697. mOriginalStoragePath + " (ignoring)", e);
  698. }
  699. try {
  700. if (out != null) {
  701. out.close();
  702. }
  703. } catch (Exception e) {
  704. Log_OC.d(TAG, "Weird exception while closing output stream for " +
  705. targetFile.getAbsolutePath() + " (ignoring)", e);
  706. }
  707. }
  708. }
  709. return result;
  710. }
  711. /**
  712. * TODO rewrite with homogeneous fail handling, remove dependency on {@link RemoteOperationResult},
  713. * TODO use Exceptions instead
  714. *
  715. * TODO refactor both this and 'copy' in a single method
  716. *
  717. * @param sourceFile Source file to move.
  718. * @param targetFile Target location to move the file.
  719. * @return {@link RemoteOperationResult}
  720. * @throws IOException
  721. */
  722. private void move(File sourceFile, File targetFile) throws IOException {
  723. if (!targetFile.equals(sourceFile)) {
  724. File expectedFolder = targetFile.getParentFile();
  725. expectedFolder.mkdirs();
  726. if (expectedFolder.isDirectory()) {
  727. if (!sourceFile.renameTo(targetFile)) {
  728. // try to copy and then delete
  729. targetFile.createNewFile();
  730. FileChannel inChannel = new FileInputStream(sourceFile).getChannel();
  731. FileChannel outChannel = new FileOutputStream(targetFile).getChannel();
  732. try {
  733. inChannel.transferTo(0, inChannel.size(), outChannel);
  734. sourceFile.delete();
  735. } catch (Exception e) {
  736. mFile.setStoragePath(""); // forget the local file
  737. // by now, treat this as a success; the file was uploaded
  738. // the best option could be show a warning message
  739. } finally {
  740. if (inChannel != null) {
  741. inChannel.close();
  742. }
  743. if (outChannel != null) {
  744. outChannel.close();
  745. }
  746. }
  747. }
  748. } else {
  749. mFile.setStoragePath("");
  750. }
  751. }
  752. }
  753. /**
  754. * Saves a OC File after a successful upload.
  755. * <p/>
  756. * A PROPFIND is necessary to keep the props in the local database
  757. * synchronized with the server, specially the modification time and Etag
  758. * (where available)
  759. * <p/>
  760. */
  761. private void saveUploadedFile(OwnCloudClient client) {
  762. OCFile file = mFile;
  763. if (file.fileExists()) {
  764. file = getStorageManager().getFileById(file.getFileId());
  765. }
  766. long syncDate = System.currentTimeMillis();
  767. file.setLastSyncDateForData(syncDate);
  768. // new PROPFIND to keep data consistent with server
  769. // in theory, should return the same we already have
  770. // TODO from the appropriate OC server version, get data from last PUT response headers, instead
  771. // TODO of a new PROPFIND; the latter may fail, specially for chunked uploads
  772. ReadRemoteFileOperation operation = new ReadRemoteFileOperation(getRemotePath());
  773. RemoteOperationResult result = operation.execute(client);
  774. if (result.isSuccess()) {
  775. updateOCFile(file, (RemoteFile) result.getData().get(0));
  776. file.setLastSyncDateForProperties(syncDate);
  777. } else {
  778. Log_OC.e(TAG, "Error reading properties of file after successful upload; this is gonna hurt...");
  779. }
  780. if (mWasRenamed) {
  781. OCFile oldFile = getStorageManager().getFileByPath(mOldFile.getRemotePath());
  782. if (oldFile != null) {
  783. oldFile.setStoragePath(null);
  784. getStorageManager().saveFile(oldFile);
  785. getStorageManager().saveConflict(oldFile, null);
  786. }
  787. // else: it was just an automatic renaming due to a name
  788. // coincidence; nothing else is needed, the storagePath is right
  789. // in the instance returned by mCurrentUpload.getFile()
  790. }
  791. file.setNeedsUpdateThumbnail(true);
  792. getStorageManager().saveFile(file);
  793. getStorageManager().saveConflict(file, null);
  794. FileDataStorageManager.triggerMediaScan(file.getStoragePath());
  795. // generate new Thumbnail
  796. final ThumbnailsCacheManager.ThumbnailGenerationTask task =
  797. new ThumbnailsCacheManager.ThumbnailGenerationTask(getStorageManager(), mAccount);
  798. task.execute(new ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file, file.getRemoteId()));
  799. }
  800. private void updateOCFile(OCFile file, RemoteFile remoteFile) {
  801. file.setCreationTimestamp(remoteFile.getCreationTimestamp());
  802. file.setFileLength(remoteFile.getLength());
  803. file.setMimetype(remoteFile.getMimeType());
  804. file.setModificationTimestamp(remoteFile.getModifiedTimestamp());
  805. file.setModificationTimestampAtLastSyncForData(remoteFile.getModifiedTimestamp());
  806. file.setEtag(remoteFile.getEtag());
  807. file.setRemoteId(remoteFile.getRemoteId());
  808. }
  809. public interface OnRenameListener {
  810. void onRenameUpload();
  811. }
  812. }