FileUploader.java 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author masensio
  6. * @author LukeOwnCloud
  7. * @author David A. Velasco
  8. *
  9. * Copyright (C) 2012 Bartek Przybylski
  10. * Copyright (C) 2012-2016 ownCloud Inc.
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License version 2,
  14. * as published by the Free Software Foundation.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. package com.owncloud.android.files.services;
  25. import android.accounts.Account;
  26. import android.accounts.AccountManager;
  27. import android.accounts.OnAccountsUpdateListener;
  28. import android.app.NotificationManager;
  29. import android.app.PendingIntent;
  30. import android.app.Service;
  31. import android.content.Context;
  32. import android.content.Intent;
  33. import android.os.Binder;
  34. import android.os.Handler;
  35. import android.os.HandlerThread;
  36. import android.os.IBinder;
  37. import android.os.Looper;
  38. import android.os.Message;
  39. import android.os.Parcelable;
  40. import android.os.Process;
  41. import android.support.v4.app.NotificationCompat;
  42. import android.util.Pair;
  43. import com.owncloud.android.R;
  44. import com.owncloud.android.authentication.AccountUtils;
  45. import com.owncloud.android.authentication.AuthenticatorActivity;
  46. import com.owncloud.android.datamodel.FileDataStorageManager;
  47. import com.owncloud.android.datamodel.OCFile;
  48. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  49. import com.owncloud.android.datamodel.UploadsStorageManager;
  50. import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus;
  51. import com.owncloud.android.db.OCUpload;
  52. import com.owncloud.android.db.UploadResult;
  53. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  54. import com.owncloud.android.lib.common.OwnCloudAccount;
  55. import com.owncloud.android.lib.common.OwnCloudClient;
  56. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  57. import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  58. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  59. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  60. import com.owncloud.android.lib.common.utils.Log_OC;
  61. import com.owncloud.android.lib.resources.files.FileUtils;
  62. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  63. import com.owncloud.android.ui.notifications.NotificationUtils;
  64. import com.owncloud.android.operations.UploadFileOperation;
  65. import com.owncloud.android.ui.activity.FileActivity;
  66. import com.owncloud.android.ui.activity.UploadListActivity;
  67. import com.owncloud.android.utils.ErrorMessageAdapter;
  68. import java.io.File;
  69. import java.util.AbstractList;
  70. import java.util.HashMap;
  71. import java.util.Iterator;
  72. import java.util.Map;
  73. import java.util.Vector;
  74. /**
  75. * Service for uploading files. Invoke using context.startService(...).
  76. *
  77. * Files to be uploaded are stored persistently using {@link UploadsStorageManager}.
  78. *
  79. * On next invocation of {@link FileUploader} uploaded files which
  80. * previously failed will be uploaded again until either upload succeeded or a
  81. * fatal error occured.
  82. *
  83. * Every file passed to this service is uploaded. No filtering is performed.
  84. * However, Intent keys (e.g., KEY_WIFI_ONLY) are obeyed.
  85. */
  86. public class FileUploader extends Service
  87. implements OnDatatransferProgressListener, OnAccountsUpdateListener, UploadFileOperation.OnRenameListener {
  88. private static final String TAG = FileUploader.class.getSimpleName();
  89. private static final String UPLOADS_ADDED_MESSAGE = "UPLOADS_ADDED";
  90. private static final String UPLOAD_START_MESSAGE = "UPLOAD_START";
  91. private static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
  92. public static final String EXTRA_UPLOAD_RESULT = "RESULT";
  93. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  94. public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
  95. public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
  96. public static final String EXTRA_LINKED_TO_PATH = "LINKED_TO";
  97. public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
  98. public static final String KEY_FILE = "FILE";
  99. public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
  100. public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
  101. public static final String KEY_MIME_TYPE = "MIME_TYPE";
  102. /**
  103. * Call this Service with only this Intent key if all pending uploads are to be retried.
  104. */
  105. private static final String KEY_RETRY = "KEY_RETRY";
  106. // /**
  107. // * Call this Service with KEY_RETRY and KEY_RETRY_REMOTE_PATH to retry
  108. // * upload of file identified by KEY_RETRY_REMOTE_PATH.
  109. // */
  110. // private static final String KEY_RETRY_REMOTE_PATH = "KEY_RETRY_REMOTE_PATH";
  111. /**
  112. * Call this Service with KEY_RETRY and KEY_RETRY_UPLOAD to retry
  113. * upload of file identified by KEY_RETRY_UPLOAD.
  114. */
  115. private static final String KEY_RETRY_UPLOAD = "KEY_RETRY_UPLOAD";
  116. /**
  117. * {@link Account} to which file is to be uploaded.
  118. */
  119. public static final String KEY_ACCOUNT = "ACCOUNT";
  120. /**
  121. * Set to true if remote file is to be overwritten. Default action is to upload with different name.
  122. */
  123. public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
  124. /**
  125. * Set to true if remote folder is to be created if it does not exist.
  126. */
  127. public static final String KEY_CREATE_REMOTE_FOLDER = "CREATE_REMOTE_FOLDER";
  128. /**
  129. * Key to signal what is the origin of the upload request
  130. */
  131. public static final String KEY_CREATED_BY = "CREATED_BY";
  132. /**
  133. * Set to true if upload is to performed only when phone is being charged.
  134. */
  135. public static final String KEY_WHILE_CHARGING_ONLY = "KEY_WHILE_CHARGING_ONLY";
  136. public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
  137. public static final int LOCAL_BEHAVIOUR_COPY = 0;
  138. public static final int LOCAL_BEHAVIOUR_MOVE = 1;
  139. public static final int LOCAL_BEHAVIOUR_FORGET = 2;
  140. public static final int LOCAL_BEHAVIOUR_DELETE = 3;
  141. private Looper mServiceLooper;
  142. private ServiceHandler mServiceHandler;
  143. private IBinder mBinder;
  144. private OwnCloudClient mUploadClient = null;
  145. private Account mCurrentAccount = null;
  146. private FileDataStorageManager mStorageManager;
  147. //since there can be only one instance of an Android service, there also just one db connection.
  148. private UploadsStorageManager mUploadsStorageManager = null;
  149. private IndexedForest<UploadFileOperation> mPendingUploads = new IndexedForest<UploadFileOperation>();
  150. /**
  151. * {@link UploadFileOperation} object of ongoing upload. Can be null. Note: There can only be one concurrent upload!
  152. */
  153. private UploadFileOperation mCurrentUpload = null;
  154. private NotificationManager mNotificationManager;
  155. private NotificationCompat.Builder mNotificationBuilder;
  156. private int mLastPercent;
  157. public static String getUploadsAddedMessage() {
  158. return FileUploader.class.getName() + UPLOADS_ADDED_MESSAGE;
  159. }
  160. public static String getUploadStartMessage() {
  161. return FileUploader.class.getName() + UPLOAD_START_MESSAGE;
  162. }
  163. public static String getUploadFinishMessage() {
  164. return FileUploader.class.getName() + UPLOAD_FINISH_MESSAGE;
  165. }
  166. @Override
  167. public void onRenameUpload() {
  168. mUploadsStorageManager.updateDatabaseUploadStart(mCurrentUpload);
  169. sendBroadcastUploadStarted(mCurrentUpload);
  170. }
  171. /**
  172. * Helper class providing methods to ease requesting commands to {@link FileUploader} .
  173. *
  174. * Avoids the need of checking once and again what extras are needed or optional
  175. * in the {@link Intent} to pass to {@link Context#startService(Intent)}.
  176. */
  177. public static class UploadRequester {
  178. /**
  179. * Call to upload several new files
  180. */
  181. public void uploadNewFile(
  182. Context context,
  183. Account account,
  184. String[] localPaths,
  185. String[] remotePaths,
  186. String[] mimeTypes,
  187. Integer behaviour,
  188. Boolean createRemoteFolder,
  189. int createdBy
  190. ) {
  191. Intent intent = new Intent(context, FileUploader.class);
  192. intent.putExtra(FileUploader.KEY_ACCOUNT, account);
  193. intent.putExtra(FileUploader.KEY_LOCAL_FILE, localPaths);
  194. intent.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
  195. intent.putExtra(FileUploader.KEY_MIME_TYPE, mimeTypes);
  196. intent.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, behaviour);
  197. intent.putExtra(FileUploader.KEY_CREATE_REMOTE_FOLDER, createRemoteFolder);
  198. intent.putExtra(FileUploader.KEY_CREATED_BY, createdBy);
  199. context.startService(intent);
  200. }
  201. /**
  202. * Call to upload a new single file
  203. */
  204. public void uploadNewFile(Context context, Account account, String localPath, String remotePath, int
  205. behaviour, String mimeType, boolean createRemoteFile, int createdBy) {
  206. uploadNewFile(
  207. context,
  208. account,
  209. new String[]{localPath},
  210. new String[]{remotePath},
  211. new String[]{mimeType},
  212. behaviour,
  213. createRemoteFile,
  214. createdBy
  215. );
  216. }
  217. /**
  218. * Call to update multiple files already uploaded
  219. */
  220. public void uploadUpdate(Context context, Account account, OCFile[] existingFiles, Integer behaviour,
  221. Boolean forceOverwrite) {
  222. Intent intent = new Intent(context, FileUploader.class);
  223. intent.putExtra(FileUploader.KEY_ACCOUNT, account);
  224. intent.putExtra(FileUploader.KEY_FILE, existingFiles);
  225. intent.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, behaviour);
  226. intent.putExtra(FileUploader.KEY_FORCE_OVERWRITE, forceOverwrite);
  227. context.startService(intent);
  228. }
  229. /**
  230. * Call to update a dingle file already uploaded
  231. */
  232. public void uploadUpdate(Context context, Account account, OCFile existingFile, Integer behaviour,
  233. Boolean forceOverwrite) {
  234. uploadUpdate(context, account, new OCFile[]{existingFile}, behaviour, forceOverwrite);
  235. }
  236. /**
  237. * Call to retry upload identified by remotePath
  238. */
  239. public void retry (Context context, OCUpload upload) {
  240. if (upload != null && context != null) {
  241. Account account = AccountUtils.getOwnCloudAccountByName(
  242. context,
  243. upload.getAccountName()
  244. );
  245. retry(context, account, upload);
  246. } else {
  247. throw new IllegalArgumentException("Null parameter!");
  248. }
  249. }
  250. /**
  251. * Retry a subset of all the stored failed uploads.
  252. *
  253. * @param context Caller {@link Context}
  254. * @param account If not null, only failed uploads to this OC account will be retried; otherwise,
  255. * uploads of all accounts will be retried.
  256. * @param uploadResult If not null, only failed uploads with the result specified will be retried;
  257. * otherwise, failed uploads due to any result will be retried.
  258. */
  259. public void retryFailedUploads(Context context, Account account, UploadResult uploadResult) {
  260. UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(context.getContentResolver(), context);
  261. OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads();
  262. Account currentAccount = null;
  263. boolean resultMatch, accountMatch;
  264. for ( OCUpload failedUpload: failedUploads) {
  265. accountMatch = (account == null || account.name.equals(failedUpload.getAccountName()));
  266. resultMatch = (uploadResult == null || uploadResult.equals(failedUpload.getLastResult()));
  267. if (accountMatch && resultMatch) {
  268. if (currentAccount == null ||
  269. !currentAccount.name.equals(failedUpload.getAccountName())) {
  270. currentAccount = failedUpload.getAccount(context);
  271. }
  272. retry(context, currentAccount, failedUpload);
  273. }
  274. }
  275. }
  276. /**
  277. * Private implementation of retry.
  278. *
  279. * @param context
  280. * @param account
  281. * @param upload
  282. */
  283. private void retry(Context context, Account account, OCUpload upload) {
  284. if (upload != null) {
  285. Intent i = new Intent(context, FileUploader.class);
  286. i.putExtra(FileUploader.KEY_RETRY, true);
  287. i.putExtra(FileUploader.KEY_ACCOUNT, account);
  288. i.putExtra(FileUploader.KEY_RETRY_UPLOAD, upload);
  289. context.startService(i);
  290. }
  291. }
  292. }
  293. /**
  294. * Service initialization
  295. */
  296. @Override
  297. public void onCreate() {
  298. super.onCreate();
  299. Log_OC.d(TAG, "Creating service");
  300. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  301. HandlerThread thread = new HandlerThread("FileUploaderThread",
  302. Process.THREAD_PRIORITY_BACKGROUND);
  303. thread.start();
  304. mServiceLooper = thread.getLooper();
  305. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  306. mBinder = new FileUploaderBinder();
  307. mUploadsStorageManager = new UploadsStorageManager(getContentResolver(), getApplicationContext());
  308. int failedCounter = mUploadsStorageManager.failInProgressUploads(
  309. UploadResult.SERVICE_INTERRUPTED // Add UploadResult.KILLED?
  310. );
  311. if (failedCounter > 0) {
  312. resurrection();
  313. }
  314. // add AccountsUpdatedListener
  315. AccountManager am = AccountManager.get(getApplicationContext());
  316. am.addOnAccountsUpdatedListener(this, null, false);
  317. }
  318. /**
  319. * Service clean-up when restarted after being killed
  320. */
  321. private void resurrection() {
  322. // remove stucked notification
  323. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  324. }
  325. /**
  326. * Service clean up
  327. */
  328. @Override
  329. public void onDestroy() {
  330. Log_OC.v(TAG, "Destroying service");
  331. mBinder = null;
  332. mServiceHandler = null;
  333. mServiceLooper.quit();
  334. mServiceLooper = null;
  335. mNotificationManager = null;
  336. // remove AccountsUpdatedListener
  337. AccountManager am = AccountManager.get(getApplicationContext());
  338. am.removeOnAccountsUpdatedListener(this);
  339. super.onDestroy();
  340. }
  341. /**
  342. * Entry point to add one or several files to the queue of uploads.
  343. *
  344. * New uploads are added calling to startService(), resulting in a call to
  345. * this method. This ensures the service will keep on working although the
  346. * caller activity goes away.
  347. */
  348. @Override
  349. public int onStartCommand(Intent intent, int flags, int startId) {
  350. Log_OC.d(TAG, "Starting command with id " + startId);
  351. boolean retry = intent.getBooleanExtra(KEY_RETRY, false);
  352. AbstractList<String> requestedUploads = new Vector<String>();
  353. if (!intent.hasExtra(KEY_ACCOUNT)) {
  354. Log_OC.e(TAG, "Not enough information provided in intent");
  355. return Service.START_NOT_STICKY;
  356. }
  357. Account account = intent.getParcelableExtra(KEY_ACCOUNT);
  358. if (!AccountUtils.exists(account, getApplicationContext())) {
  359. return Service.START_NOT_STICKY;
  360. }
  361. OwnCloudVersion ocv = AccountUtils.getServerVersion(account);
  362. boolean chunked = ocv.isChunkedUploadSupported();
  363. if (!retry) {
  364. if (!(intent.hasExtra(KEY_LOCAL_FILE) ||
  365. intent.hasExtra(KEY_FILE))) {
  366. Log_OC.e(TAG, "Not enough information provided in intent");
  367. return Service.START_NOT_STICKY;
  368. }
  369. String[] localPaths = null, remotePaths = null, mimeTypes = null;
  370. OCFile[] files = null;
  371. if (intent.hasExtra(KEY_FILE)) {
  372. Parcelable[] files_temp = intent.getParcelableArrayExtra(KEY_FILE);
  373. files = new OCFile[files_temp.length];
  374. System.arraycopy(files_temp, 0, files, 0, files_temp.length);
  375. } else {
  376. localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
  377. remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
  378. mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
  379. }
  380. boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
  381. int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_FORGET);
  382. boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
  383. int createdBy = intent.getIntExtra(KEY_CREATED_BY, UploadFileOperation.CREATED_BY_USER);
  384. if (intent.hasExtra(KEY_FILE) && files == null) {
  385. Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
  386. return Service.START_NOT_STICKY;
  387. } else if (!intent.hasExtra(KEY_FILE)) {
  388. if (localPaths == null) {
  389. Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent");
  390. return Service.START_NOT_STICKY;
  391. }
  392. if (remotePaths == null) {
  393. Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent");
  394. return Service.START_NOT_STICKY;
  395. }
  396. if (localPaths.length != remotePaths.length) {
  397. Log_OC.e(TAG, "Different number of remote paths and local paths!");
  398. return Service.START_NOT_STICKY;
  399. }
  400. files = new OCFile[localPaths.length];
  401. for (int i = 0; i < localPaths.length; i++) {
  402. files[i] = UploadFileOperation.obtainNewOCFileToUpload(
  403. remotePaths[i],
  404. localPaths[i],
  405. ((mimeTypes != null) ? mimeTypes[i] : null)
  406. );
  407. if (files[i] == null) {
  408. Log_OC.e(TAG, "obtainNewOCFileToUpload() returned null for remotePaths[i]:" + remotePaths[i]
  409. + " and localPaths[i]:" + localPaths[i]);
  410. return Service.START_NOT_STICKY;
  411. }
  412. }
  413. }
  414. // at this point variable "OCFile[] files" is loaded correctly.
  415. String uploadKey = null;
  416. UploadFileOperation newUpload = null;
  417. try {
  418. for (int i = 0; i < files.length; i++) {
  419. OCUpload ocUpload = new OCUpload(files[i], account);
  420. ocUpload.setFileSize(files[i].getFileLength());
  421. ocUpload.setForceOverwrite(forceOverwrite);
  422. ocUpload.setCreateRemoteFolder(isCreateRemoteFolder);
  423. ocUpload.setCreatedBy(createdBy);
  424. ocUpload.setLocalAction(localAction);
  425. /*ocUpload.setUseWifiOnly(isUseWifiOnly);
  426. ocUpload.setWhileChargingOnly(isWhileChargingOnly);*/
  427. ocUpload.setUploadStatus(UploadStatus.UPLOAD_IN_PROGRESS);
  428. newUpload = new UploadFileOperation(
  429. account,
  430. files[i],
  431. ocUpload,
  432. chunked,
  433. forceOverwrite,
  434. localAction,
  435. this
  436. );
  437. newUpload.setCreatedBy(createdBy);
  438. if (isCreateRemoteFolder) {
  439. newUpload.setRemoteFolderToBeCreated();
  440. }
  441. newUpload.addDatatransferProgressListener(this);
  442. newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
  443. newUpload.addRenameUploadListener(this);
  444. Pair<String, String> putResult = mPendingUploads.putIfAbsent(
  445. account.name,
  446. files[i].getRemotePath(),
  447. newUpload
  448. );
  449. if (putResult != null) {
  450. uploadKey = putResult.first;
  451. requestedUploads.add(uploadKey);
  452. // Save upload in database
  453. long id = mUploadsStorageManager.storeUpload(ocUpload);
  454. newUpload.setOCUploadId(id);
  455. }
  456. }
  457. } catch (IllegalArgumentException e) {
  458. Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  459. return START_NOT_STICKY;
  460. } catch (IllegalStateException e) {
  461. Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
  462. return START_NOT_STICKY;
  463. } catch (Exception e) {
  464. Log_OC.e(TAG, "Unexpected exception while processing upload intent", e);
  465. return START_NOT_STICKY;
  466. }
  467. // *** TODO REWRITE: block inserted to request A retry; too many code copied, no control exception ***/
  468. } else {
  469. if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_RETRY_UPLOAD)) {
  470. Log_OC.e(TAG, "Not enough information provided in intent: no KEY_RETRY_UPLOAD_KEY");
  471. return START_NOT_STICKY;
  472. }
  473. OCUpload upload = intent.getParcelableExtra(KEY_RETRY_UPLOAD);
  474. UploadFileOperation newUpload = new UploadFileOperation(
  475. account,
  476. null,
  477. upload,
  478. chunked,
  479. upload.isForceOverwrite(), // TODO should be read from DB?
  480. upload.getLocalAction(), // TODO should be read from DB?
  481. this
  482. );
  483. newUpload.addDatatransferProgressListener(this);
  484. newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
  485. newUpload.addRenameUploadListener(this);
  486. Pair<String, String> putResult = mPendingUploads.putIfAbsent(
  487. account.name,
  488. upload.getRemotePath(),
  489. newUpload
  490. );
  491. if (putResult != null) {
  492. String uploadKey = putResult.first;
  493. requestedUploads.add(uploadKey);
  494. // Update upload in database
  495. upload.setUploadStatus(UploadStatus.UPLOAD_IN_PROGRESS);
  496. mUploadsStorageManager.updateUpload(upload);
  497. }
  498. }
  499. // *** TODO REWRITE END ***/
  500. if (requestedUploads.size() > 0) {
  501. Message msg = mServiceHandler.obtainMessage();
  502. msg.arg1 = startId;
  503. msg.obj = requestedUploads;
  504. mServiceHandler.sendMessage(msg);
  505. sendBroadcastUploadsAdded();
  506. }
  507. return Service.START_NOT_STICKY;
  508. }
  509. /**
  510. * Provides a binder object that clients can use to perform operations on
  511. * the queue of uploads, excepting the addition of new files.
  512. *
  513. * Implemented to perform cancellation, pause and resume of existing
  514. * uploads.
  515. */
  516. @Override
  517. public IBinder onBind(Intent arg0) {
  518. return mBinder;
  519. }
  520. /**
  521. * Called when ALL the bound clients were onbound.
  522. */
  523. @Override
  524. public boolean onUnbind(Intent intent) {
  525. ((FileUploaderBinder) mBinder).clearListeners();
  526. return false; // not accepting rebinding (default behaviour)
  527. }
  528. @Override
  529. public void onAccountsUpdated(Account[] accounts) {
  530. // Review current upload, and cancel it if its account doen't exist
  531. if (mCurrentUpload != null &&
  532. !AccountUtils.exists(mCurrentUpload.getAccount(), getApplicationContext())) {
  533. mCurrentUpload.cancel();
  534. }
  535. // The rest of uploads are cancelled when they try to start
  536. }
  537. /**
  538. * Binder to let client components to perform operations on the queue of
  539. * uploads.
  540. * <p/>
  541. * It provides by itself the available operations.
  542. */
  543. public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
  544. /**
  545. * Map of listeners that will be reported about progress of uploads from a
  546. * {@link FileUploaderBinder} instance
  547. */
  548. private Map<String, OnDatatransferProgressListener> mBoundListeners =
  549. new HashMap<String, OnDatatransferProgressListener>();
  550. /**
  551. * Cancels a pending or current upload of a remote file.
  552. *
  553. * @param account ownCloud account where the remote file will be stored.
  554. * @param file A file in the queue of pending uploads
  555. */
  556. public void cancel(Account account, OCFile file) {
  557. cancel(account.name, file.getRemotePath());
  558. }
  559. /**
  560. * Cancels a pending or current upload that was persisted.
  561. *
  562. * @param storedUpload Upload operation persisted
  563. */
  564. public void cancel(OCUpload storedUpload) {
  565. cancel(storedUpload.getAccountName(), storedUpload.getRemotePath());
  566. }
  567. /**
  568. * Cancels a pending or current upload of a remote file.
  569. *
  570. * @param accountName Local name of an ownCloud account where the remote file will be stored.
  571. * @param remotePath Remote target of the upload
  572. */
  573. private void cancel(String accountName, String remotePath) {
  574. Pair<UploadFileOperation, String> removeResult =
  575. mPendingUploads.remove(accountName, remotePath);
  576. UploadFileOperation upload = removeResult.first;
  577. if (upload == null &&
  578. mCurrentUpload != null && mCurrentAccount != null &&
  579. mCurrentUpload.getRemotePath().startsWith(remotePath) &&
  580. accountName.equals(mCurrentAccount.name)) {
  581. upload = mCurrentUpload;
  582. }
  583. if (upload != null) {
  584. boolean pending = !upload.isUploadInProgress();
  585. upload.cancel();
  586. // need to update now table in mUploadsStorageManager,
  587. // since the operation will not get to be run by FileUploader#uploadFile
  588. mUploadsStorageManager.removeUpload(accountName, remotePath);
  589. } else {
  590. // try to cancel job in jobScheduler
  591. mUploadsStorageManager.cancelPendingJob(accountName, remotePath);
  592. }
  593. }
  594. /**
  595. * Cancels all the uploads for an account
  596. *
  597. * @param account ownCloud account.
  598. */
  599. public void cancel(Account account) {
  600. Log_OC.d(TAG, "Account= " + account.name);
  601. if (mCurrentUpload != null) {
  602. Log_OC.d(TAG, "Current Upload Account= " + mCurrentUpload.getAccount().name);
  603. if (mCurrentUpload.getAccount().name.equals(account.name)) {
  604. mCurrentUpload.cancel();
  605. }
  606. }
  607. // Cancel pending uploads
  608. cancelUploadsForAccount(account);
  609. }
  610. public void clearListeners() {
  611. mBoundListeners.clear();
  612. }
  613. /**
  614. * Returns True when the file described by 'file' is being uploaded to
  615. * the ownCloud account 'account' or waiting for it
  616. *
  617. * If 'file' is a directory, returns 'true' if some of its descendant files
  618. * is uploading or waiting to upload.
  619. *
  620. * Warning: If remote file exists and !forceOverwrite the original file
  621. * is being returned here. That is, it seems as if the original file is
  622. * being updated when actually a new file is being uploaded.
  623. *
  624. * @param account Owncloud account where the remote file will be stored.
  625. * @param file A file that could be in the queue of pending uploads
  626. */
  627. public boolean isUploading(Account account, OCFile file) {
  628. if (account == null || file == null) {
  629. return false;
  630. }
  631. return (mPendingUploads.contains(account.name, file.getRemotePath()));
  632. }
  633. public boolean isUploadingNow(OCUpload upload) {
  634. return (
  635. upload != null &&
  636. mCurrentAccount != null &&
  637. mCurrentUpload != null &&
  638. upload.getAccountName().equals(mCurrentAccount.name) &&
  639. upload.getRemotePath().equals(mCurrentUpload.getRemotePath())
  640. );
  641. }
  642. /**
  643. * Adds a listener interested in the progress of the upload for a concrete file.
  644. *
  645. * @param listener Object to notify about progress of transfer.
  646. * @param account ownCloud account holding the file of interest.
  647. * @param file {@link OCFile} of interest for listener.
  648. */
  649. public void addDatatransferProgressListener(
  650. OnDatatransferProgressListener listener,
  651. Account account,
  652. OCFile file
  653. ) {
  654. if (account == null || file == null || listener == null) {
  655. return;
  656. }
  657. String targetKey = buildRemoteName(account.name, file.getRemotePath());
  658. mBoundListeners.put(targetKey, listener);
  659. }
  660. /**
  661. * Adds a listener interested in the progress of the upload for a concrete file.
  662. *
  663. * @param listener Object to notify about progress of transfer.
  664. * @param ocUpload {@link OCUpload} of interest for listener.
  665. */
  666. public void addDatatransferProgressListener(
  667. OnDatatransferProgressListener listener,
  668. OCUpload ocUpload
  669. ) {
  670. if (ocUpload == null || listener == null) {
  671. return;
  672. }
  673. String targetKey = buildRemoteName(ocUpload.getAccountName(), ocUpload.getRemotePath());
  674. mBoundListeners.put(targetKey, listener);
  675. }
  676. /**
  677. * Removes a listener interested in the progress of the upload for a concrete file.
  678. *
  679. * @param listener Object to notify about progress of transfer.
  680. * @param account ownCloud account holding the file of interest.
  681. * @param file {@link OCFile} of interest for listener.
  682. */
  683. public void removeDatatransferProgressListener(
  684. OnDatatransferProgressListener listener,
  685. Account account,
  686. OCFile file
  687. ) {
  688. if (account == null || file == null || listener == null) {
  689. return;
  690. }
  691. String targetKey = buildRemoteName(account.name, file.getRemotePath());
  692. if (mBoundListeners.get(targetKey) == listener) {
  693. mBoundListeners.remove(targetKey);
  694. }
  695. }
  696. /**
  697. * Removes a listener interested in the progress of the upload for a concrete file.
  698. *
  699. * @param listener Object to notify about progress of transfer.
  700. * @param ocUpload Stored upload of interest
  701. */
  702. public void removeDatatransferProgressListener(
  703. OnDatatransferProgressListener listener,
  704. OCUpload ocUpload
  705. ) {
  706. if (ocUpload == null || listener == null) {
  707. return;
  708. }
  709. String targetKey = buildRemoteName(ocUpload.getAccountName(), ocUpload.getRemotePath());
  710. if (mBoundListeners.get(targetKey) == listener) {
  711. mBoundListeners.remove(targetKey);
  712. }
  713. }
  714. @Override
  715. public void onTransferProgress(long progressRate, long totalTransferredSoFar,
  716. long totalToTransfer, String fileName) {
  717. String key = buildRemoteName(mCurrentUpload.getAccount().name, mCurrentUpload.getFile().getRemotePath());
  718. OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
  719. if (boundListener != null) {
  720. boundListener.onTransferProgress(progressRate, totalTransferredSoFar,
  721. totalToTransfer, fileName);
  722. }
  723. }
  724. /**
  725. * Builds a key for the map of listeners.
  726. * <p/>
  727. * TODO use method in IndexedForest, or refactor both to a common place
  728. * add to local database) to better policy (add to local database, then upload)
  729. *
  730. * @param accountName Local name of the ownCloud account where the file to upload belongs.
  731. * @param remotePath Remote path to upload the file to.
  732. * @return Key
  733. */
  734. private String buildRemoteName(String accountName, String remotePath) {
  735. return accountName + remotePath;
  736. }
  737. }
  738. /**
  739. * Upload worker. Performs the pending uploads in the order they were
  740. * requested.
  741. * <p/>
  742. * Created with the Looper of a new thread, started in
  743. * {@link FileUploader#onCreate()}.
  744. */
  745. private static class ServiceHandler extends Handler {
  746. // don't make it a final class, and don't remove the static ; lint will
  747. // warn about a possible memory leak
  748. FileUploader mService;
  749. public ServiceHandler(Looper looper, FileUploader service) {
  750. super(looper);
  751. if (service == null) {
  752. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  753. }
  754. mService = service;
  755. }
  756. @Override
  757. public void handleMessage(Message msg) {
  758. @SuppressWarnings("unchecked")
  759. AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
  760. if (msg.obj != null) {
  761. Iterator<String> it = requestedUploads.iterator();
  762. while (it.hasNext()) {
  763. mService.uploadFile(it.next());
  764. }
  765. }
  766. Log_OC.d(TAG, "Stopping command after id " + msg.arg1);
  767. mService.stopSelf(msg.arg1);
  768. }
  769. }
  770. /**
  771. * Core upload method: sends the file(s) to upload
  772. *
  773. * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
  774. */
  775. public void uploadFile(String uploadKey) {
  776. mCurrentUpload = mPendingUploads.get(uploadKey);
  777. if (mCurrentUpload != null) {
  778. /// Check account existence
  779. if (!AccountUtils.exists(mCurrentUpload.getAccount(), this)) {
  780. Log_OC.w(TAG, "Account " + mCurrentUpload.getAccount().name +
  781. " does not exist anymore -> cancelling all its uploads");
  782. cancelUploadsForAccount(mCurrentUpload.getAccount());
  783. return;
  784. }
  785. /// OK, let's upload
  786. mUploadsStorageManager.updateDatabaseUploadStart(mCurrentUpload);
  787. notifyUploadStart(mCurrentUpload);
  788. sendBroadcastUploadStarted(mCurrentUpload);
  789. RemoteOperationResult uploadResult = null;
  790. try {
  791. /// prepare client object to send the request to the ownCloud server
  792. if (mCurrentAccount == null || !mCurrentAccount.equals(mCurrentUpload.getAccount())) {
  793. mCurrentAccount = mCurrentUpload.getAccount();
  794. mStorageManager = new FileDataStorageManager(
  795. mCurrentAccount,
  796. getContentResolver()
  797. );
  798. } // else, reuse storage manager from previous operation
  799. // always get client from client manager, to get fresh credentials in case of update
  800. OwnCloudAccount ocAccount = new OwnCloudAccount(
  801. mCurrentAccount,
  802. this
  803. );
  804. mUploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  805. getClientFor(ocAccount, this);
  806. /// perform the upload
  807. uploadResult = mCurrentUpload.execute(mUploadClient, mStorageManager);
  808. } catch (Exception e) {
  809. Log_OC.e(TAG, "Error uploading", e);
  810. uploadResult = new RemoteOperationResult(e);
  811. } finally {
  812. Pair<UploadFileOperation, String> removeResult;
  813. if (mCurrentUpload.wasRenamed()) {
  814. removeResult = mPendingUploads.removePayload(
  815. mCurrentAccount.name,
  816. mCurrentUpload.getOldFile().getRemotePath()
  817. );
  818. /** TODO: grant that name is also updated for mCurrentUpload.getOCUploadId */
  819. } else {
  820. removeResult = mPendingUploads.removePayload(
  821. mCurrentAccount.name,
  822. mCurrentUpload.getRemotePath()
  823. );
  824. }
  825. mUploadsStorageManager.updateDatabaseUploadResult(uploadResult, mCurrentUpload);
  826. /// notify result
  827. notifyUploadResult(mCurrentUpload, uploadResult);
  828. sendBroadcastUploadFinished(mCurrentUpload, uploadResult, removeResult.second);
  829. }
  830. // generate new Thumbnail
  831. final ThumbnailsCacheManager.ThumbnailGenerationTask task =
  832. new ThumbnailsCacheManager.ThumbnailGenerationTask(mStorageManager, mCurrentAccount);
  833. Object[] params = new Object[2];
  834. params[0] = new File(mCurrentUpload.getOriginalStoragePath());
  835. params[1] = mCurrentUpload.getFile().getRemoteId();
  836. task.execute(params);
  837. }
  838. }
  839. /**
  840. * Creates a status notification to show the upload progress
  841. *
  842. * @param upload Upload operation starting.
  843. */
  844. private void notifyUploadStart(UploadFileOperation upload) {
  845. // / create status notification with a progress bar
  846. mLastPercent = 0;
  847. mNotificationBuilder =
  848. NotificationUtils.newNotificationBuilder(this);
  849. mNotificationBuilder
  850. .setOngoing(true)
  851. .setSmallIcon(R.drawable.notification_icon)
  852. .setTicker(getString(R.string.uploader_upload_in_progress_ticker))
  853. .setContentTitle(getString(R.string.uploader_upload_in_progress_ticker))
  854. .setProgress(100, 0, false)
  855. .setContentText(
  856. String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName())
  857. );
  858. /// includes a pending intent in the notification showing the details
  859. Intent showUploadListIntent = new Intent(this, UploadListActivity.class);
  860. showUploadListIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
  861. showUploadListIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  862. showUploadListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  863. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
  864. showUploadListIntent, 0));
  865. if (!upload.isInstantPicture() && !upload.isInstantVideo()) {
  866. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
  867. } // else wait until the upload really start (onTransferProgress is called), so that if it's discarded
  868. // due to lack of Wifi, no notification is shown
  869. // TODO generalize for automated uploads
  870. }
  871. /**
  872. * Callback method to update the progress bar in the status notification
  873. */
  874. @Override
  875. public void onTransferProgress(long progressRate, long totalTransferredSoFar,
  876. long totalToTransfer, String filePath) {
  877. int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
  878. if (percent != mLastPercent) {
  879. mNotificationBuilder.setProgress(100, percent, false);
  880. String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
  881. String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
  882. mNotificationBuilder.setContentText(text);
  883. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
  884. }
  885. mLastPercent = percent;
  886. }
  887. /**
  888. * Updates the status notification with the result of an upload operation.
  889. *
  890. * @param uploadResult Result of the upload operation.
  891. * @param upload Finished upload operation
  892. */
  893. private void notifyUploadResult(UploadFileOperation upload,
  894. RemoteOperationResult uploadResult) {
  895. Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
  896. // / cancelled operation or success -> silent removal of progress notification
  897. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  898. // Show the result: success or fail notification
  899. if (!uploadResult.isCancelled() &&
  900. !ResultCode.LOCAL_FILE_NOT_FOUND.equals(uploadResult.getCode()) &&
  901. !uploadResult.getCode().equals(ResultCode.DELAYED_FOR_WIFI) &&
  902. !uploadResult.getCode().equals(ResultCode.DELAYED_FOR_CHARGING)) {
  903. int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker :
  904. R.string.uploader_upload_failed_ticker;
  905. String content;
  906. // check credentials error
  907. boolean needsToUpdateCredentials = (ResultCode.UNAUTHORIZED.equals(uploadResult.getCode()));
  908. tickerId = (needsToUpdateCredentials) ?
  909. R.string.uploader_upload_failed_credentials_error : tickerId;
  910. mNotificationBuilder
  911. .setTicker(getString(tickerId))
  912. .setContentTitle(getString(tickerId))
  913. .setAutoCancel(true)
  914. .setOngoing(false)
  915. .setProgress(0, 0, false);
  916. content = ErrorMessageAdapter.getErrorCauseMessage(
  917. uploadResult, upload, getResources()
  918. );
  919. if (needsToUpdateCredentials) {
  920. // let the user update credentials with one click
  921. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  922. updateAccountCredentials.putExtra(
  923. AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount()
  924. );
  925. updateAccountCredentials.putExtra(
  926. AuthenticatorActivity.EXTRA_ACTION,
  927. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN
  928. );
  929. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  930. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  931. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  932. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
  933. this,
  934. (int) System.currentTimeMillis(),
  935. updateAccountCredentials,
  936. PendingIntent.FLAG_ONE_SHOT
  937. ));
  938. } else {
  939. mNotificationBuilder.setContentText(content);
  940. }
  941. if (!uploadResult.isSuccess() && !needsToUpdateCredentials ) {
  942. //in case of failure, do not show details file view (because there is no file!)
  943. Intent showUploadListIntent = new Intent(this, UploadListActivity.class);
  944. showUploadListIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
  945. showUploadListIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  946. showUploadListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  947. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
  948. showUploadListIntent, 0));
  949. }
  950. mNotificationBuilder.setContentText(content);
  951. mNotificationManager.notify(tickerId, mNotificationBuilder.build());
  952. if (uploadResult.isSuccess()) {
  953. mPendingUploads.remove(upload.getAccount().name, upload.getFile().getRemotePath());
  954. // remove success notification, with a delay of 2 seconds
  955. NotificationUtils.cancelWithDelay(
  956. mNotificationManager,
  957. R.string.uploader_upload_succeeded_ticker,
  958. 2000);
  959. }
  960. }
  961. }
  962. /**
  963. * Sends a broadcast in order to the interested activities can update their
  964. * view
  965. *
  966. * TODO - no more broadcasts, replace with a callback to subscribed listeners
  967. */
  968. private void sendBroadcastUploadsAdded() {
  969. Intent start = new Intent(getUploadsAddedMessage());
  970. // nothing else needed right now
  971. sendStickyBroadcast(start);
  972. }
  973. /**
  974. * Sends a broadcast in order to the interested activities can update their
  975. * view
  976. *
  977. * TODO - no more broadcasts, replace with a callback to subscribed listeners
  978. *
  979. * @param upload Finished upload operation
  980. */
  981. private void sendBroadcastUploadStarted(
  982. UploadFileOperation upload) {
  983. Intent start = new Intent(getUploadStartMessage());
  984. start.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  985. start.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  986. start.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  987. sendStickyBroadcast(start);
  988. }
  989. /**
  990. * Sends a broadcast in order to the interested activities can update their
  991. * view
  992. *
  993. * TODO - no more broadcasts, replace with a callback to subscribed listeners
  994. *
  995. * @param upload Finished upload operation
  996. * @param uploadResult Result of the upload operation
  997. * @param unlinkedFromRemotePath Path in the uploads tree where the upload was unlinked from
  998. */
  999. private void sendBroadcastUploadFinished(
  1000. UploadFileOperation upload,
  1001. RemoteOperationResult uploadResult,
  1002. String unlinkedFromRemotePath) {
  1003. Intent end = new Intent(getUploadFinishMessage());
  1004. end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  1005. // path, after
  1006. // possible
  1007. // automatic
  1008. // renaming
  1009. if (upload.wasRenamed()) {
  1010. end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
  1011. }
  1012. end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  1013. end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  1014. end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
  1015. if (unlinkedFromRemotePath != null) {
  1016. end.putExtra(EXTRA_LINKED_TO_PATH, unlinkedFromRemotePath);
  1017. }
  1018. sendStickyBroadcast(end);
  1019. }
  1020. /**
  1021. * Remove and 'forgets' pending uploads of an account.
  1022. *
  1023. * @param account Account which uploads will be cancelled
  1024. */
  1025. private void cancelUploadsForAccount(Account account) {
  1026. mPendingUploads.remove(account.name);
  1027. mUploadsStorageManager.removeUploads(account.name);
  1028. }
  1029. }