FileUploader.java 46 KB

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