UploadFileOperation.java 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402
  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()) {
  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);
  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. try {
  408. // TODO change key if file has changed, e.g. when file is updated
  409. key = encodeStringToBase64Bytes(metadata.files.get(mFile.getFileName()).encrypted.key);
  410. } catch (Exception e) {
  411. // no key found
  412. }
  413. if (key == null || key.length == 0) {
  414. key = EncryptionUtils.generateKey();
  415. }
  416. // IV
  417. byte[] iv = null;
  418. try {
  419. iv = encodeStringToBase64Bytes(metadata.files.get(mFile.getFileName()).initializationVector);
  420. } catch (Exception e) {
  421. // no iv found
  422. }
  423. if (iv == null || iv.length == 0) {
  424. iv = EncryptionUtils.generateIV();
  425. }
  426. EncryptionUtils.EncryptedFile encryptedFile = EncryptionUtils.encryptFile(mFile, key, iv);
  427. // new random file name, check if it exists in metadata
  428. String encryptedFileName = UUID.randomUUID().toString().replaceAll("-", "");
  429. while (metadata.files.get(encryptedFileName) != null) {
  430. encryptedFileName = UUID.randomUUID().toString().replaceAll("-", "");
  431. }
  432. mFile.setEncryptedFileName(encryptedFileName);
  433. File encryptedTempFile = File.createTempFile("encFile", encryptedFileName);
  434. FileOutputStream fileOutputStream = new FileOutputStream(encryptedTempFile);
  435. fileOutputStream.write(encryptedFile.encryptedBytes);
  436. fileOutputStream.close();
  437. /***** E2E *****/
  438. FileChannel channel = null;
  439. try {
  440. channel = new RandomAccessFile(mFile.getStoragePath(), "rw").getChannel();
  441. fileLock = channel.tryLock();
  442. } catch (FileNotFoundException e) {
  443. // this basically means that the file is on SD card
  444. // try to copy file to temporary dir if it doesn't exist
  445. String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
  446. mFile.setStoragePath(temporalPath);
  447. temporalFile = new File(temporalPath);
  448. Files.deleteIfExists(Paths.get(temporalPath));
  449. result = copy(originalFile, temporalFile);
  450. if (result == null) {
  451. if (temporalFile.length() == originalFile.length()) {
  452. channel = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw").getChannel();
  453. fileLock = channel.tryLock();
  454. } else {
  455. result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
  456. }
  457. }
  458. }
  459. try {
  460. size = channel.size();
  461. } catch (IOException e1) {
  462. size = new File(mFile.getStoragePath()).length();
  463. }
  464. for (OCUpload ocUpload : uploadsStorageManager.getAllStoredUploads()) {
  465. if (ocUpload.getUploadId() == getOCUploadId()) {
  466. ocUpload.setFileSize(size);
  467. uploadsStorageManager.updateUpload(ocUpload);
  468. break;
  469. }
  470. }
  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. if (Device.getNetworkType(mContext).equals(JobRequest.NetworkType.ANY) ||
  634. ConnectivityUtils.isInternetWalled(mContext)) {
  635. return new RemoteOperationResult(ResultCode.NO_NETWORK_CONNECTION);
  636. }
  637. /// Check that connectivity conditions are met and delays the upload otherwise
  638. // TODO verify if this can be deleted
  639. if (mOnWifiOnly && !Device.getNetworkType(mContext).equals(JobRequest.NetworkType.UNMETERED)) {
  640. Log_OC.d(TAG, "Upload delayed until WiFi is available: " + getRemotePath());
  641. return new RemoteOperationResult(ResultCode.DELAYED_FOR_WIFI);
  642. }
  643. // TODO verify if this can be deleted
  644. // Check if charging conditions are met and delays the upload otherwise
  645. if (mWhileChargingOnly && !Device.isCharging(mContext)) {
  646. Log_OC.d(TAG, "Upload delayed until the device is charging: " + getRemotePath());
  647. return new RemoteOperationResult(ResultCode.DELAYED_FOR_CHARGING);
  648. }
  649. // Check that device is not in power save mode
  650. if (!mIgnoringPowerSaveMode && UploadUtils.isPowerSaveMode(mContext)) {
  651. Log_OC.d(TAG, "Upload delayed because device is in power save mode: " + getRemotePath());
  652. return new RemoteOperationResult(ResultCode.DELAYED_IN_POWER_SAVE_MODE);
  653. }
  654. /// check if the file continues existing before schedule the operation
  655. if (!originalFile.exists()) {
  656. Log_OC.d(TAG, mOriginalStoragePath + " not exists anymore");
  657. return new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
  658. }
  659. return null;
  660. }
  661. private RemoteOperationResult normalUpload(OwnCloudClient client) {
  662. RemoteOperationResult result = null;
  663. File temporalFile = null;
  664. File originalFile = new File(mOriginalStoragePath);
  665. File expectedFile = null;
  666. FileLock fileLock = null;
  667. long size = 0;
  668. try {
  669. // check conditions
  670. result = checkConditions(originalFile);
  671. // check name collision
  672. checkNameCollision(client);
  673. String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);
  674. expectedFile = new File(expectedPath);
  675. result = copyFile(originalFile, expectedPath);
  676. if (result != null) {
  677. return result;
  678. }
  679. // Get the last modification date of the file from the file system
  680. Long timeStampLong = originalFile.lastModified() / 1000;
  681. String timeStamp = timeStampLong.toString();
  682. FileChannel channel = null;
  683. try {
  684. channel = new RandomAccessFile(mFile.getStoragePath(), "rw").getChannel();
  685. fileLock = channel.tryLock();
  686. } catch (FileNotFoundException e) {
  687. // this basically means that the file is on SD card
  688. // try to copy file to temporary dir if it doesn't exist
  689. String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
  690. mFile.setStoragePath(temporalPath);
  691. temporalFile = new File(temporalPath);
  692. Files.deleteIfExists(Paths.get(temporalPath));
  693. result = copy(originalFile, temporalFile);
  694. if (result == null) {
  695. if (temporalFile.length() == originalFile.length()) {
  696. channel = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw").getChannel();
  697. fileLock = channel.tryLock();
  698. } else {
  699. result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
  700. }
  701. }
  702. }
  703. try {
  704. size = channel.size();
  705. } catch (IOException e1) {
  706. size = new File(mFile.getStoragePath()).length();
  707. }
  708. for (OCUpload ocUpload : uploadsStorageManager.getAllStoredUploads()) {
  709. if (ocUpload.getUploadId() == getOCUploadId()) {
  710. ocUpload.setFileSize(size);
  711. uploadsStorageManager.updateUpload(ocUpload);
  712. break;
  713. }
  714. }
  715. // perform the upload
  716. if (mChunked && (size > ChunkedUploadRemoteFileOperation.CHUNK_SIZE)) {
  717. mUploadOperation = new ChunkedUploadRemoteFileOperation(mContext, mFile.getStoragePath(),
  718. mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict(), timeStamp);
  719. } else {
  720. mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(),
  721. mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict(), timeStamp);
  722. }
  723. Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
  724. while (listener.hasNext()) {
  725. mUploadOperation.addDatatransferProgressListener(listener.next());
  726. }
  727. if (mCancellationRequested.get()) {
  728. throw new OperationCancelledException();
  729. }
  730. if (result == null || result.isSuccess() && mUploadOperation != null) {
  731. result = mUploadOperation.execute(client);
  732. /// move local temporal file or original file to its corresponding
  733. // location in the Nextcloud local folder
  734. if (!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
  735. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  736. }
  737. }
  738. } catch (FileNotFoundException e) {
  739. Log_OC.d(TAG, mOriginalStoragePath + " not exists anymore");
  740. result = new RemoteOperationResult(ResultCode.LOCAL_FILE_NOT_FOUND);
  741. } catch (OverlappingFileLockException e) {
  742. Log_OC.d(TAG, "Overlapping file lock exception");
  743. result = new RemoteOperationResult(ResultCode.LOCK_FAILED);
  744. } catch (Exception e) {
  745. result = new RemoteOperationResult(e);
  746. } finally {
  747. mUploadStarted.set(false);
  748. if (fileLock != null) {
  749. try {
  750. fileLock.release();
  751. } catch (IOException e) {
  752. Log_OC.e(TAG, "Failed to unlock file with path " + mOriginalStoragePath);
  753. }
  754. }
  755. if (temporalFile != null && !originalFile.equals(temporalFile)) {
  756. temporalFile.delete();
  757. }
  758. if (result == null) {
  759. result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  760. }
  761. if (result.isSuccess()) {
  762. Log_OC.i(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " +
  763. result.getLogMessage());
  764. } else {
  765. if (result.getException() != null) {
  766. if (result.isCancelled()) {
  767. Log_OC.w(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath +
  768. ": " + result.getLogMessage());
  769. } else {
  770. Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath +
  771. ": " + result.getLogMessage(), result.getException());
  772. }
  773. } else {
  774. Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath +
  775. ": " + result.getLogMessage());
  776. }
  777. }
  778. }
  779. if (result.isSuccess()) {
  780. handleSuccessfulUpload(temporalFile, expectedFile, originalFile, client);
  781. } else if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  782. getStorageManager().saveConflict(mFile, mFile.getEtagInConflict());
  783. }
  784. return result;
  785. }
  786. private RemoteOperationResult copyFile(File originalFile, String expectedPath) throws OperationCancelledException,
  787. IOException {
  788. RemoteOperationResult result = null;
  789. if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY && !mOriginalStoragePath.equals(expectedPath)) {
  790. String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
  791. mFile.setStoragePath(temporalPath);
  792. File temporalFile = new File(temporalPath);
  793. result = copy(originalFile, temporalFile);
  794. }
  795. if (mCancellationRequested.get()) {
  796. throw new OperationCancelledException();
  797. }
  798. return result;
  799. }
  800. private void checkNameCollision(OwnCloudClient client) throws OperationCancelledException {
  801. /// automatic rename of file to upload in case of name collision in server
  802. Log_OC.d(TAG, "Checking name collision in server");
  803. if (!mForceOverwrite) {
  804. // TODO encrypted always false?
  805. String remotePath = getAvailableRemotePath(client, mRemotePath, null, false);
  806. mWasRenamed = !remotePath.equals(mRemotePath);
  807. if (mWasRenamed) {
  808. createNewOCFile(remotePath);
  809. Log_OC.d(TAG, "File renamed as " + remotePath);
  810. }
  811. mRemotePath = remotePath;
  812. mRenameUploadListener.onRenameUpload();
  813. }
  814. if (mCancellationRequested.get()) {
  815. throw new OperationCancelledException();
  816. }
  817. }
  818. private void handleSuccessfulUpload(File temporalFile, File expectedFile, File originalFile,
  819. OwnCloudClient client) {
  820. switch (mLocalBehaviour) {
  821. case FileUploader.LOCAL_BEHAVIOUR_FORGET:
  822. default:
  823. String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
  824. if (mOriginalStoragePath.equals(temporalPath)) {
  825. // delete local file is was pre-copied in temporary folder (see .ui.helpers.UriUploader)
  826. temporalFile = new File(temporalPath);
  827. temporalFile.delete();
  828. }
  829. mFile.setStoragePath("");
  830. saveUploadedFile(client);
  831. break;
  832. case FileUploader.LOCAL_BEHAVIOUR_DELETE:
  833. Log_OC.d(TAG, "Delete source file");
  834. originalFile.delete();
  835. getStorageManager().deleteFileInMediaScan(originalFile.getAbsolutePath());
  836. saveUploadedFile(client);
  837. break;
  838. case FileUploader.LOCAL_BEHAVIOUR_COPY:
  839. if (temporalFile != null) {
  840. try {
  841. move(temporalFile, expectedFile);
  842. } catch (IOException e) {
  843. e.printStackTrace();
  844. }
  845. }
  846. mFile.setStoragePath(expectedFile.getAbsolutePath());
  847. saveUploadedFile(client);
  848. FileDataStorageManager.triggerMediaScan(expectedFile.getAbsolutePath());
  849. break;
  850. case FileUploader.LOCAL_BEHAVIOUR_MOVE:
  851. String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);
  852. expectedFile = new File(expectedPath);
  853. try {
  854. move(originalFile, expectedFile);
  855. } catch (IOException e) {
  856. e.printStackTrace();
  857. }
  858. getStorageManager().deleteFileInMediaScan(originalFile.getAbsolutePath());
  859. mFile.setStoragePath(expectedFile.getAbsolutePath());
  860. saveUploadedFile(client);
  861. FileDataStorageManager.triggerMediaScan(expectedFile.getAbsolutePath());
  862. break;
  863. }
  864. }
  865. /**
  866. * Checks the existence of the folder where the current file will be uploaded both
  867. * in the remote server and in the local database.
  868. * <p/>
  869. * If the upload is set to enforce the creation of the folder, the method tries to
  870. * create it both remote and locally.
  871. *
  872. * @param pathToGrant Full remote path whose existence will be granted.
  873. * @return An {@link OCFile} instance corresponding to the folder where the file
  874. * will be uploaded.
  875. */
  876. private RemoteOperationResult grantFolderExistence(String pathToGrant, OwnCloudClient client) {
  877. RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, mContext, false);
  878. RemoteOperationResult result = operation.execute(client);
  879. if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND && mRemoteFolderToBeCreated) {
  880. SyncOperation syncOp = new CreateFolderOperation(pathToGrant, true);
  881. result = syncOp.execute(client, getStorageManager());
  882. }
  883. if (result.isSuccess()) {
  884. OCFile parentDir = getStorageManager().getFileByPath(pathToGrant);
  885. if (parentDir == null) {
  886. parentDir = createLocalFolder(pathToGrant);
  887. }
  888. if (parentDir != null) {
  889. result = new RemoteOperationResult(ResultCode.OK);
  890. } else {
  891. result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  892. }
  893. }
  894. return result;
  895. }
  896. private OCFile createLocalFolder(String remotePath) {
  897. String parentPath = new File(remotePath).getParent();
  898. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ?
  899. parentPath : parentPath + OCFile.PATH_SEPARATOR;
  900. OCFile parent = getStorageManager().getFileByPath(parentPath);
  901. if (parent == null) {
  902. parent = createLocalFolder(parentPath);
  903. }
  904. if (parent != null) {
  905. OCFile createdFolder = new OCFile(remotePath);
  906. createdFolder.setMimetype(MimeType.DIRECTORY);
  907. createdFolder.setParentId(parent.getFileId());
  908. getStorageManager().saveFile(createdFolder);
  909. return createdFolder;
  910. }
  911. return null;
  912. }
  913. /**
  914. * Create a new OCFile mFile with new remote path. This is required if forceOverwrite==false.
  915. * New file is stored as mFile, original as mOldFile.
  916. *
  917. * @param newRemotePath new remote path
  918. */
  919. private void createNewOCFile(String newRemotePath) {
  920. // a new OCFile instance must be created for a new remote path
  921. OCFile newFile = new OCFile(newRemotePath);
  922. newFile.setCreationTimestamp(mFile.getCreationTimestamp());
  923. newFile.setFileLength(mFile.getFileLength());
  924. newFile.setMimetype(mFile.getMimetype());
  925. newFile.setModificationTimestamp(mFile.getModificationTimestamp());
  926. newFile.setModificationTimestampAtLastSyncForData(
  927. mFile.getModificationTimestampAtLastSyncForData()
  928. );
  929. newFile.setEtag(mFile.getEtag());
  930. newFile.setAvailableOffline(mFile.isAvailableOffline());
  931. newFile.setLastSyncDateForProperties(mFile.getLastSyncDateForProperties());
  932. newFile.setLastSyncDateForData(mFile.getLastSyncDateForData());
  933. newFile.setStoragePath(mFile.getStoragePath());
  934. newFile.setParentId(mFile.getParentId());
  935. mOldFile = mFile;
  936. mFile = newFile;
  937. }
  938. /**
  939. * Checks if remotePath does not exist in the server and returns it, or adds
  940. * a suffix to it in order to avoid the server file is overwritten.
  941. *
  942. * @param client OwnCloud client
  943. * @param remotePath remote path of the file
  944. * @param metadata metadata of encrypted folder
  945. * @return new remote path
  946. */
  947. private String getAvailableRemotePath(OwnCloudClient client, String remotePath, DecryptedFolderMetadata metadata,
  948. boolean encrypted) {
  949. boolean check = existsFile(client, remotePath, metadata, encrypted);
  950. if (!check) {
  951. return remotePath;
  952. }
  953. int pos = remotePath.lastIndexOf('.');
  954. String suffix;
  955. String extension = "";
  956. String remotePathWithoutExtension = "";
  957. if (pos >= 0) {
  958. extension = remotePath.substring(pos + 1);
  959. remotePathWithoutExtension = remotePath.substring(0, pos);
  960. }
  961. int count = 2;
  962. do {
  963. suffix = " (" + count + ")";
  964. if (pos >= 0) {
  965. check = existsFile(client, remotePathWithoutExtension + suffix + "." + extension, metadata, encrypted);
  966. } else {
  967. check = existsFile(client, remotePath + suffix, metadata, encrypted);
  968. }
  969. count++;
  970. } while (check);
  971. if (pos >= 0) {
  972. return remotePathWithoutExtension + suffix + "." + extension;
  973. } else {
  974. return remotePath + suffix;
  975. }
  976. }
  977. private boolean existsFile(OwnCloudClient client, String remotePath, DecryptedFolderMetadata metadata,
  978. boolean encrypted) {
  979. if (encrypted) {
  980. String fileName = new File(remotePath).getName();
  981. for (DecryptedFolderMetadata.DecryptedFile file : metadata.files.values()) {
  982. if (file.encrypted.filename.equalsIgnoreCase(fileName)) {
  983. return true;
  984. }
  985. }
  986. return false;
  987. } else {
  988. ExistenceCheckRemoteOperation existsOperation = new ExistenceCheckRemoteOperation(remotePath, mContext,
  989. false);
  990. RemoteOperationResult result = existsOperation.execute(client);
  991. return result.isSuccess();
  992. }
  993. }
  994. /**
  995. * Allows to cancel the actual upload operation. If actual upload operating
  996. * is in progress it is cancelled, if upload preparation is being performed
  997. * upload will not take place.
  998. */
  999. public void cancel() {
  1000. if (mUploadOperation == null) {
  1001. if (mUploadStarted.get()) {
  1002. Log_OC.d(TAG, "Cancelling upload during upload preparations.");
  1003. mCancellationRequested.set(true);
  1004. } else {
  1005. Log_OC.e(TAG, "No upload in progress. This should not happen.");
  1006. }
  1007. } else {
  1008. Log_OC.d(TAG, "Cancelling upload during actual upload operation.");
  1009. mUploadOperation.cancel();
  1010. }
  1011. }
  1012. /**
  1013. * As soon as this method return true, upload can be cancel via cancel().
  1014. */
  1015. public boolean isUploadInProgress() {
  1016. return mUploadStarted.get();
  1017. }
  1018. /**
  1019. * TODO rewrite with homogeneous fail handling, remove dependency on {@link RemoteOperationResult},
  1020. * TODO use Exceptions instead
  1021. *
  1022. * @param sourceFile Source file to copy.
  1023. * @param targetFile Target location to copy the file.
  1024. * @return {@link RemoteOperationResult}
  1025. * @throws IOException exception if file cannot be accessed
  1026. */
  1027. private RemoteOperationResult copy(File sourceFile, File targetFile) throws IOException {
  1028. Log_OC.d(TAG, "Copying local file");
  1029. RemoteOperationResult result = null;
  1030. if (FileStorageUtils.getUsableSpace(mAccount.name) < sourceFile.length()) {
  1031. result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
  1032. return result; // error condition when the file should be copied
  1033. } else {
  1034. Log_OC.d(TAG, "Creating temporal folder");
  1035. File temporalParent = targetFile.getParentFile();
  1036. temporalParent.mkdirs();
  1037. if (!temporalParent.isDirectory()) {
  1038. throw new IOException(
  1039. "Unexpected error: parent directory could not be created");
  1040. }
  1041. Log_OC.d(TAG, "Creating temporal file");
  1042. targetFile.createNewFile();
  1043. if (!targetFile.isFile()) {
  1044. throw new IOException(
  1045. "Unexpected error: target file could not be created");
  1046. }
  1047. Log_OC.d(TAG, "Copying file contents");
  1048. InputStream in = null;
  1049. OutputStream out = null;
  1050. try {
  1051. if (!mOriginalStoragePath.equals(targetFile.getAbsolutePath())) {
  1052. // In case document provider schema as 'content://'
  1053. if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
  1054. Uri uri = Uri.parse(mOriginalStoragePath);
  1055. in = mContext.getContentResolver().openInputStream(uri);
  1056. } else {
  1057. in = new FileInputStream(sourceFile);
  1058. }
  1059. out = new FileOutputStream(targetFile);
  1060. int nRead;
  1061. byte[] buf = new byte[4096];
  1062. while (!mCancellationRequested.get() &&
  1063. (nRead = in.read(buf)) > -1) {
  1064. out.write(buf, 0, nRead);
  1065. }
  1066. out.flush();
  1067. } // else: weird but possible situation, nothing to copy
  1068. if (mCancellationRequested.get()) {
  1069. result = new RemoteOperationResult(new OperationCancelledException());
  1070. return result;
  1071. }
  1072. } catch (Exception e) {
  1073. result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
  1074. return result;
  1075. } finally {
  1076. try {
  1077. if (in != null) {
  1078. in.close();
  1079. }
  1080. } catch (Exception e) {
  1081. Log_OC.d(TAG, "Weird exception while closing input stream for " +
  1082. mOriginalStoragePath + " (ignoring)", e);
  1083. }
  1084. try {
  1085. if (out != null) {
  1086. out.close();
  1087. }
  1088. } catch (Exception e) {
  1089. Log_OC.d(TAG, "Weird exception while closing output stream for " +
  1090. targetFile.getAbsolutePath() + " (ignoring)", e);
  1091. }
  1092. }
  1093. }
  1094. return result;
  1095. }
  1096. /**
  1097. * TODO rewrite with homogeneous fail handling, remove dependency on {@link RemoteOperationResult},
  1098. * TODO use Exceptions instead
  1099. * <p>
  1100. * TODO refactor both this and 'copy' in a single method
  1101. *
  1102. * @param sourceFile Source file to move.
  1103. * @param targetFile Target location to move the file.
  1104. * @return {@link RemoteOperationResult} result from remote operation
  1105. * @throws IOException exception if file cannot be read/wrote
  1106. */
  1107. private void move(File sourceFile, File targetFile) throws IOException {
  1108. if (!targetFile.equals(sourceFile)) {
  1109. File expectedFolder = targetFile.getParentFile();
  1110. expectedFolder.mkdirs();
  1111. if (expectedFolder.isDirectory()) {
  1112. if (!sourceFile.renameTo(targetFile)) {
  1113. // try to copy and then delete
  1114. targetFile.createNewFile();
  1115. FileChannel inChannel = new FileInputStream(sourceFile).getChannel();
  1116. FileChannel outChannel = new FileOutputStream(targetFile).getChannel();
  1117. try {
  1118. inChannel.transferTo(0, inChannel.size(), outChannel);
  1119. sourceFile.delete();
  1120. } catch (Exception e) {
  1121. mFile.setStoragePath(""); // forget the local file
  1122. // by now, treat this as a success; the file was uploaded
  1123. // the best option could be show a warning message
  1124. } finally {
  1125. if (inChannel != null) {
  1126. inChannel.close();
  1127. }
  1128. if (outChannel != null) {
  1129. outChannel.close();
  1130. }
  1131. }
  1132. }
  1133. } else {
  1134. mFile.setStoragePath("");
  1135. }
  1136. }
  1137. }
  1138. /**
  1139. * Saves a OC File after a successful upload.
  1140. * <p>
  1141. * A PROPFIND is necessary to keep the props in the local database
  1142. * synchronized with the server, specially the modification time and Etag
  1143. * (where available)
  1144. */
  1145. private void saveUploadedFile(OwnCloudClient client) {
  1146. OCFile file = mFile;
  1147. if (file.fileExists()) {
  1148. file = getStorageManager().getFileById(file.getFileId());
  1149. }
  1150. long syncDate = System.currentTimeMillis();
  1151. file.setLastSyncDateForData(syncDate);
  1152. // new PROPFIND to keep data consistent with server
  1153. // in theory, should return the same we already have
  1154. // TODO from the appropriate OC server version, get data from last PUT response headers, instead
  1155. // TODO of a new PROPFIND; the latter may fail, specially for chunked uploads
  1156. ReadRemoteFileOperation operation = new ReadRemoteFileOperation(getRemotePath());
  1157. RemoteOperationResult result = operation.execute(client);
  1158. if (result.isSuccess()) {
  1159. updateOCFile(file, (RemoteFile) result.getData().get(0));
  1160. file.setLastSyncDateForProperties(syncDate);
  1161. } else {
  1162. Log_OC.e(TAG, "Error reading properties of file after successful upload; this is gonna hurt...");
  1163. }
  1164. if (mWasRenamed) {
  1165. OCFile oldFile = getStorageManager().getFileByPath(mOldFile.getRemotePath());
  1166. if (oldFile != null) {
  1167. oldFile.setStoragePath(null);
  1168. getStorageManager().saveFile(oldFile);
  1169. getStorageManager().saveConflict(oldFile, null);
  1170. }
  1171. // else: it was just an automatic renaming due to a name
  1172. // coincidence; nothing else is needed, the storagePath is right
  1173. // in the instance returned by mCurrentUpload.getFile()
  1174. }
  1175. file.setNeedsUpdateThumbnail(true);
  1176. getStorageManager().saveFile(file);
  1177. getStorageManager().saveConflict(file, null);
  1178. FileDataStorageManager.triggerMediaScan(file.getStoragePath());
  1179. // generate new Thumbnail
  1180. final ThumbnailsCacheManager.ThumbnailGenerationTask task =
  1181. new ThumbnailsCacheManager.ThumbnailGenerationTask(getStorageManager(), mAccount);
  1182. task.execute(new ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file, file.getRemoteId()));
  1183. }
  1184. private void updateOCFile(OCFile file, RemoteFile remoteFile) {
  1185. file.setCreationTimestamp(remoteFile.getCreationTimestamp());
  1186. file.setFileLength(remoteFile.getLength());
  1187. file.setMimetype(remoteFile.getMimeType());
  1188. file.setModificationTimestamp(remoteFile.getModifiedTimestamp());
  1189. file.setModificationTimestampAtLastSyncForData(remoteFile.getModifiedTimestamp());
  1190. file.setEtag(remoteFile.getEtag());
  1191. file.setRemoteId(remoteFile.getRemoteId());
  1192. }
  1193. public interface OnRenameListener {
  1194. void onRenameUpload();
  1195. }
  1196. }