UploadFileOperation.java 56 KB

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