FileUploader.java 46 KB

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