FileUploader.java 46 KB

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