FileDownloader.java 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.Iterator;
  25. import java.util.Map;
  26. import java.util.Vector;
  27. import java.util.concurrent.ConcurrentHashMap;
  28. import java.util.concurrent.ConcurrentMap;
  29. import com.owncloud.android.R;
  30. import com.owncloud.android.authentication.AuthenticatorActivity;
  31. import com.owncloud.android.datamodel.FileDataStorageManager;
  32. import com.owncloud.android.datamodel.OCFile;
  33. import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  34. import com.owncloud.android.lib.common.OwnCloudAccount;
  35. import com.owncloud.android.lib.common.OwnCloudClient;
  36. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  37. import com.owncloud.android.notifications.NotificationBuilderWithProgressBar;
  38. import com.owncloud.android.notifications.NotificationDelayer;
  39. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  40. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  41. import com.owncloud.android.lib.common.utils.Log_OC;
  42. import com.owncloud.android.lib.resources.files.FileUtils;
  43. import com.owncloud.android.operations.DownloadFileOperation;
  44. import com.owncloud.android.ui.activity.FileActivity;
  45. import com.owncloud.android.ui.activity.FileDisplayActivity;
  46. import com.owncloud.android.ui.preview.PreviewImageActivity;
  47. import com.owncloud.android.ui.preview.PreviewImageFragment;
  48. import com.owncloud.android.utils.ErrorMessageAdapter;
  49. import android.accounts.Account;
  50. import android.accounts.AccountsException;
  51. import android.app.NotificationManager;
  52. import android.app.PendingIntent;
  53. import android.app.Service;
  54. import android.content.Intent;
  55. import android.os.Binder;
  56. import android.os.Handler;
  57. import android.os.HandlerThread;
  58. import android.os.IBinder;
  59. import android.os.Looper;
  60. import android.os.Message;
  61. import android.os.Process;
  62. import android.support.v4.app.NotificationCompat;
  63. public class FileDownloader extends Service implements OnDatatransferProgressListener {
  64. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  65. public static final String EXTRA_FILE = "FILE";
  66. public static final String ACTION_CANCEL_FILE_DOWNLOAD = "CANCEL_FILE_DOWNLOAD";
  67. private static final String DOWNLOAD_ADDED_MESSAGE = "DOWNLOAD_ADDED";
  68. private static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
  69. public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
  70. public static final String EXTRA_FILE_PATH = "FILE_PATH";
  71. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  72. public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
  73. private static final String TAG = "FileDownloader";
  74. private Looper mServiceLooper;
  75. private ServiceHandler mServiceHandler;
  76. private IBinder mBinder;
  77. private OwnCloudClient mDownloadClient = null;
  78. private Account mLastAccount = null;
  79. private FileDataStorageManager mStorageManager;
  80. private ConcurrentMap<String, DownloadFileOperation> mPendingDownloads = new ConcurrentHashMap<String, DownloadFileOperation>();
  81. private DownloadFileOperation mCurrentDownload = null;
  82. private NotificationManager mNotificationManager;
  83. private NotificationCompat.Builder mNotificationBuilder;
  84. private int mLastPercent;
  85. private Account mAccount;
  86. private OCFile mFile;
  87. public static String getDownloadAddedMessage() {
  88. return FileDownloader.class.getName().toString() + DOWNLOAD_ADDED_MESSAGE;
  89. }
  90. public static String getDownloadFinishMessage() {
  91. return FileDownloader.class.getName().toString() + DOWNLOAD_FINISH_MESSAGE;
  92. }
  93. /**
  94. * Builds a key for mPendingDownloads from the account and file to download
  95. *
  96. * @param account Account where the file to download is stored
  97. * @param file File to download
  98. */
  99. private String buildRemoteName(Account account, OCFile file) {
  100. return account.name + file.getRemotePath();
  101. }
  102. /**
  103. * Service initialization
  104. */
  105. @Override
  106. public void onCreate() {
  107. super.onCreate();
  108. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  109. HandlerThread thread = new HandlerThread("FileDownloaderThread",
  110. Process.THREAD_PRIORITY_BACKGROUND);
  111. thread.start();
  112. mServiceLooper = thread.getLooper();
  113. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  114. mBinder = new FileDownloaderBinder();
  115. }
  116. /**
  117. * Entry point to add one or several files to the queue of downloads.
  118. *
  119. * New downloads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
  120. * although the caller activity goes away.
  121. */
  122. @Override
  123. public int onStartCommand(Intent intent, int flags, int startId) {
  124. if ( !intent.hasExtra(EXTRA_ACCOUNT) ||
  125. !intent.hasExtra(EXTRA_FILE)
  126. /*!intent.hasExtra(EXTRA_FILE_PATH) ||
  127. !intent.hasExtra(EXTRA_REMOTE_PATH)*/
  128. ) {
  129. Log_OC.e(TAG, "Not enough information provided in intent");
  130. return START_NOT_STICKY;
  131. } else {
  132. mAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);
  133. mFile = intent.getParcelableExtra(EXTRA_FILE);
  134. if (ACTION_CANCEL_FILE_DOWNLOAD.equals(intent.getAction())) {
  135. new Thread(new Runnable() {
  136. public void run() {
  137. // Cancel the download
  138. cancel(mAccount,mFile);
  139. }
  140. }).start();
  141. } else {
  142. AbstractList<String> requestedDownloads = new Vector<String>(); // dvelasco: now this always contains just one element, but that can change in a near future (download of multiple selection)
  143. String downloadKey = buildRemoteName(mAccount, mFile);
  144. try {
  145. DownloadFileOperation newDownload = new DownloadFileOperation(mAccount, mFile);
  146. mPendingDownloads.putIfAbsent(downloadKey, newDownload);
  147. newDownload.addDatatransferProgressListener(this);
  148. newDownload.addDatatransferProgressListener((FileDownloaderBinder) mBinder);
  149. requestedDownloads.add(downloadKey);
  150. sendBroadcastNewDownload(newDownload);
  151. } catch (IllegalArgumentException e) {
  152. Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  153. return START_NOT_STICKY;
  154. }
  155. if (requestedDownloads.size() > 0) {
  156. Message msg = mServiceHandler.obtainMessage();
  157. msg.arg1 = startId;
  158. msg.obj = requestedDownloads;
  159. mServiceHandler.sendMessage(msg);
  160. }
  161. }
  162. }
  163. return START_NOT_STICKY;
  164. }
  165. /**
  166. * Provides a binder object that clients can use to perform operations on the queue of downloads, excepting the addition of new files.
  167. *
  168. * Implemented to perform cancellation, pause and resume of existing downloads.
  169. */
  170. @Override
  171. public IBinder onBind(Intent arg0) {
  172. return mBinder;
  173. }
  174. /**
  175. * Called when ALL the bound clients were onbound.
  176. */
  177. @Override
  178. public boolean onUnbind(Intent intent) {
  179. ((FileDownloaderBinder)mBinder).clearListeners();
  180. return false; // not accepting rebinding (default behaviour)
  181. }
  182. /**
  183. * Binder to let client components to perform operations on the queue of downloads.
  184. *
  185. * It provides by itself the available operations.
  186. */
  187. public class FileDownloaderBinder extends Binder implements OnDatatransferProgressListener {
  188. /**
  189. * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder} instance
  190. */
  191. private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
  192. /**
  193. * Cancels a pending or current download of a remote file.
  194. *
  195. * @param account Owncloud account where the remote file is stored.
  196. * @param file A file in the queue of pending downloads
  197. */
  198. public void cancel(Account account, OCFile file) {
  199. DownloadFileOperation download = null;
  200. synchronized (mPendingDownloads) {
  201. download = mPendingDownloads.remove(buildRemoteName(account, file));
  202. }
  203. if (download != null) {
  204. download.cancel();
  205. }
  206. }
  207. public void clearListeners() {
  208. mBoundListeners.clear();
  209. }
  210. /**
  211. * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download.
  212. *
  213. * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
  214. *
  215. * @param account Owncloud account where the remote file is stored.
  216. * @param file A file that could be in the queue of downloads.
  217. */
  218. public boolean isDownloading(Account account, OCFile file) {
  219. if (account == null || file == null) return false;
  220. String targetKey = buildRemoteName(account, file);
  221. synchronized (mPendingDownloads) {
  222. if (file.isFolder()) {
  223. // this can be slow if there are many downloads :(
  224. Iterator<String> it = mPendingDownloads.keySet().iterator();
  225. boolean found = false;
  226. while (it.hasNext() && !found) {
  227. found = it.next().startsWith(targetKey);
  228. }
  229. return found;
  230. } else {
  231. return (mPendingDownloads.containsKey(targetKey));
  232. }
  233. }
  234. }
  235. /**
  236. * Adds a listener interested in the progress of the download for a concrete file.
  237. *
  238. * @param listener Object to notify about progress of transfer.
  239. * @param account ownCloud account holding the file of interest.
  240. * @param file {@link OCfile} of interest for listener.
  241. */
  242. public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
  243. if (account == null || file == null || listener == null) return;
  244. String targetKey = buildRemoteName(account, file);
  245. mBoundListeners.put(targetKey, listener);
  246. }
  247. /**
  248. * Removes a listener interested in the progress of the download for a concrete file.
  249. *
  250. * @param listener Object to notify about progress of transfer.
  251. * @param account ownCloud account holding the file of interest.
  252. * @param file {@link OCfile} of interest for listener.
  253. */
  254. public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
  255. if (account == null || file == null || listener == null) return;
  256. String targetKey = buildRemoteName(account, file);
  257. if (mBoundListeners.get(targetKey) == listener) {
  258. mBoundListeners.remove(targetKey);
  259. }
  260. }
  261. @Override
  262. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
  263. String fileName) {
  264. String key = buildRemoteName(mCurrentDownload.getAccount(), mCurrentDownload.getFile());
  265. OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
  266. if (boundListener != null) {
  267. boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
  268. }
  269. }
  270. }
  271. /**
  272. * Download worker. Performs the pending downloads in the order they were requested.
  273. *
  274. * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
  275. */
  276. private static class ServiceHandler extends Handler {
  277. // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
  278. FileDownloader mService;
  279. public ServiceHandler(Looper looper, FileDownloader service) {
  280. super(looper);
  281. if (service == null)
  282. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  283. mService = service;
  284. }
  285. @Override
  286. public void handleMessage(Message msg) {
  287. @SuppressWarnings("unchecked")
  288. AbstractList<String> requestedDownloads = (AbstractList<String>) msg.obj;
  289. if (msg.obj != null) {
  290. Iterator<String> it = requestedDownloads.iterator();
  291. while (it.hasNext()) {
  292. mService.downloadFile(it.next());
  293. }
  294. }
  295. mService.stopSelf(msg.arg1);
  296. }
  297. }
  298. /**
  299. * Core download method: requests a file to download and stores it.
  300. *
  301. * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
  302. */
  303. private void downloadFile(String downloadKey) {
  304. synchronized(mPendingDownloads) {
  305. mCurrentDownload = mPendingDownloads.get(downloadKey);
  306. }
  307. if (mCurrentDownload != null) {
  308. notifyDownloadStart(mCurrentDownload);
  309. RemoteOperationResult downloadResult = null;
  310. try {
  311. /// prepare client object to send the request to the ownCloud server
  312. if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {
  313. mLastAccount = mCurrentDownload.getAccount();
  314. mStorageManager =
  315. new FileDataStorageManager(mLastAccount, getContentResolver());
  316. OwnCloudAccount ocAccount = new OwnCloudAccount(mLastAccount, this);
  317. mDownloadClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  318. getClientFor(ocAccount, this);
  319. }
  320. /// perform the download
  321. downloadResult = mCurrentDownload.execute(mDownloadClient);
  322. if (downloadResult.isSuccess()) {
  323. saveDownloadedFile();
  324. }
  325. } catch (AccountsException e) {
  326. Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  327. downloadResult = new RemoteOperationResult(e);
  328. } catch (IOException e) {
  329. Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  330. downloadResult = new RemoteOperationResult(e);
  331. } finally {
  332. synchronized(mPendingDownloads) {
  333. mPendingDownloads.remove(downloadKey);
  334. }
  335. }
  336. /// notify result
  337. notifyDownloadResult(mCurrentDownload, downloadResult);
  338. sendBroadcastDownloadFinished(mCurrentDownload, downloadResult);
  339. }
  340. }
  341. /**
  342. * Updates the OC File after a successful download.
  343. */
  344. private void saveDownloadedFile() {
  345. OCFile file = mStorageManager.getFileById(mCurrentDownload.getFile().getFileId());
  346. long syncDate = System.currentTimeMillis();
  347. file.setLastSyncDateForProperties(syncDate);
  348. file.setLastSyncDateForData(syncDate);
  349. file.setNeedsUpdateThumbnail(true);
  350. file.setModificationTimestamp(mCurrentDownload.getModificationTimestamp());
  351. file.setModificationTimestampAtLastSyncForData(mCurrentDownload.getModificationTimestamp());
  352. // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
  353. file.setMimetype(mCurrentDownload.getMimeType());
  354. file.setStoragePath(mCurrentDownload.getSavePath());
  355. file.setFileLength((new File(mCurrentDownload.getSavePath()).length()));
  356. file.setRemoteId(mCurrentDownload.getFile().getRemoteId());
  357. mStorageManager.saveFile(file);
  358. mStorageManager.triggerMediaScan(file.getStoragePath());
  359. }
  360. /**
  361. * Creates a status notification to show the download progress
  362. *
  363. * @param download Download operation starting.
  364. */
  365. private void notifyDownloadStart(DownloadFileOperation download) {
  366. /// create status notification with a progress bar
  367. mLastPercent = 0;
  368. mNotificationBuilder =
  369. NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
  370. mNotificationBuilder
  371. .setSmallIcon(R.drawable.notification_icon)
  372. .setTicker(getString(R.string.downloader_download_in_progress_ticker))
  373. .setContentTitle(getString(R.string.downloader_download_in_progress_ticker))
  374. .setOngoing(true)
  375. .setProgress(100, 0, download.getSize() < 0)
  376. .setContentText(
  377. String.format(getString(R.string.downloader_download_in_progress_content), 0,
  378. new File(download.getSavePath()).getName())
  379. );
  380. /// includes a pending intent in the notification showing the details view of the file
  381. Intent showDetailsIntent = null;
  382. if (PreviewImageFragment.canBePreviewed(download.getFile())) {
  383. showDetailsIntent = new Intent(this, PreviewImageActivity.class);
  384. } else {
  385. showDetailsIntent = new Intent(this, FileDisplayActivity.class);
  386. }
  387. showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, download.getFile());
  388. showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, download.getAccount());
  389. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  390. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
  391. this, (int) System.currentTimeMillis(), showDetailsIntent, 0
  392. ));
  393. mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
  394. }
  395. /**
  396. * Callback method to update the progress bar in the status notification.
  397. */
  398. @Override
  399. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) {
  400. int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
  401. if (percent != mLastPercent) {
  402. mNotificationBuilder.setProgress(100, percent, totalToTransfer < 0);
  403. String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
  404. String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);
  405. mNotificationBuilder.setContentText(text);
  406. mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotificationBuilder.build());
  407. }
  408. mLastPercent = percent;
  409. }
  410. /**
  411. * Updates the status notification with the result of a download operation.
  412. *
  413. * @param downloadResult Result of the download operation.
  414. * @param download Finished download operation
  415. */
  416. private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
  417. mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
  418. if (!downloadResult.isCancelled()) {
  419. int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker :
  420. R.string.downloader_download_failed_ticker;
  421. boolean needsToUpdateCredentials = (
  422. downloadResult.getCode() == ResultCode.UNAUTHORIZED ||
  423. downloadResult.isIdPRedirection()
  424. );
  425. tickerId = (needsToUpdateCredentials) ?
  426. R.string.downloader_download_failed_credentials_error : tickerId;
  427. mNotificationBuilder
  428. .setTicker(getString(tickerId))
  429. .setContentTitle(getString(tickerId))
  430. .setAutoCancel(true)
  431. .setOngoing(false)
  432. .setProgress(0, 0, false);
  433. if (needsToUpdateCredentials) {
  434. // let the user update credentials with one click
  435. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  436. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
  437. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
  438. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  439. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  440. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  441. mNotificationBuilder
  442. .setContentIntent(PendingIntent.getActivity(
  443. this, (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));
  444. mDownloadClient = null; // grant that future retries on the same account will get the fresh credentials
  445. } else {
  446. // TODO put something smart in showDetailsIntent
  447. Intent showDetailsIntent = new Intent();
  448. mNotificationBuilder
  449. .setContentIntent(PendingIntent.getActivity(
  450. this, (int) System.currentTimeMillis(), showDetailsIntent, 0));
  451. }
  452. mNotificationBuilder.setContentText(ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, getResources()));
  453. mNotificationManager.notify(tickerId, mNotificationBuilder.build());
  454. // Remove success notification
  455. if (downloadResult.isSuccess()) {
  456. // Sleep 2 seconds, so show the notification before remove it
  457. NotificationDelayer.cancelWithDelay(
  458. mNotificationManager,
  459. R.string.downloader_download_succeeded_ticker,
  460. 2000);
  461. }
  462. }
  463. }
  464. /**
  465. * Sends a broadcast when a download finishes in order to the interested activities can update their view
  466. *
  467. * @param download Finished download operation
  468. * @param downloadResult Result of the download operation
  469. */
  470. private void sendBroadcastDownloadFinished(DownloadFileOperation download, RemoteOperationResult downloadResult) {
  471. Intent end = new Intent(getDownloadFinishMessage());
  472. end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult.isSuccess());
  473. end.putExtra(ACCOUNT_NAME, download.getAccount().name);
  474. end.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
  475. end.putExtra(EXTRA_FILE_PATH, download.getSavePath());
  476. sendStickyBroadcast(end);
  477. }
  478. /**
  479. * Sends a broadcast when a new download is added to the queue.
  480. *
  481. * @param download Added download operation
  482. */
  483. private void sendBroadcastNewDownload(DownloadFileOperation download) {
  484. Intent added = new Intent(getDownloadAddedMessage());
  485. added.putExtra(ACCOUNT_NAME, download.getAccount().name);
  486. added.putExtra(EXTRA_REMOTE_PATH, download.getRemotePath());
  487. added.putExtra(EXTRA_FILE_PATH, download.getSavePath());
  488. sendStickyBroadcast(added);
  489. }
  490. /**
  491. * Cancel operation
  492. * @param account Owncloud account where the remote file is stored.
  493. * @param file File OCFile
  494. */
  495. public void cancel(Account account, OCFile file){
  496. DownloadFileOperation download = null;
  497. String targetKey = buildRemoteName(account, file);
  498. ArrayList<String> keyItems = new ArrayList<String>();
  499. synchronized (mPendingDownloads) {
  500. if (file.isFolder()) {
  501. Log_OC.d(TAG, "Folder download. Canceling pending downloads (from folder)");
  502. Iterator<String> it = mPendingDownloads.keySet().iterator();
  503. boolean found = false;
  504. while (it.hasNext()) {
  505. String keyDownloadOperation = it.next();
  506. found = keyDownloadOperation.startsWith(targetKey);
  507. if (found) {
  508. keyItems.add(keyDownloadOperation);
  509. }
  510. }
  511. } else {
  512. // this is not really expected...
  513. Log_OC.d(TAG, "Canceling file download");
  514. keyItems.add(buildRemoteName(account, file));
  515. }
  516. }
  517. for (String item: keyItems) {
  518. download = mPendingDownloads.remove(item);
  519. Log_OC.d(TAG, "Key removed: " + item);
  520. if (download != null) {
  521. download.cancel();
  522. }
  523. }
  524. }
  525. }