FileUploader.java 39 KB

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