FileUploader.java 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * Copyright (C) 2012 Bartek Przybylski
  5. * Copyright (C) 2012-2015 ownCloud Inc.
  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. */
  20. package com.owncloud.android.files.services;
  21. import java.io.File;
  22. import java.util.AbstractList;
  23. import java.util.HashMap;
  24. import java.util.Iterator;
  25. import java.util.Map;
  26. import java.util.Vector;
  27. import android.accounts.Account;
  28. import android.accounts.AccountManager;
  29. import android.accounts.OnAccountsUpdateListener;
  30. import android.app.NotificationManager;
  31. import android.app.PendingIntent;
  32. import android.app.Service;
  33. import android.content.Intent;
  34. import android.os.Binder;
  35. import android.os.Handler;
  36. import android.os.HandlerThread;
  37. import android.os.IBinder;
  38. import android.os.Looper;
  39. import android.os.Message;
  40. import android.os.Process;
  41. import android.support.v4.app.NotificationCompat;
  42. import android.util.Pair;
  43. import android.webkit.MimeTypeMap;
  44. import com.owncloud.android.R;
  45. import com.owncloud.android.authentication.AccountUtils;
  46. import com.owncloud.android.authentication.AuthenticatorActivity;
  47. import com.owncloud.android.datamodel.FileDataStorageManager;
  48. import com.owncloud.android.datamodel.OCFile;
  49. import com.owncloud.android.db.DbHandler;
  50. import com.owncloud.android.lib.common.OwnCloudAccount;
  51. import com.owncloud.android.lib.common.OwnCloudClient;
  52. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  53. import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  54. import com.owncloud.android.lib.common.operations.RemoteOperation;
  55. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  56. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  57. import com.owncloud.android.lib.common.utils.Log_OC;
  58. import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
  59. import com.owncloud.android.lib.resources.files.FileUtils;
  60. import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
  61. import com.owncloud.android.lib.resources.files.RemoteFile;
  62. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  63. import com.owncloud.android.notifications.NotificationBuilderWithProgressBar;
  64. import com.owncloud.android.notifications.NotificationDelayer;
  65. import com.owncloud.android.operations.CreateFolderOperation;
  66. import com.owncloud.android.operations.UploadFileOperation;
  67. import com.owncloud.android.operations.common.SyncOperation;
  68. import com.owncloud.android.ui.activity.FileActivity;
  69. import com.owncloud.android.ui.activity.FileDisplayActivity;
  70. import com.owncloud.android.utils.ErrorMessageAdapter;
  71. import com.owncloud.android.utils.UriUtils;
  72. public class FileUploader extends Service
  73. implements OnDatatransferProgressListener, OnAccountsUpdateListener {
  74. private static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
  75. public static final String EXTRA_UPLOAD_RESULT = "RESULT";
  76. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  77. public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
  78. public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
  79. public static final String EXTRA_LINKED_TO_PATH = "LINKED_TO";
  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 OwnCloudClient mUploadClient = null;
  100. private Account mCurrentAccount = null;
  101. private FileDataStorageManager mStorageManager;
  102. private IndexedForest<UploadFileOperation> mPendingUploads = new IndexedForest<UploadFileOperation>();
  103. private UploadFileOperation mCurrentUpload = null;
  104. private NotificationManager mNotificationManager;
  105. private NotificationCompat.Builder mNotificationBuilder;
  106. private int mLastPercent;
  107. private static final String MIME_TYPE_PDF = "application/pdf";
  108. private static final String FILE_EXTENSION_PDF = ".pdf";
  109. public static String getUploadFinishMessage() {
  110. return FileUploader.class.getName() + UPLOAD_FINISH_MESSAGE;
  111. }
  112. /**
  113. * Checks if an ownCloud server version should support chunked uploads.
  114. *
  115. * @param version OwnCloud version instance corresponding to an ownCloud
  116. * server.
  117. * @return 'True' if the ownCloud server with version supports chunked
  118. * uploads.
  119. *
  120. * TODO - move to OCClient
  121. */
  122. private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
  123. return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
  124. }
  125. /**
  126. * Service initialization
  127. */
  128. @Override
  129. public void onCreate() {
  130. super.onCreate();
  131. Log_OC.d(TAG, "Creating service");
  132. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  133. HandlerThread thread = new HandlerThread("FileUploaderThread",
  134. Process.THREAD_PRIORITY_BACKGROUND);
  135. thread.start();
  136. mServiceLooper = thread.getLooper();
  137. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  138. mBinder = new FileUploaderBinder();
  139. // add AccountsUpdatedListener
  140. AccountManager am = AccountManager.get(getApplicationContext());
  141. am.addOnAccountsUpdatedListener(this, null, false);
  142. }
  143. /**
  144. * Service clean up
  145. */
  146. @Override
  147. public void onDestroy() {
  148. Log_OC.v(TAG, "Destroying service" );
  149. mBinder = null;
  150. mServiceHandler = null;
  151. mServiceLooper.quit();
  152. mServiceLooper = null;
  153. mNotificationManager = null;
  154. // remove AccountsUpdatedListener
  155. AccountManager am = AccountManager.get(getApplicationContext());
  156. am.removeOnAccountsUpdatedListener(this);
  157. super.onDestroy();
  158. }
  159. /**
  160. * Entry point to add one or several files to the queue of uploads.
  161. *
  162. * New uploads are added calling to startService(), resulting in a call to
  163. * this method. This ensures the service will keep on working although the
  164. * caller activity goes away.
  165. */
  166. @Override
  167. public int onStartCommand(Intent intent, int flags, int startId) {
  168. Log_OC.d(TAG, "Starting command with id " + startId);
  169. if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE)
  170. || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
  171. Log_OC.e(TAG, "Not enough information provided in intent");
  172. return Service.START_NOT_STICKY;
  173. }
  174. int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
  175. if (uploadType == -1) {
  176. Log_OC.e(TAG, "Incorrect upload type provided");
  177. return Service.START_NOT_STICKY;
  178. }
  179. Account account = intent.getParcelableExtra(KEY_ACCOUNT);
  180. if (!AccountUtils.exists(account, getApplicationContext())) {
  181. return Service.START_NOT_STICKY;
  182. }
  183. String[] localPaths = null, remotePaths = null, mimeTypes = null;
  184. OCFile[] files = null;
  185. if (uploadType == UPLOAD_SINGLE_FILE) {
  186. if (intent.hasExtra(KEY_FILE)) {
  187. files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) };
  188. } else {
  189. localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
  190. remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
  191. mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
  192. }
  193. } else { // mUploadType == UPLOAD_MULTIPLE_FILES
  194. if (intent.hasExtra(KEY_FILE)) {
  195. files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO
  196. // will
  197. // this
  198. // casting
  199. // work
  200. // fine?
  201. } else {
  202. localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
  203. remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
  204. mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
  205. }
  206. }
  207. FileDataStorageManager storageManager = new FileDataStorageManager(account,
  208. getContentResolver());
  209. boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
  210. boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
  211. int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_FORGET);
  212. if (intent.hasExtra(KEY_FILE) && files == null) {
  213. Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
  214. return Service.START_NOT_STICKY;
  215. } else if (!intent.hasExtra(KEY_FILE)) {
  216. if (localPaths == null) {
  217. Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent");
  218. return Service.START_NOT_STICKY;
  219. }
  220. if (remotePaths == null) {
  221. Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent");
  222. return Service.START_NOT_STICKY;
  223. }
  224. if (localPaths.length != remotePaths.length) {
  225. Log_OC.e(TAG, "Different number of remote paths and local paths!");
  226. return Service.START_NOT_STICKY;
  227. }
  228. files = new OCFile[localPaths.length];
  229. for (int i = 0; i < localPaths.length; i++) {
  230. files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i],
  231. ((mimeTypes != null) ? mimeTypes[i] : null));
  232. if (files[i] == null) {
  233. // TODO @andomaex add failure Notification
  234. return Service.START_NOT_STICKY;
  235. }
  236. }
  237. }
  238. OwnCloudVersion ocv = AccountUtils.getServerVersion(account);
  239. boolean chunked = FileUploader.chunkedUploadIsSupported(ocv);
  240. AbstractList<String> requestedUploads = new Vector<String>();
  241. String uploadKey = null;
  242. UploadFileOperation newUpload = null;
  243. try {
  244. for (int i = 0; i < files.length; i++) {
  245. newUpload = new UploadFileOperation(
  246. account,
  247. files[i],
  248. chunked,
  249. isInstant,
  250. forceOverwrite, localAction,
  251. getApplicationContext()
  252. );
  253. if (isInstant) {
  254. newUpload.setRemoteFolderToBeCreated();
  255. }
  256. newUpload.addDatatransferProgressListener(this);
  257. newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
  258. Pair<String, String> putResult = mPendingUploads.putIfAbsent(
  259. account, files[i].getRemotePath(), newUpload
  260. );
  261. if (putResult != null) {
  262. uploadKey = putResult.first;
  263. requestedUploads.add(uploadKey);
  264. } // else, file already in the queue of uploads; don't repeat the request
  265. }
  266. } catch (IllegalArgumentException e) {
  267. Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  268. return START_NOT_STICKY;
  269. } catch (IllegalStateException e) {
  270. Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
  271. return START_NOT_STICKY;
  272. } catch (Exception e) {
  273. Log_OC.e(TAG, "Unexpected exception while processing upload intent", e);
  274. return START_NOT_STICKY;
  275. }
  276. if (requestedUploads.size() > 0) {
  277. Message msg = mServiceHandler.obtainMessage();
  278. msg.arg1 = startId;
  279. msg.obj = requestedUploads;
  280. mServiceHandler.sendMessage(msg);
  281. }
  282. return Service.START_NOT_STICKY;
  283. }
  284. /**
  285. * Provides a binder object that clients can use to perform operations on
  286. * the queue of uploads, excepting the addition of new files.
  287. *
  288. * Implemented to perform cancellation, pause and resume of existing
  289. * uploads.
  290. */
  291. @Override
  292. public IBinder onBind(Intent arg0) {
  293. return mBinder;
  294. }
  295. /**
  296. * Called when ALL the bound clients were onbound.
  297. */
  298. @Override
  299. public boolean onUnbind(Intent intent) {
  300. ((FileUploaderBinder)mBinder).clearListeners();
  301. return false; // not accepting rebinding (default behaviour)
  302. }
  303. @Override
  304. public void onAccountsUpdated(Account[] accounts) {
  305. // Review current upload, and cancel it if its account doen't exist
  306. if (mCurrentUpload != null &&
  307. !AccountUtils.exists(mCurrentUpload.getAccount(), getApplicationContext())) {
  308. mCurrentUpload.cancel();
  309. }
  310. // The rest of uploads are cancelled when they try to start
  311. }
  312. /**
  313. * Binder to let client components to perform operations on the queue of
  314. * uploads.
  315. *
  316. * It provides by itself the available operations.
  317. */
  318. public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
  319. /**
  320. * Map of listeners that will be reported about progress of uploads from a
  321. * {@link FileUploaderBinder} instance
  322. */
  323. private Map<String, OnDatatransferProgressListener> mBoundListeners =
  324. new HashMap<String, OnDatatransferProgressListener>();
  325. /**
  326. * Cancels a pending or current upload of a remote file.
  327. *
  328. * @param account ownCloud account where the remote file will be stored.
  329. * @param file A file in the queue of pending uploads
  330. */
  331. public void cancel(Account account, OCFile file) {
  332. Pair<UploadFileOperation, String> removeResult = mPendingUploads.remove(account, file.getRemotePath());
  333. UploadFileOperation upload = removeResult.first;
  334. if (upload != null) {
  335. upload.cancel();
  336. } else {
  337. if (mCurrentUpload != null && mCurrentAccount != null &&
  338. mCurrentUpload.getRemotePath().startsWith(file.getRemotePath()) &&
  339. account.name.equals(mCurrentAccount.name)) {
  340. mCurrentUpload.cancel();
  341. }
  342. }
  343. }
  344. /**
  345. * Cancels all the uploads for an account
  346. *
  347. * @param account ownCloud account.
  348. */
  349. public void cancel(Account account) {
  350. Log_OC.d(TAG, "Account= " + account.name);
  351. if (mCurrentUpload != null) {
  352. Log_OC.d(TAG, "Current Upload Account= " + mCurrentUpload.getAccount().name);
  353. if (mCurrentUpload.getAccount().name.equals(account.name)) {
  354. mCurrentUpload.cancel();
  355. }
  356. }
  357. // Cancel pending uploads
  358. cancelUploadsForAccount(account);
  359. }
  360. public void clearListeners() {
  361. mBoundListeners.clear();
  362. }
  363. /**
  364. * Returns True when the file described by 'file' is being uploaded to
  365. * the ownCloud account 'account' or waiting for it
  366. *
  367. * If 'file' is a directory, returns 'true' if some of its descendant files
  368. * is uploading or waiting to upload.
  369. *
  370. * @param account ownCloud account where the remote file will be stored.
  371. * @param file A file that could be in the queue of pending uploads
  372. */
  373. public boolean isUploading(Account account, OCFile file) {
  374. if (account == null || file == null) return false;
  375. return (mPendingUploads.contains(account, file.getRemotePath()));
  376. }
  377. /**
  378. * Adds a listener interested in the progress of the upload for a concrete file.
  379. *
  380. * @param listener Object to notify about progress of transfer.
  381. * @param account ownCloud account holding the file of interest.
  382. * @param file {@link OCFile} of interest for listener.
  383. */
  384. public void addDatatransferProgressListener (OnDatatransferProgressListener listener,
  385. Account account, OCFile file) {
  386. if (account == null || file == null || listener == null) return;
  387. String targetKey = buildRemoteName(account, file);
  388. mBoundListeners.put(targetKey, listener);
  389. }
  390. /**
  391. * Removes a listener interested in the progress of the upload for a concrete file.
  392. *
  393. * @param listener Object to notify about progress of transfer.
  394. * @param account ownCloud account holding the file of interest.
  395. * @param file {@link OCFile} of interest for listener.
  396. */
  397. public void removeDatatransferProgressListener (OnDatatransferProgressListener listener,
  398. Account account, OCFile file) {
  399. if (account == null || file == null || listener == null) return;
  400. String targetKey = buildRemoteName(account, file);
  401. if (mBoundListeners.get(targetKey) == listener) {
  402. mBoundListeners.remove(targetKey);
  403. }
  404. }
  405. @Override
  406. public void onTransferProgress(long progressRate, long totalTransferredSoFar,
  407. long totalToTransfer, String fileName) {
  408. String key = buildRemoteName(mCurrentUpload.getAccount(), mCurrentUpload.getFile());
  409. OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
  410. if (boundListener != null) {
  411. boundListener.onTransferProgress(progressRate, totalTransferredSoFar,
  412. totalToTransfer, fileName);
  413. }
  414. }
  415. /**
  416. * Builds a key for the map of listeners.
  417. *
  418. * TODO remove and replace key with file.getFileId() after changing current policy (upload file, then
  419. * add to local database) to better policy (add to local database, then upload)
  420. *
  421. * @param account ownCloud account where the file to upload belongs.
  422. * @param file File to upload
  423. * @return Key
  424. */
  425. private String buildRemoteName(Account account, OCFile file) {
  426. return account.name + file.getRemotePath();
  427. }
  428. }
  429. /**
  430. * Upload worker. Performs the pending uploads in the order they were
  431. * requested.
  432. *
  433. * Created with the Looper of a new thread, started in
  434. * {@link FileUploader#onCreate()}.
  435. */
  436. private static class ServiceHandler extends Handler {
  437. // don't make it a final class, and don't remove the static ; lint will
  438. // warn about a possible memory leak
  439. FileUploader mService;
  440. public ServiceHandler(Looper looper, FileUploader service) {
  441. super(looper);
  442. if (service == null)
  443. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  444. mService = service;
  445. }
  446. @Override
  447. public void handleMessage(Message msg) {
  448. @SuppressWarnings("unchecked")
  449. AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
  450. if (msg.obj != null) {
  451. Iterator<String> it = requestedUploads.iterator();
  452. while (it.hasNext()) {
  453. mService.uploadFile(it.next());
  454. }
  455. }
  456. Log_OC.d(TAG, "Stopping command after id " + msg.arg1);
  457. mService.stopSelf(msg.arg1);
  458. }
  459. }
  460. /**
  461. * Core upload method: sends the file(s) to upload
  462. *
  463. * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
  464. */
  465. public void uploadFile(String uploadKey) {
  466. mCurrentUpload = mPendingUploads.get(uploadKey);
  467. if (mCurrentUpload != null) {
  468. // Detect if the account exists
  469. if (AccountUtils.exists(mCurrentUpload.getAccount(), getApplicationContext())) {
  470. Log_OC.d(TAG, "Account " + mCurrentUpload.getAccount().name + " exists");
  471. notifyUploadStart(mCurrentUpload);
  472. RemoteOperationResult uploadResult = null, grantResult;
  473. try {
  474. /// prepare client object to send the request to the ownCloud server
  475. if (mCurrentAccount == null || !mCurrentAccount.equals(mCurrentUpload.getAccount())) {
  476. mCurrentAccount = mCurrentUpload.getAccount();
  477. mStorageManager = new FileDataStorageManager(
  478. mCurrentAccount,
  479. getContentResolver()
  480. );
  481. } // else, reuse storage manager from previous operation
  482. // always get client from client manager, to get fresh credentials in case of update
  483. OwnCloudAccount ocAccount = new OwnCloudAccount(mCurrentAccount, this);
  484. mUploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  485. getClientFor(ocAccount, this);
  486. /// check the existence of the parent folder for the file to upload
  487. String remoteParentPath = new File(mCurrentUpload.getRemotePath()).getParent();
  488. remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ?
  489. remoteParentPath : remoteParentPath + OCFile.PATH_SEPARATOR;
  490. grantResult = grantFolderExistence(remoteParentPath);
  491. /// perform the upload
  492. if (grantResult.isSuccess()) {
  493. OCFile parent = mStorageManager.getFileByPath(remoteParentPath);
  494. mCurrentUpload.getFile().setParentId(parent.getFileId());
  495. uploadResult = mCurrentUpload.execute(mUploadClient);
  496. if (uploadResult.isSuccess()) {
  497. saveUploadedFile();
  498. } else if (uploadResult.getCode() == ResultCode.SYNC_CONFLICT) {
  499. mStorageManager.saveConflict(mCurrentUpload.getFile(),
  500. mCurrentUpload.getFile().getEtagInConflict());
  501. }
  502. } else {
  503. uploadResult = grantResult;
  504. }
  505. } catch (Exception e) {
  506. Log_OC.e(TAG, "Error uploading", e);
  507. uploadResult = new RemoteOperationResult(e);
  508. } finally {
  509. Pair<UploadFileOperation, String> removeResult;
  510. if (mCurrentUpload.wasRenamed()) {
  511. removeResult = mPendingUploads.removePayload(
  512. mCurrentAccount,
  513. mCurrentUpload.getOldFile().getRemotePath()
  514. );
  515. } else {
  516. removeResult = mPendingUploads.removePayload(
  517. mCurrentAccount,
  518. mCurrentUpload.getRemotePath()
  519. );
  520. }
  521. /// notify result
  522. notifyUploadResult(mCurrentUpload, uploadResult);
  523. sendBroadcastUploadFinished(mCurrentUpload, uploadResult, removeResult.second);
  524. }
  525. } else {
  526. // Cancel the transfer
  527. Log_OC.d(TAG, "Account " + mCurrentUpload.getAccount().toString() +
  528. " doesn't exist");
  529. cancelUploadsForAccount(mCurrentUpload.getAccount());
  530. }
  531. }
  532. }
  533. /**
  534. * Checks the existence of the folder where the current file will be uploaded both
  535. * in the remote server and in the local database.
  536. *
  537. * If the upload is set to enforce the creation of the folder, the method tries to
  538. * create it both remote and locally.
  539. *
  540. * @param pathToGrant Full remote path whose existence will be granted.
  541. * @return An {@link OCFile} instance corresponding to the folder where the file
  542. * will be uploaded.
  543. */
  544. private RemoteOperationResult grantFolderExistence(String pathToGrant) {
  545. RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, this, false);
  546. RemoteOperationResult result = operation.execute(mUploadClient);
  547. if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND &&
  548. mCurrentUpload.isRemoteFolderToBeCreated()) {
  549. SyncOperation syncOp = new CreateFolderOperation( pathToGrant, true);
  550. result = syncOp.execute(mUploadClient, mStorageManager);
  551. }
  552. if (result.isSuccess()) {
  553. OCFile parentDir = mStorageManager.getFileByPath(pathToGrant);
  554. if (parentDir == null) {
  555. parentDir = createLocalFolder(pathToGrant);
  556. }
  557. if (parentDir != null) {
  558. result = new RemoteOperationResult(ResultCode.OK);
  559. } else {
  560. result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  561. }
  562. }
  563. return result;
  564. }
  565. private OCFile createLocalFolder(String remotePath) {
  566. String parentPath = new File(remotePath).getParent();
  567. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ?
  568. parentPath : parentPath + OCFile.PATH_SEPARATOR;
  569. OCFile parent = mStorageManager.getFileByPath(parentPath);
  570. if (parent == null) {
  571. parent = createLocalFolder(parentPath);
  572. }
  573. if (parent != null) {
  574. OCFile createdFolder = new OCFile(remotePath);
  575. createdFolder.setMimetype("DIR");
  576. createdFolder.setParentId(parent.getFileId());
  577. mStorageManager.saveFile(createdFolder);
  578. return createdFolder;
  579. }
  580. return null;
  581. }
  582. /**
  583. * Saves a OC File after a successful upload.
  584. *
  585. * A PROPFIND is necessary to keep the props in the local database
  586. * synchronized with the server, specially the modification time and Etag
  587. * (where available)
  588. *
  589. * TODO move into UploadFileOperation
  590. */
  591. private void saveUploadedFile() {
  592. OCFile file = mCurrentUpload.getFile();
  593. if (file.fileExists()) {
  594. file = mStorageManager.getFileById(file.getFileId());
  595. }
  596. long syncDate = System.currentTimeMillis();
  597. file.setLastSyncDateForData(syncDate);
  598. // new PROPFIND to keep data consistent with server
  599. // in theory, should return the same we already have
  600. ReadRemoteFileOperation operation =
  601. new ReadRemoteFileOperation(mCurrentUpload.getRemotePath());
  602. RemoteOperationResult result = operation.execute(mUploadClient);
  603. if (result.isSuccess()) {
  604. updateOCFile(file, (RemoteFile) result.getData().get(0));
  605. file.setLastSyncDateForProperties(syncDate);
  606. } else {
  607. Log_OC.e(TAG, "Error reading properties of file after successful upload; this is gonna hurt...");
  608. }
  609. // / maybe this would be better as part of UploadFileOperation... or
  610. // maybe all this method
  611. if (mCurrentUpload.wasRenamed()) {
  612. OCFile oldFile = mCurrentUpload.getOldFile();
  613. if (oldFile.fileExists()) {
  614. oldFile.setStoragePath(null);
  615. mStorageManager.saveFile(oldFile);
  616. mStorageManager.saveConflict(oldFile, null);
  617. } // else: it was just an automatic renaming due to a name
  618. // coincidence; nothing else is needed, the storagePath is right
  619. // in the instance returned by mCurrentUpload.getFile()
  620. }
  621. file.setNeedsUpdateThumbnail(true);
  622. mStorageManager.saveFile(file);
  623. mStorageManager.saveConflict(file, null);
  624. mStorageManager.triggerMediaScan(file.getStoragePath());
  625. }
  626. private void updateOCFile(OCFile file, RemoteFile remoteFile) {
  627. file.setCreationTimestamp(remoteFile.getCreationTimestamp());
  628. file.setFileLength(remoteFile.getLength());
  629. file.setMimetype(remoteFile.getMimeType());
  630. file.setModificationTimestamp(remoteFile.getModifiedTimestamp());
  631. file.setModificationTimestampAtLastSyncForData(remoteFile.getModifiedTimestamp());
  632. file.setEtag(remoteFile.getEtag());
  633. file.setRemoteId(remoteFile.getRemoteId());
  634. }
  635. private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType) {
  636. // MIME type
  637. if (mimeType == null || mimeType.length() <= 0) {
  638. try {
  639. mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
  640. remotePath.substring(remotePath.lastIndexOf('.') + 1));
  641. } catch (IndexOutOfBoundsException e) {
  642. Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " +
  643. remotePath);
  644. }
  645. }
  646. if (mimeType == null) {
  647. mimeType = "application/octet-stream";
  648. }
  649. if (isPdfFileFromContentProviderWithoutExtension(localPath, mimeType)){
  650. remotePath += FILE_EXTENSION_PDF;
  651. }
  652. OCFile newFile = new OCFile(remotePath);
  653. newFile.setStoragePath(localPath);
  654. newFile.setLastSyncDateForProperties(0);
  655. newFile.setLastSyncDateForData(0);
  656. // size
  657. if (localPath != null && localPath.length() > 0) {
  658. File localFile = new File(localPath);
  659. newFile.setFileLength(localFile.length());
  660. newFile.setLastSyncDateForData(localFile.lastModified());
  661. } // don't worry about not assigning size, the problems with localPath
  662. // are checked when the UploadFileOperation instance is created
  663. newFile.setMimetype(mimeType);
  664. return newFile;
  665. }
  666. /**
  667. * Creates a status notification to show the upload progress
  668. *
  669. * @param upload Upload operation starting.
  670. */
  671. private void notifyUploadStart(UploadFileOperation upload) {
  672. // / create status notification with a progress bar
  673. mLastPercent = 0;
  674. mNotificationBuilder =
  675. NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
  676. mNotificationBuilder
  677. .setOngoing(true)
  678. .setSmallIcon(R.drawable.notification_icon)
  679. .setTicker(getString(R.string.uploader_upload_in_progress_ticker))
  680. .setContentTitle(getString(R.string.uploader_upload_in_progress_ticker))
  681. .setProgress(100, 0, false)
  682. .setContentText(
  683. String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
  684. /// includes a pending intent in the notification showing the details view of the file
  685. Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
  686. showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
  687. showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  688. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  689. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
  690. this, (int) System.currentTimeMillis(), showDetailsIntent, 0
  691. ));
  692. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
  693. }
  694. /**
  695. * Callback method to update the progress bar in the status notification
  696. */
  697. @Override
  698. public void onTransferProgress(long progressRate, long totalTransferredSoFar,
  699. long totalToTransfer, String filePath) {
  700. int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
  701. if (percent != mLastPercent) {
  702. mNotificationBuilder.setProgress(100, percent, false);
  703. String fileName = filePath.substring(
  704. filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
  705. String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
  706. mNotificationBuilder.setContentText(text);
  707. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
  708. }
  709. mLastPercent = percent;
  710. }
  711. /**
  712. * Updates the status notification with the result of an upload operation.
  713. *
  714. * @param uploadResult Result of the upload operation.
  715. * @param upload Finished upload operation
  716. */
  717. private void notifyUploadResult(UploadFileOperation upload,
  718. RemoteOperationResult uploadResult) {
  719. Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
  720. // / cancelled operation or success -> silent removal of progress notification
  721. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  722. // Show the result: success or fail notification
  723. if (!uploadResult.isCancelled()) {
  724. int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker :
  725. R.string.uploader_upload_failed_ticker;
  726. String content;
  727. // check credentials error
  728. boolean needsToUpdateCredentials = (
  729. uploadResult.getCode() == ResultCode.UNAUTHORIZED ||
  730. uploadResult.isIdPRedirection()
  731. );
  732. tickerId = (needsToUpdateCredentials) ?
  733. R.string.uploader_upload_failed_credentials_error : tickerId;
  734. mNotificationBuilder
  735. .setTicker(getString(tickerId))
  736. .setContentTitle(getString(tickerId))
  737. .setAutoCancel(true)
  738. .setOngoing(false)
  739. .setProgress(0, 0, false);
  740. content = ErrorMessageAdapter.getErrorCauseMessage(
  741. uploadResult, upload, getResources()
  742. );
  743. if (needsToUpdateCredentials) {
  744. // let the user update credentials with one click
  745. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  746. updateAccountCredentials.putExtra(
  747. AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount()
  748. );
  749. updateAccountCredentials.putExtra(
  750. AuthenticatorActivity.EXTRA_ACTION,
  751. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN
  752. );
  753. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  754. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  755. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  756. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
  757. this,
  758. (int) System.currentTimeMillis(),
  759. updateAccountCredentials,
  760. PendingIntent.FLAG_ONE_SHOT
  761. ));
  762. mUploadClient = null;
  763. // grant that future retries on the same account will get the fresh credentials
  764. } else {
  765. mNotificationBuilder.setContentText(content);
  766. if (upload.isInstant()) {
  767. DbHandler db = null;
  768. try {
  769. db = new DbHandler(this.getBaseContext());
  770. String message = uploadResult.getLogMessage() + " errorCode: " +
  771. uploadResult.getCode();
  772. Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
  773. if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
  774. //message = getString(R.string.failed_upload_quota_exceeded_text);
  775. if (db.updateFileState(
  776. upload.getOriginalStoragePath(),
  777. DbHandler.UPLOAD_STATUS_UPLOAD_FAILED,
  778. message) == 0) {
  779. db.putFileForLater(
  780. upload.getOriginalStoragePath(),
  781. upload.getAccount().name,
  782. message
  783. );
  784. }
  785. }
  786. } finally {
  787. if (db != null) {
  788. db.close();
  789. }
  790. }
  791. }
  792. }
  793. mNotificationBuilder.setContentText(content);
  794. mNotificationManager.notify(tickerId, mNotificationBuilder.build());
  795. if (uploadResult.isSuccess()) {
  796. DbHandler db = new DbHandler(this.getBaseContext());
  797. db.removeIUPendingFile(mCurrentUpload.getOriginalStoragePath());
  798. db.close();
  799. // remove success notification, with a delay of 2 seconds
  800. NotificationDelayer.cancelWithDelay(
  801. mNotificationManager,
  802. R.string.uploader_upload_succeeded_ticker,
  803. 2000);
  804. }
  805. }
  806. }
  807. /**
  808. * Sends a broadcast in order to the interested activities can update their
  809. * view
  810. *
  811. * @param upload Finished upload operation
  812. * @param uploadResult Result of the upload operation
  813. * @param unlinkedFromRemotePath Path in the uploads tree where the upload was unlinked from
  814. */
  815. private void sendBroadcastUploadFinished(
  816. UploadFileOperation upload,
  817. RemoteOperationResult uploadResult,
  818. String unlinkedFromRemotePath) {
  819. Intent end = new Intent(getUploadFinishMessage());
  820. end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  821. // path, after
  822. // possible
  823. // automatic
  824. // renaming
  825. if (upload.wasRenamed()) {
  826. end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
  827. }
  828. end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  829. end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  830. end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
  831. if (unlinkedFromRemotePath != null) {
  832. end.putExtra(EXTRA_LINKED_TO_PATH, unlinkedFromRemotePath);
  833. }
  834. sendStickyBroadcast(end);
  835. }
  836. /**
  837. * Checks if content provider, using the content:// scheme, returns a file with mime-type
  838. * 'application/pdf' but file has not extension
  839. * @param localPath Full path to a file in the local file system.
  840. * @param mimeType MIME type of the file.
  841. * @return true if is needed to add the pdf file extension to the file
  842. *
  843. * TODO - move to OCFile or Utils class
  844. */
  845. private boolean isPdfFileFromContentProviderWithoutExtension(String localPath,
  846. String mimeType) {
  847. return localPath.startsWith(UriUtils.URI_CONTENT_SCHEME) &&
  848. mimeType.equals(MIME_TYPE_PDF) &&
  849. !localPath.endsWith(FILE_EXTENSION_PDF);
  850. }
  851. /**
  852. * Remove uploads of an account
  853. *
  854. * @param account Downloads account to remove
  855. */
  856. private void cancelUploadsForAccount(Account account){
  857. // Cancel pending uploads
  858. mPendingUploads.remove(account);
  859. }
  860. }