FileUploader.java 41 KB

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