UploadFileOperation.java 61 KB

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