FileUploader.java 41 KB

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