FileUploader.java 51 KB

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