FileUploader.java 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012 Bartek Przybylski
  3. * Copyright (C) 2012-2013 ownCloud Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2,
  7. * as published by the Free Software Foundation.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. */
  18. package com.owncloud.android.files.services;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.util.AbstractList;
  22. import java.util.HashMap;
  23. import java.util.Iterator;
  24. import java.util.Map;
  25. import java.util.Vector;
  26. import java.util.concurrent.ConcurrentHashMap;
  27. import java.util.concurrent.ConcurrentMap;
  28. import org.apache.http.HttpStatus;
  29. import org.apache.jackrabbit.webdav.DavConstants;
  30. import org.apache.jackrabbit.webdav.MultiStatus;
  31. import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
  32. import com.owncloud.android.authentication.AccountAuthenticator;
  33. import com.owncloud.android.authentication.AuthenticatorActivity;
  34. import com.owncloud.android.datamodel.FileDataStorageManager;
  35. import com.owncloud.android.datamodel.OCFile;
  36. import com.owncloud.android.operations.ChunkedUploadFileOperation;
  37. import com.owncloud.android.operations.CreateFolderOperation;
  38. import com.owncloud.android.operations.ExistenceCheckOperation;
  39. import com.owncloud.android.operations.RemoteOperation;
  40. import com.owncloud.android.operations.RemoteOperationResult;
  41. import com.owncloud.android.operations.UploadFileOperation;
  42. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  43. import com.owncloud.android.utils.OwnCloudVersion;
  44. import com.owncloud.android.network.OwnCloudClientUtils;
  45. import com.owncloud.android.network.webdav.OnDatatransferProgressListener;
  46. import com.owncloud.android.network.webdav.WebdavClient;
  47. import com.owncloud.android.network.webdav.WebdavEntry;
  48. import com.owncloud.android.network.webdav.WebdavUtils;
  49. import android.accounts.Account;
  50. import android.accounts.AccountManager;
  51. import android.accounts.AccountsException;
  52. import android.app.Notification;
  53. import android.app.NotificationManager;
  54. import android.app.PendingIntent;
  55. import android.app.Service;
  56. import android.content.Intent;
  57. import android.os.Binder;
  58. import android.os.Handler;
  59. import android.os.HandlerThread;
  60. import android.os.IBinder;
  61. import android.os.Looper;
  62. import android.os.Message;
  63. import android.os.Process;
  64. import android.webkit.MimeTypeMap;
  65. import android.widget.RemoteViews;
  66. import com.owncloud.android.Log_OC;
  67. import com.owncloud.android.MainApp;
  68. import com.owncloud.android.R;
  69. import com.owncloud.android.db.DbHandler;
  70. import com.owncloud.android.ui.activity.FailedUploadActivity;
  71. import com.owncloud.android.ui.activity.FileActivity;
  72. import com.owncloud.android.ui.activity.FileDisplayActivity;
  73. import com.owncloud.android.ui.activity.InstantUploadActivity;
  74. import com.owncloud.android.ui.preview.PreviewImageActivity;
  75. import com.owncloud.android.ui.preview.PreviewImageFragment;
  76. public class FileUploader extends Service implements OnDatatransferProgressListener {
  77. private static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
  78. public static final String EXTRA_UPLOAD_RESULT = "RESULT";
  79. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  80. public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
  81. public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
  82. public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
  83. public static final String KEY_FILE = "FILE";
  84. public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
  85. public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
  86. public static final String KEY_MIME_TYPE = "MIME_TYPE";
  87. public static final String KEY_ACCOUNT = "ACCOUNT";
  88. public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
  89. public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
  90. public static final String KEY_INSTANT_UPLOAD = "INSTANT_UPLOAD";
  91. public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
  92. public static final int LOCAL_BEHAVIOUR_COPY = 0;
  93. public static final int LOCAL_BEHAVIOUR_MOVE = 1;
  94. public static final int LOCAL_BEHAVIOUR_FORGET = 2;
  95. public static final int UPLOAD_SINGLE_FILE = 0;
  96. public static final int UPLOAD_MULTIPLE_FILES = 1;
  97. private static final String TAG = FileUploader.class.getSimpleName();
  98. private Looper mServiceLooper;
  99. private ServiceHandler mServiceHandler;
  100. private IBinder mBinder;
  101. private WebdavClient mUploadClient = null;
  102. private Account mLastAccount = null;
  103. private FileDataStorageManager mStorageManager;
  104. private ConcurrentMap<String, UploadFileOperation> mPendingUploads = new ConcurrentHashMap<String, UploadFileOperation>();
  105. private UploadFileOperation mCurrentUpload = null;
  106. private NotificationManager mNotificationManager;
  107. private Notification mNotification;
  108. private int mLastPercent;
  109. private RemoteViews mDefaultNotificationContentView;
  110. public static String getUploadFinishMessage() {
  111. return FileUploader.class.getName().toString() + UPLOAD_FINISH_MESSAGE;
  112. }
  113. /**
  114. * Builds a key for mPendingUploads from the account and file to upload
  115. *
  116. * @param account Account where the file to upload is stored
  117. * @param file File to upload
  118. */
  119. private String buildRemoteName(Account account, OCFile file) {
  120. return account.name + file.getRemotePath();
  121. }
  122. private String buildRemoteName(Account account, String remotePath) {
  123. return account.name + remotePath;
  124. }
  125. /**
  126. * Checks if an ownCloud server version should support chunked uploads.
  127. *
  128. * @param version OwnCloud version instance corresponding to an ownCloud
  129. * server.
  130. * @return 'True' if the ownCloud server with version supports chunked
  131. * uploads.
  132. */
  133. private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
  134. return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
  135. }
  136. /**
  137. * Service initialization
  138. */
  139. @Override
  140. public void onCreate() {
  141. super.onCreate();
  142. Log_OC.i(TAG, "mPendingUploads size:" + mPendingUploads.size());
  143. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  144. HandlerThread thread = new HandlerThread("FileUploaderThread", Process.THREAD_PRIORITY_BACKGROUND);
  145. thread.start();
  146. mServiceLooper = thread.getLooper();
  147. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  148. mBinder = new FileUploaderBinder();
  149. }
  150. /**
  151. * Entry point to add one or several files to the queue of uploads.
  152. *
  153. * New uploads are added calling to startService(), resulting in a call to
  154. * this method. This ensures the service will keep on working although the
  155. * caller activity goes away.
  156. */
  157. @Override
  158. public int onStartCommand(Intent intent, int flags, int startId) {
  159. if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE)
  160. || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
  161. Log_OC.e(TAG, "Not enough information provided in intent");
  162. return Service.START_NOT_STICKY;
  163. }
  164. int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
  165. if (uploadType == -1) {
  166. Log_OC.e(TAG, "Incorrect upload type provided");
  167. return Service.START_NOT_STICKY;
  168. }
  169. Account account = intent.getParcelableExtra(KEY_ACCOUNT);
  170. String[] localPaths = null, remotePaths = null, mimeTypes = null;
  171. OCFile[] files = null;
  172. if (uploadType == UPLOAD_SINGLE_FILE) {
  173. if (intent.hasExtra(KEY_FILE)) {
  174. files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) };
  175. } else {
  176. localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
  177. remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
  178. mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
  179. }
  180. } else { // mUploadType == UPLOAD_MULTIPLE_FILES
  181. if (intent.hasExtra(KEY_FILE)) {
  182. files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO
  183. // will
  184. // this
  185. // casting
  186. // work
  187. // fine?
  188. } else {
  189. localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
  190. remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
  191. mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
  192. }
  193. }
  194. FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
  195. boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
  196. boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
  197. int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_COPY);
  198. if (intent.hasExtra(KEY_FILE) && files == null) {
  199. Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
  200. return Service.START_NOT_STICKY;
  201. } else if (!intent.hasExtra(KEY_FILE)) {
  202. if (localPaths == null) {
  203. Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent");
  204. return Service.START_NOT_STICKY;
  205. }
  206. if (remotePaths == null) {
  207. Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent");
  208. return Service.START_NOT_STICKY;
  209. }
  210. if (localPaths.length != remotePaths.length) {
  211. Log_OC.e(TAG, "Different number of remote paths and local paths!");
  212. return Service.START_NOT_STICKY;
  213. }
  214. files = new OCFile[localPaths.length];
  215. for (int i = 0; i < localPaths.length; i++) {
  216. files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes != null) ? mimeTypes[i]
  217. : (String) null), storageManager);
  218. if (files[i] == null) {
  219. // TODO @andomaex add failure Notiification
  220. return Service.START_NOT_STICKY;
  221. }
  222. }
  223. }
  224. OwnCloudVersion ocv = new OwnCloudVersion(AccountManager.get(this).getUserData(account,
  225. AccountAuthenticator.KEY_OC_VERSION));
  226. boolean chunked = FileUploader.chunkedUploadIsSupported(ocv);
  227. AbstractList<String> requestedUploads = new Vector<String>();
  228. String uploadKey = null;
  229. UploadFileOperation newUpload = null;
  230. try {
  231. for (int i = 0; i < files.length; i++) {
  232. uploadKey = buildRemoteName(account, files[i].getRemotePath());
  233. if (chunked) {
  234. newUpload = new ChunkedUploadFileOperation(account, files[i], isInstant, forceOverwrite,
  235. localAction);
  236. } else {
  237. newUpload = new UploadFileOperation(account, files[i], isInstant, forceOverwrite, localAction);
  238. }
  239. if (isInstant) {
  240. newUpload.setRemoteFolderToBeCreated();
  241. }
  242. mPendingUploads.putIfAbsent(uploadKey, newUpload); // Grants that the file only upload once time
  243. newUpload.addDatatransferProgressListener(this);
  244. newUpload.addDatatransferProgressListener((FileUploaderBinder)mBinder);
  245. requestedUploads.add(uploadKey);
  246. }
  247. } catch (IllegalArgumentException e) {
  248. Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  249. return START_NOT_STICKY;
  250. } catch (IllegalStateException e) {
  251. Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
  252. return START_NOT_STICKY;
  253. } catch (Exception e) {
  254. Log_OC.e(TAG, "Unexpected exception while processing upload intent", e);
  255. return START_NOT_STICKY;
  256. }
  257. if (requestedUploads.size() > 0) {
  258. Message msg = mServiceHandler.obtainMessage();
  259. msg.arg1 = startId;
  260. msg.obj = requestedUploads;
  261. mServiceHandler.sendMessage(msg);
  262. }
  263. Log_OC.i(TAG, "mPendingUploads size:" + mPendingUploads.size());
  264. return Service.START_NOT_STICKY;
  265. }
  266. /**
  267. * Provides a binder object that clients can use to perform operations on
  268. * the queue of uploads, excepting the addition of new files.
  269. *
  270. * Implemented to perform cancellation, pause and resume of existing
  271. * uploads.
  272. */
  273. @Override
  274. public IBinder onBind(Intent arg0) {
  275. return mBinder;
  276. }
  277. /**
  278. * Called when ALL the bound clients were onbound.
  279. */
  280. @Override
  281. public boolean onUnbind(Intent intent) {
  282. ((FileUploaderBinder)mBinder).clearListeners();
  283. return false; // not accepting rebinding (default behaviour)
  284. }
  285. /**
  286. * Binder to let client components to perform operations on the queue of
  287. * uploads.
  288. *
  289. * It provides by itself the available operations.
  290. */
  291. public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
  292. /**
  293. * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
  294. */
  295. private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
  296. /**
  297. * Cancels a pending or current upload of a remote file.
  298. *
  299. * @param account Owncloud account where the remote file will be stored.
  300. * @param file A file in the queue of pending uploads
  301. */
  302. public void cancel(Account account, OCFile file) {
  303. UploadFileOperation upload = null;
  304. synchronized (mPendingUploads) {
  305. upload = mPendingUploads.remove(buildRemoteName(account, file));
  306. }
  307. if (upload != null) {
  308. upload.cancel();
  309. }
  310. }
  311. public void clearListeners() {
  312. mBoundListeners.clear();
  313. }
  314. /**
  315. * Returns True when the file described by 'file' is being uploaded to
  316. * the ownCloud account 'account' or waiting for it
  317. *
  318. * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
  319. *
  320. * @param account Owncloud account where the remote file will be stored.
  321. * @param file A file that could be in the queue of pending uploads
  322. */
  323. public boolean isUploading(Account account, OCFile file) {
  324. if (account == null || file == null)
  325. return false;
  326. String targetKey = buildRemoteName(account, file);
  327. synchronized (mPendingUploads) {
  328. if (file.isFolder()) {
  329. // this can be slow if there are many uploads :(
  330. Iterator<String> it = mPendingUploads.keySet().iterator();
  331. boolean found = false;
  332. while (it.hasNext() && !found) {
  333. found = it.next().startsWith(targetKey);
  334. }
  335. return found;
  336. } else {
  337. return (mPendingUploads.containsKey(targetKey));
  338. }
  339. }
  340. }
  341. /**
  342. * Adds a listener interested in the progress of the upload for a concrete file.
  343. *
  344. * @param listener Object to notify about progress of transfer.
  345. * @param account ownCloud account holding the file of interest.
  346. * @param file {@link OCfile} of interest for listener.
  347. */
  348. public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
  349. if (account == null || file == null || listener == null) return;
  350. String targetKey = buildRemoteName(account, file);
  351. mBoundListeners.put(targetKey, listener);
  352. }
  353. /**
  354. * Removes a listener interested in the progress of the upload for a concrete file.
  355. *
  356. * @param listener Object to notify about progress of transfer.
  357. * @param account ownCloud account holding the file of interest.
  358. * @param file {@link OCfile} of interest for listener.
  359. */
  360. public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
  361. if (account == null || file == null || listener == null) return;
  362. String targetKey = buildRemoteName(account, file);
  363. if (mBoundListeners.get(targetKey) == listener) {
  364. mBoundListeners.remove(targetKey);
  365. }
  366. }
  367. @Override
  368. public void onTransferProgress(long progressRate) {
  369. // old way, should not be in use any more
  370. }
  371. @Override
  372. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
  373. String fileName) {
  374. String key = buildRemoteName(mCurrentUpload.getAccount(), mCurrentUpload.getFile());
  375. OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
  376. if (boundListener != null) {
  377. boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
  378. }
  379. }
  380. }
  381. /**
  382. * Upload worker. Performs the pending uploads in the order they were
  383. * requested.
  384. *
  385. * Created with the Looper of a new thread, started in
  386. * {@link FileUploader#onCreate()}.
  387. */
  388. private static class ServiceHandler extends Handler {
  389. // don't make it a final class, and don't remove the static ; lint will
  390. // warn about a possible memory leak
  391. FileUploader mService;
  392. public ServiceHandler(Looper looper, FileUploader service) {
  393. super(looper);
  394. if (service == null)
  395. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  396. mService = service;
  397. }
  398. @Override
  399. public void handleMessage(Message msg) {
  400. @SuppressWarnings("unchecked")
  401. AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
  402. if (msg.obj != null) {
  403. Iterator<String> it = requestedUploads.iterator();
  404. while (it.hasNext()) {
  405. mService.uploadFile(it.next());
  406. }
  407. }
  408. mService.stopSelf(msg.arg1);
  409. }
  410. }
  411. /**
  412. * Core upload method: sends the file(s) to upload
  413. *
  414. * @param uploadKey Key to access the upload to perform, contained in
  415. * mPendingUploads
  416. */
  417. public void uploadFile(String uploadKey) {
  418. synchronized (mPendingUploads) {
  419. mCurrentUpload = mPendingUploads.get(uploadKey);
  420. }
  421. if (mCurrentUpload != null) {
  422. notifyUploadStart(mCurrentUpload);
  423. RemoteOperationResult uploadResult = null, grantResult = null;
  424. try {
  425. /// prepare client object to send requests to the ownCloud server
  426. if (mUploadClient == null || !mLastAccount.equals(mCurrentUpload.getAccount())) {
  427. mLastAccount = mCurrentUpload.getAccount();
  428. mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
  429. mUploadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
  430. }
  431. /// check the existence of the parent folder for the file to upload
  432. String remoteParentPath = new File(mCurrentUpload.getRemotePath()).getParent();
  433. remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ? remoteParentPath : remoteParentPath + OCFile.PATH_SEPARATOR;
  434. grantResult = grantFolderExistence(remoteParentPath);
  435. /// perform the upload
  436. if (grantResult.isSuccess()) {
  437. OCFile parent = mStorageManager.getFileByPath(remoteParentPath);
  438. mCurrentUpload.getFile().setParentId(parent.getFileId());
  439. uploadResult = mCurrentUpload.execute(mUploadClient);
  440. if (uploadResult.isSuccess()) {
  441. saveUploadedFile();
  442. }
  443. } else {
  444. uploadResult = grantResult;
  445. }
  446. } catch (AccountsException e) {
  447. Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  448. uploadResult = new RemoteOperationResult(e);
  449. } catch (IOException e) {
  450. Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  451. uploadResult = new RemoteOperationResult(e);
  452. } finally {
  453. synchronized (mPendingUploads) {
  454. mPendingUploads.remove(uploadKey);
  455. Log_OC.i(TAG, "Remove CurrentUploadItem from pending upload Item Map.");
  456. }
  457. if (uploadResult.isException()) {
  458. // enforce the creation of a new client object for next uploads; this grant that a new socket will
  459. // be created in the future if the current exception is due to an abrupt lose of network connection
  460. mUploadClient = null;
  461. }
  462. }
  463. /// notify result
  464. notifyUploadResult(uploadResult, mCurrentUpload);
  465. sendFinalBroadcast(mCurrentUpload, uploadResult);
  466. }
  467. }
  468. /**
  469. * Checks the existence of the folder where the current file will be uploaded both in the remote server
  470. * and in the local database.
  471. *
  472. * If the upload is set to enforce the creation of the folder, the method tries to create it both remote
  473. * and locally.
  474. *
  475. * @param pathToGrant Full remote path whose existence will be granted.
  476. * @return An {@link OCFile} instance corresponding to the folder where the file will be uploaded.
  477. */
  478. private RemoteOperationResult grantFolderExistence(String pathToGrant) {
  479. RemoteOperation operation = new ExistenceCheckOperation(pathToGrant, this, false);
  480. RemoteOperationResult result = operation.execute(mUploadClient);
  481. if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND && mCurrentUpload.isRemoteFolderToBeCreated()) {
  482. operation = new CreateFolderOperation( pathToGrant,
  483. true,
  484. mStorageManager );
  485. result = operation.execute(mUploadClient);
  486. }
  487. if (result.isSuccess()) {
  488. OCFile parentDir = mStorageManager.getFileByPath(pathToGrant);
  489. if (parentDir == null) {
  490. parentDir = createLocalFolder(pathToGrant);
  491. }
  492. if (parentDir != null) {
  493. result = new RemoteOperationResult(ResultCode.OK);
  494. } else {
  495. result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  496. }
  497. }
  498. return result;
  499. }
  500. private OCFile createLocalFolder(String remotePath) {
  501. String parentPath = new File(remotePath).getParent();
  502. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
  503. OCFile parent = mStorageManager.getFileByPath(parentPath);
  504. if (parent == null) {
  505. parent = createLocalFolder(parentPath);
  506. }
  507. if (parent != null) {
  508. OCFile createdFolder = new OCFile(remotePath);
  509. createdFolder.setMimetype("DIR");
  510. createdFolder.setParentId(parent.getFileId());
  511. mStorageManager.saveFile(createdFolder);
  512. return createdFolder;
  513. }
  514. return null;
  515. }
  516. /**
  517. * Saves a OC File after a successful upload.
  518. *
  519. * A PROPFIND is necessary to keep the props in the local database
  520. * synchronized with the server, specially the modification time and Etag
  521. * (where available)
  522. *
  523. * TODO refactor this ugly thing
  524. */
  525. private void saveUploadedFile() {
  526. OCFile file = mCurrentUpload.getFile();
  527. long syncDate = System.currentTimeMillis();
  528. file.setLastSyncDateForData(syncDate);
  529. // / new PROPFIND to keep data consistent with server in theory, should
  530. // return the same we already have
  531. PropFindMethod propfind = null;
  532. RemoteOperationResult result = null;
  533. try {
  534. propfind = new PropFindMethod(mUploadClient.getBaseUri() + WebdavUtils.encodePath(mCurrentUpload.getRemotePath()),
  535. DavConstants.PROPFIND_ALL_PROP,
  536. DavConstants.DEPTH_0);
  537. int status = mUploadClient.executeMethod(propfind);
  538. boolean isMultiStatus = (status == HttpStatus.SC_MULTI_STATUS);
  539. if (isMultiStatus) {
  540. MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
  541. WebdavEntry we = new WebdavEntry(resp.getResponses()[0], mUploadClient.getBaseUri().getPath());
  542. updateOCFile(file, we);
  543. file.setLastSyncDateForProperties(syncDate);
  544. } else {
  545. mUploadClient.exhaustResponse(propfind.getResponseBodyAsStream());
  546. }
  547. result = new RemoteOperationResult(isMultiStatus, status, propfind.getResponseHeaders());
  548. Log_OC.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": "
  549. + result.getLogMessage());
  550. } catch (Exception e) {
  551. result = new RemoteOperationResult(e);
  552. Log_OC.e(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": "
  553. + result.getLogMessage(), e);
  554. } finally {
  555. if (propfind != null)
  556. propfind.releaseConnection();
  557. }
  558. // / maybe this would be better as part of UploadFileOperation... or
  559. // maybe all this method
  560. if (mCurrentUpload.wasRenamed()) {
  561. OCFile oldFile = mCurrentUpload.getOldFile();
  562. if (oldFile.fileExists()) {
  563. oldFile.setStoragePath(null);
  564. mStorageManager.saveFile(oldFile);
  565. } // else: it was just an automatic renaming due to a name
  566. // coincidence; nothing else is needed, the storagePath is right
  567. // in the instance returned by mCurrentUpload.getFile()
  568. }
  569. mStorageManager.saveFile(file);
  570. }
  571. private void updateOCFile(OCFile file, WebdavEntry we) {
  572. file.setCreationTimestamp(we.createTimestamp());
  573. file.setFileLength(we.contentLength());
  574. file.setMimetype(we.contentType());
  575. file.setModificationTimestamp(we.modifiedTimestamp());
  576. file.setModificationTimestampAtLastSyncForData(we.modifiedTimestamp());
  577. // file.setEtag(mCurrentUpload.getEtag()); // TODO Etag, where available
  578. }
  579. private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType,
  580. FileDataStorageManager storageManager) {
  581. OCFile newFile = new OCFile(remotePath);
  582. newFile.setStoragePath(localPath);
  583. newFile.setLastSyncDateForProperties(0);
  584. newFile.setLastSyncDateForData(0);
  585. // size
  586. if (localPath != null && localPath.length() > 0) {
  587. File localFile = new File(localPath);
  588. newFile.setFileLength(localFile.length());
  589. newFile.setLastSyncDateForData(localFile.lastModified());
  590. } // don't worry about not assigning size, the problems with localPath
  591. // are checked when the UploadFileOperation instance is created
  592. // MIME type
  593. if (mimeType == null || mimeType.length() <= 0) {
  594. try {
  595. mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
  596. remotePath.substring(remotePath.lastIndexOf('.') + 1));
  597. } catch (IndexOutOfBoundsException e) {
  598. Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
  599. }
  600. }
  601. if (mimeType == null) {
  602. mimeType = "application/octet-stream";
  603. }
  604. newFile.setMimetype(mimeType);
  605. return newFile;
  606. }
  607. /**
  608. * Creates a status notification to show the upload progress
  609. *
  610. * @param upload Upload operation starting.
  611. */
  612. @SuppressWarnings("deprecation")
  613. private void notifyUploadStart(UploadFileOperation upload) {
  614. // / create status notification with a progress bar
  615. mLastPercent = 0;
  616. mNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_in_progress_ticker),
  617. System.currentTimeMillis());
  618. mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
  619. mDefaultNotificationContentView = mNotification.contentView;
  620. mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(),
  621. R.layout.progressbar_layout);
  622. mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
  623. mNotification.contentView.setTextViewText(R.id.status_text,
  624. String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
  625. mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
  626. /// includes a pending intent in the notification showing the details view of the file
  627. Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
  628. showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
  629. showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  630. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  631. mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
  632. (int) System.currentTimeMillis(), showDetailsIntent, 0);
  633. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
  634. }
  635. /**
  636. * Callback method to update the progress bar in the status notification
  637. */
  638. @Override
  639. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
  640. int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
  641. if (percent != mLastPercent) {
  642. mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
  643. String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
  644. mNotification.contentView.setTextViewText(R.id.status_text, text);
  645. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
  646. }
  647. mLastPercent = percent;
  648. }
  649. /**
  650. * Callback method to update the progress bar in the status notification
  651. * (old version)
  652. */
  653. @Override
  654. public void onTransferProgress(long progressRate) {
  655. // NOTHING TO DO HERE ANYMORE
  656. }
  657. /**
  658. * Updates the status notification with the result of an upload operation.
  659. *
  660. * @param uploadResult Result of the upload operation.
  661. * @param upload Finished upload operation
  662. */
  663. private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
  664. Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
  665. if (uploadResult.isCancelled()) {
  666. // / cancelled operation -> silent removal of progress notification
  667. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  668. } else if (uploadResult.isSuccess()) {
  669. // / success -> silent update of progress notification to success
  670. // message
  671. mNotification.flags ^= Notification.FLAG_ONGOING_EVENT; // remove
  672. // the
  673. // ongoing
  674. // flag
  675. mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
  676. mNotification.contentView = mDefaultNotificationContentView;
  677. /// includes a pending intent in the notification showing the details view of the file
  678. Intent showDetailsIntent = null;
  679. if (PreviewImageFragment.canBePreviewed(upload.getFile())) {
  680. showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  681. } else {
  682. showDetailsIntent = new Intent(this, FileDisplayActivity.class);
  683. }
  684. showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
  685. showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  686. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  687. mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
  688. (int) System.currentTimeMillis(), showDetailsIntent, 0);
  689. mNotification.setLatestEventInfo(getApplicationContext(),
  690. getString(R.string.uploader_upload_succeeded_ticker),
  691. String.format(getString(R.string.uploader_upload_succeeded_content_single), upload.getFileName()),
  692. mNotification.contentIntent);
  693. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification); // NOT
  694. // AN
  695. DbHandler db = new DbHandler(this.getBaseContext());
  696. db.removeIUPendingFile(mCurrentUpload.getOriginalStoragePath());
  697. db.close();
  698. } else {
  699. // / fail -> explicit failure notification
  700. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  701. Notification finalNotification = new Notification(R.drawable.icon,
  702. getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
  703. finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
  704. String content = null;
  705. boolean needsToUpdateCredentials = (uploadResult.getCode() == ResultCode.UNAUTHORIZED ||
  706. //(uploadResult.isTemporalRedirection() && uploadResult.isIdPRedirection() &&
  707. (uploadResult.isIdPRedirection() &&
  708. MainApp.getAuthTokenTypeSamlSessionCookie().equals(mUploadClient.getAuthTokenType())));
  709. if (needsToUpdateCredentials) {
  710. // let the user update credentials with one click
  711. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  712. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount());
  713. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
  714. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
  715. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  716. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  717. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  718. finalNotification.contentIntent = PendingIntent.getActivity(this, (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT);
  719. content = String.format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
  720. finalNotification.setLatestEventInfo(getApplicationContext(),
  721. getString(R.string.uploader_upload_failed_ticker), content, finalNotification.contentIntent);
  722. mUploadClient = null; // grant that future retries on the same account will get the fresh credentials
  723. } else {
  724. // TODO put something smart in the contentIntent below
  725. // finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
  726. //}
  727. if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL
  728. || uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
  729. // TODO we need a class to provide error messages for the users
  730. // from a RemoteOperationResult and a RemoteOperation
  731. content = String.format(getString(R.string.error__upload__local_file_not_copied), upload.getFileName(),
  732. getString(R.string.app_name));
  733. } else if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
  734. content = getString(R.string.failed_upload_quota_exceeded_text);
  735. } else {
  736. content = String
  737. .format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
  738. }
  739. // we add only for instant-uploads the InstantUploadActivity and the
  740. // db entry
  741. Intent detailUploadIntent = null;
  742. if (upload.isInstant() && InstantUploadActivity.IS_ENABLED) {
  743. detailUploadIntent = new Intent(this, InstantUploadActivity.class);
  744. detailUploadIntent.putExtra(FileUploader.KEY_ACCOUNT, upload.getAccount());
  745. } else {
  746. detailUploadIntent = new Intent(this, FailedUploadActivity.class);
  747. detailUploadIntent.putExtra(FailedUploadActivity.MESSAGE, content);
  748. }
  749. finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
  750. (int) System.currentTimeMillis(), detailUploadIntent, PendingIntent.FLAG_UPDATE_CURRENT
  751. | PendingIntent.FLAG_ONE_SHOT);
  752. if (upload.isInstant()) {
  753. DbHandler db = null;
  754. try {
  755. db = new DbHandler(this.getBaseContext());
  756. String message = uploadResult.getLogMessage() + " errorCode: " + uploadResult.getCode();
  757. Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
  758. if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
  759. message = getString(R.string.failed_upload_quota_exceeded_text);
  760. if (db.updateFileState(upload.getOriginalStoragePath(), DbHandler.UPLOAD_STATUS_UPLOAD_FAILED,
  761. message) == 0) {
  762. db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name, message);
  763. }
  764. }
  765. } finally {
  766. if (db != null) {
  767. db.close();
  768. }
  769. }
  770. }
  771. }
  772. finalNotification.setLatestEventInfo(getApplicationContext(),
  773. getString(R.string.uploader_upload_failed_ticker), content, finalNotification.contentIntent);
  774. mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
  775. }
  776. }
  777. /**
  778. * Sends a broadcast in order to the interested activities can update their
  779. * view
  780. *
  781. * @param upload Finished upload operation
  782. * @param uploadResult Result of the upload operation
  783. */
  784. private void sendFinalBroadcast(UploadFileOperation upload, RemoteOperationResult uploadResult) {
  785. Intent end = new Intent(getUploadFinishMessage());
  786. end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  787. // path, after
  788. // possible
  789. // automatic
  790. // renaming
  791. if (upload.wasRenamed()) {
  792. end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
  793. }
  794. end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  795. end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  796. end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
  797. sendStickyBroadcast(end);
  798. }
  799. }