FileUploader.java 36 KB

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