FileUploader.java 40 KB

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