FileUploader.java 40 KB

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