FileUploader.java 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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. * Retry a subset of all the stored failed uploads.
  312. *
  313. * @param context Caller {@link Context}
  314. * @param account If not null, only failed uploads to this OC account will be retried; otherwise,
  315. * uploads of all accounts will be retried.
  316. * @param uploadResult If not null, only failed uploads with the result specified will be retried;
  317. * otherwise, failed uploads due to any result will be retried.
  318. */
  319. public void retryFailedUploads(Context context, Account account, UploadResult uploadResult) {
  320. UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(context.getContentResolver(), context);
  321. OCUpload[] failedUploads = uploadsStorageManager.getFailedUploads();
  322. Account currentAccount = null;
  323. boolean resultMatch;
  324. boolean accountMatch;
  325. for ( OCUpload failedUpload: failedUploads) {
  326. accountMatch = (account == null || account.name.equals(failedUpload.getAccountName()));
  327. resultMatch = ((uploadResult == null || uploadResult.equals(failedUpload.getLastResult())));
  328. if (accountMatch && resultMatch) {
  329. if (currentAccount == null ||
  330. !currentAccount.name.equals(failedUpload.getAccountName())) {
  331. currentAccount = failedUpload.getAccount(context);
  332. }
  333. retry(context, currentAccount, failedUpload);
  334. }
  335. }
  336. }
  337. /**
  338. * Private implementation of retry.
  339. *
  340. * @param context
  341. * @param account
  342. * @param upload
  343. */
  344. private void retry(Context context, Account account, OCUpload upload) {
  345. if (upload != null) {
  346. Intent i = new Intent(context, FileUploader.class);
  347. i.putExtra(FileUploader.KEY_RETRY, true);
  348. i.putExtra(FileUploader.KEY_ACCOUNT, account);
  349. i.putExtra(FileUploader.KEY_RETRY_UPLOAD, upload);
  350. context.startService(i);
  351. }
  352. }
  353. }
  354. /**
  355. * Service initialization
  356. */
  357. @Override
  358. public void onCreate() {
  359. super.onCreate();
  360. Log_OC.d(TAG, "Creating service");
  361. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  362. HandlerThread thread = new HandlerThread("FileUploaderThread",
  363. Process.THREAD_PRIORITY_BACKGROUND);
  364. thread.start();
  365. mServiceLooper = thread.getLooper();
  366. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  367. mBinder = new FileUploaderBinder();
  368. mUploadsStorageManager = new UploadsStorageManager(getContentResolver(), getApplicationContext());
  369. mNotification = new NotificationCompat.Builder(this).setContentTitle(getApplicationContext().
  370. getResources().getString(R.string.app_name))
  371. .build();
  372. int failedCounter = mUploadsStorageManager.failInProgressUploads(
  373. UploadResult.SERVICE_INTERRUPTED // Add UploadResult.KILLED?
  374. );
  375. if (failedCounter > 0) {
  376. resurrection();
  377. }
  378. // add AccountsUpdatedListener
  379. AccountManager am = AccountManager.get(getApplicationContext());
  380. am.addOnAccountsUpdatedListener(this, null, false);
  381. }
  382. /**
  383. * Service clean-up when restarted after being killed
  384. */
  385. private void resurrection() {
  386. // remove stucked notification
  387. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  388. }
  389. /**
  390. * Service clean up
  391. */
  392. @Override
  393. public void onDestroy() {
  394. Log_OC.v(TAG, "Destroying service");
  395. mBinder = null;
  396. mServiceHandler = null;
  397. mServiceLooper.quit();
  398. mServiceLooper = null;
  399. mNotificationManager = null;
  400. // remove AccountsUpdatedListener
  401. AccountManager am = AccountManager.get(getApplicationContext());
  402. am.removeOnAccountsUpdatedListener(this);
  403. super.onDestroy();
  404. }
  405. /**
  406. * Entry point to add one or several files to the queue of uploads.
  407. *
  408. * New uploads are added calling to startService(), resulting in a call to
  409. * this method. This ensures the service will keep on working although the
  410. * caller activity goes away.
  411. */
  412. @Override
  413. public int onStartCommand(Intent intent, int flags, int startId) {
  414. Log_OC.d(TAG, "Starting command with id " + startId);
  415. startForeground(FOREGROUND_SERVICE_ID, mNotification);
  416. boolean retry = intent.getBooleanExtra(KEY_RETRY, false);
  417. AbstractList<String> requestedUploads = new Vector<String>();
  418. if (!intent.hasExtra(KEY_ACCOUNT)) {
  419. Log_OC.e(TAG, "Not enough information provided in intent");
  420. return Service.START_NOT_STICKY;
  421. }
  422. Account account = intent.getParcelableExtra(KEY_ACCOUNT);
  423. if (!AccountUtils.exists(account, getApplicationContext())) {
  424. return Service.START_NOT_STICKY;
  425. }
  426. OwnCloudVersion ocv = AccountUtils.getServerVersion(account);
  427. boolean chunked = ocv.isChunkedUploadSupported();
  428. boolean onWifiOnly = intent.getBooleanExtra(KEY_WHILE_ON_WIFI_ONLY, false);
  429. boolean whileChargingOnly = intent.getBooleanExtra(KEY_WHILE_CHARGING_ONLY, false);
  430. if (!retry) {
  431. if (!(intent.hasExtra(KEY_LOCAL_FILE) ||
  432. intent.hasExtra(KEY_FILE))) {
  433. Log_OC.e(TAG, "Not enough information provided in intent");
  434. return Service.START_NOT_STICKY;
  435. }
  436. String[] localPaths = null;
  437. String[] remotePaths = null;
  438. String[] mimeTypes = null;
  439. OCFile[] files = null;
  440. if (intent.hasExtra(KEY_FILE)) {
  441. Parcelable[] files_temp = intent.getParcelableArrayExtra(KEY_FILE);
  442. files = new OCFile[files_temp.length];
  443. System.arraycopy(files_temp, 0, files, 0, files_temp.length);
  444. } else {
  445. localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
  446. remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
  447. mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
  448. }
  449. boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
  450. int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_FORGET);
  451. boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
  452. int createdBy = intent.getIntExtra(KEY_CREATED_BY, UploadFileOperation.CREATED_BY_USER);
  453. if (intent.hasExtra(KEY_FILE) && files == null) {
  454. Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
  455. return Service.START_NOT_STICKY;
  456. } else if (!intent.hasExtra(KEY_FILE)) {
  457. if (localPaths == null) {
  458. Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent");
  459. return Service.START_NOT_STICKY;
  460. }
  461. if (remotePaths == null) {
  462. Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent");
  463. return Service.START_NOT_STICKY;
  464. }
  465. if (localPaths.length != remotePaths.length) {
  466. Log_OC.e(TAG, "Different number of remote paths and local paths!");
  467. return Service.START_NOT_STICKY;
  468. }
  469. files = new OCFile[localPaths.length];
  470. for (int i = 0; i < localPaths.length; i++) {
  471. files[i] = UploadFileOperation.obtainNewOCFileToUpload(
  472. remotePaths[i],
  473. localPaths[i],
  474. ((mimeTypes != null) ? mimeTypes[i] : null)
  475. );
  476. if (files[i] == null) {
  477. Log_OC.e(TAG, "obtainNewOCFileToUpload() returned null for remotePaths[i]:" + remotePaths[i]
  478. + " and localPaths[i]:" + localPaths[i]);
  479. return Service.START_NOT_STICKY;
  480. }
  481. }
  482. }
  483. // at this point variable "OCFile[] files" is loaded correctly.
  484. String uploadKey = null;
  485. UploadFileOperation newUpload = null;
  486. try {
  487. for (int i = 0; i < files.length; i++) {
  488. OCUpload ocUpload = new OCUpload(files[i], account);
  489. ocUpload.setFileSize(files[i].getFileLength());
  490. ocUpload.setForceOverwrite(forceOverwrite);
  491. ocUpload.setCreateRemoteFolder(isCreateRemoteFolder);
  492. ocUpload.setCreatedBy(createdBy);
  493. ocUpload.setLocalAction(localAction);
  494. ocUpload.setUseWifiOnly(onWifiOnly);
  495. ocUpload.setWhileChargingOnly(whileChargingOnly);
  496. ocUpload.setUploadStatus(UploadStatus.UPLOAD_IN_PROGRESS);
  497. newUpload = new UploadFileOperation(
  498. account,
  499. files[i],
  500. ocUpload,
  501. chunked,
  502. forceOverwrite,
  503. localAction,
  504. this,
  505. onWifiOnly,
  506. whileChargingOnly
  507. );
  508. newUpload.setCreatedBy(createdBy);
  509. if (isCreateRemoteFolder) {
  510. newUpload.setRemoteFolderToBeCreated();
  511. }
  512. newUpload.addDatatransferProgressListener(this);
  513. newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
  514. newUpload.addRenameUploadListener(this);
  515. Pair<String, String> putResult = mPendingUploads.putIfAbsent(
  516. account.name,
  517. files[i].getRemotePath(),
  518. newUpload
  519. );
  520. if (putResult != null) {
  521. uploadKey = putResult.first;
  522. requestedUploads.add(uploadKey);
  523. // Save upload in database
  524. long id = mUploadsStorageManager.storeUpload(ocUpload);
  525. newUpload.setOCUploadId(id);
  526. }
  527. }
  528. } catch (IllegalArgumentException e) {
  529. Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  530. return START_NOT_STICKY;
  531. } catch (IllegalStateException e) {
  532. Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
  533. return START_NOT_STICKY;
  534. } catch (Exception e) {
  535. Log_OC.e(TAG, "Unexpected exception while processing upload intent", e);
  536. return START_NOT_STICKY;
  537. }
  538. // *** TODO REWRITE: block inserted to request A retry; too many code copied, no control exception ***/
  539. } else {
  540. if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_RETRY_UPLOAD)) {
  541. Log_OC.e(TAG, "Not enough information provided in intent: no KEY_RETRY_UPLOAD_KEY");
  542. return START_NOT_STICKY;
  543. }
  544. OCUpload upload = intent.getParcelableExtra(KEY_RETRY_UPLOAD);
  545. onWifiOnly = upload.isUseWifiOnly();
  546. whileChargingOnly = upload.isWhileChargingOnly();
  547. UploadFileOperation newUpload = new UploadFileOperation(
  548. account,
  549. null,
  550. upload,
  551. chunked,
  552. upload.isForceOverwrite(), // TODO should be read from DB?
  553. upload.getLocalAction(), // TODO should be read from DB?
  554. this,
  555. onWifiOnly,
  556. whileChargingOnly
  557. );
  558. newUpload.addDatatransferProgressListener(this);
  559. newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
  560. newUpload.addRenameUploadListener(this);
  561. Pair<String, String> putResult = mPendingUploads.putIfAbsent(
  562. account.name,
  563. upload.getRemotePath(),
  564. newUpload
  565. );
  566. if (putResult != null) {
  567. String uploadKey = putResult.first;
  568. requestedUploads.add(uploadKey);
  569. // Update upload in database
  570. upload.setUploadStatus(UploadStatus.UPLOAD_IN_PROGRESS);
  571. mUploadsStorageManager.updateUpload(upload);
  572. }
  573. }
  574. // *** TODO REWRITE END ***/
  575. if (requestedUploads.size() > 0) {
  576. Message msg = mServiceHandler.obtainMessage();
  577. msg.arg1 = startId;
  578. msg.obj = requestedUploads;
  579. mServiceHandler.sendMessage(msg);
  580. sendBroadcastUploadsAdded();
  581. }
  582. return Service.START_NOT_STICKY;
  583. }
  584. /**
  585. * Provides a binder object that clients can use to perform operations on
  586. * the queue of uploads, excepting the addition of new files.
  587. *
  588. * Implemented to perform cancellation, pause and resume of existing
  589. * uploads.
  590. */
  591. @Override
  592. public IBinder onBind(Intent arg0) {
  593. return mBinder;
  594. }
  595. /**
  596. * Called when ALL the bound clients were onbound.
  597. */
  598. @Override
  599. public boolean onUnbind(Intent intent) {
  600. ((FileUploaderBinder) mBinder).clearListeners();
  601. return false; // not accepting rebinding (default behaviour)
  602. }
  603. @Override
  604. public void onAccountsUpdated(Account[] accounts) {
  605. // Review current upload, and cancel it if its account doen't exist
  606. if (mCurrentUpload != null &&
  607. !AccountUtils.exists(mCurrentUpload.getAccount(), getApplicationContext())) {
  608. mCurrentUpload.cancel();
  609. }
  610. // The rest of uploads are cancelled when they try to start
  611. }
  612. /**
  613. * Binder to let client components to perform operations on the queue of uploads.
  614. *
  615. * It provides by itself the available operations.
  616. */
  617. public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
  618. /**
  619. * Map of listeners that will be reported about progress of uploads from a
  620. * {@link FileUploaderBinder} instance
  621. */
  622. private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<>();
  623. /**
  624. * Cancels a pending or current upload of a remote file.
  625. *
  626. * @param account ownCloud account where the remote file will be stored.
  627. * @param file A file in the queue of pending uploads
  628. */
  629. public void cancel(Account account, OCFile file) {
  630. cancel(account.name, file.getRemotePath(), null);
  631. }
  632. /**
  633. * Cancels a pending or current upload that was persisted.
  634. *
  635. * @param storedUpload Upload operation persisted
  636. */
  637. public void cancel(OCUpload storedUpload) {
  638. cancel(storedUpload.getAccountName(), storedUpload.getRemotePath(), null);
  639. }
  640. /**
  641. * Cancels a pending or current upload of a remote file.
  642. *
  643. * @param accountName Local name of an ownCloud account where the remote file will be stored.
  644. * @param remotePath Remote target of the upload
  645. *
  646. * Setting result code will pause rather than cancel the job
  647. */
  648. private void cancel(String accountName, String remotePath, @Nullable ResultCode resultCode ) {
  649. Pair<UploadFileOperation, String> removeResult =
  650. mPendingUploads.remove(accountName, remotePath);
  651. UploadFileOperation upload = removeResult.first;
  652. if (upload == null &&
  653. mCurrentUpload != null && mCurrentAccount != null &&
  654. mCurrentUpload.getRemotePath().startsWith(remotePath) &&
  655. accountName.equals(mCurrentAccount.name)) {
  656. upload = mCurrentUpload;
  657. }
  658. if (upload != null) {
  659. upload.cancel();
  660. // need to update now table in mUploadsStorageManager,
  661. // since the operation will not get to be run by FileUploader#uploadFile
  662. if (resultCode != null) {
  663. mUploadsStorageManager.updateDatabaseUploadResult(new RemoteOperationResult(resultCode), upload);
  664. notifyUploadResult(upload, new RemoteOperationResult(resultCode));
  665. } else {
  666. mUploadsStorageManager.removeUpload(accountName, remotePath);
  667. }
  668. }
  669. }
  670. /**
  671. * Cancels all the uploads for an account.
  672. *
  673. * @param account ownCloud account.
  674. */
  675. public void cancel(Account account) {
  676. Log_OC.d(TAG, "Account= " + account.name);
  677. if (mCurrentUpload != null) {
  678. Log_OC.d(TAG, "Current Upload Account= " + mCurrentUpload.getAccount().name);
  679. if (mCurrentUpload.getAccount().name.equals(account.name)) {
  680. mCurrentUpload.cancel();
  681. }
  682. }
  683. // Cancel pending uploads
  684. cancelUploadsForAccount(account);
  685. }
  686. public void clearListeners() {
  687. mBoundListeners.clear();
  688. }
  689. /**
  690. * Returns True when the file described by 'file' is being uploaded to
  691. * the ownCloud account 'account' or waiting for it
  692. *
  693. * If 'file' is a directory, returns 'true' if some of its descendant files
  694. * is uploading or waiting to upload.
  695. *
  696. * Warning: If remote file exists and !forceOverwrite the original file
  697. * is being returned here. That is, it seems as if the original file is
  698. * being updated when actually a new file is being uploaded.
  699. *
  700. * @param account Owncloud account where the remote file will be stored.
  701. * @param file A file that could be in the queue of pending uploads
  702. */
  703. public boolean isUploading(Account account, OCFile file) {
  704. if (account == null || file == null) {
  705. return false;
  706. }
  707. return (mPendingUploads.contains(account.name, file.getRemotePath()));
  708. }
  709. public boolean isUploadingNow(OCUpload upload) {
  710. return (
  711. upload != null &&
  712. mCurrentAccount != null &&
  713. mCurrentUpload != null &&
  714. upload.getAccountName().equals(mCurrentAccount.name) &&
  715. upload.getRemotePath().equals(mCurrentUpload.getRemotePath())
  716. );
  717. }
  718. /**
  719. * Adds a listener interested in the progress of the upload for a concrete file.
  720. *
  721. * @param listener Object to notify about progress of transfer.
  722. * @param account ownCloud account holding the file of interest.
  723. * @param file {@link OCFile} of interest for listener.
  724. */
  725. public void addDatatransferProgressListener(
  726. OnDatatransferProgressListener listener,
  727. Account account,
  728. OCFile file
  729. ) {
  730. if (account == null || file == null || listener == null) {
  731. return;
  732. }
  733. String targetKey = buildRemoteName(account.name, file.getRemotePath());
  734. mBoundListeners.put(targetKey, listener);
  735. }
  736. /**
  737. * Adds a listener interested in the progress of the upload for a concrete file.
  738. *
  739. * @param listener Object to notify about progress of transfer.
  740. * @param ocUpload {@link OCUpload} of interest for listener.
  741. */
  742. public void addDatatransferProgressListener(
  743. OnDatatransferProgressListener listener,
  744. OCUpload ocUpload
  745. ) {
  746. if (ocUpload == null || listener == null) {
  747. return;
  748. }
  749. String targetKey = buildRemoteName(ocUpload.getAccountName(), ocUpload.getRemotePath());
  750. mBoundListeners.put(targetKey, listener);
  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 account ownCloud account holding the file of interest.
  757. * @param file {@link OCFile} of interest for listener.
  758. */
  759. public void removeDatatransferProgressListener(
  760. OnDatatransferProgressListener listener,
  761. Account account,
  762. OCFile file
  763. ) {
  764. if (account == null || file == null || listener == null) {
  765. return;
  766. }
  767. String targetKey = buildRemoteName(account.name, file.getRemotePath());
  768. if (mBoundListeners.get(targetKey) == listener) {
  769. mBoundListeners.remove(targetKey);
  770. }
  771. }
  772. /**
  773. * Removes a listener interested in the progress of the upload for a concrete file.
  774. *
  775. * @param listener Object to notify about progress of transfer.
  776. * @param ocUpload Stored upload of interest
  777. */
  778. public void removeDatatransferProgressListener(
  779. OnDatatransferProgressListener listener,
  780. OCUpload ocUpload
  781. ) {
  782. if (ocUpload == null || listener == null) {
  783. return;
  784. }
  785. String targetKey = buildRemoteName(ocUpload.getAccountName(), ocUpload.getRemotePath());
  786. if (mBoundListeners.get(targetKey) == listener) {
  787. mBoundListeners.remove(targetKey);
  788. }
  789. }
  790. @Override
  791. public void onTransferProgress(long progressRate, long totalTransferredSoFar,
  792. long totalToTransfer, String fileName) {
  793. String key = buildRemoteName(mCurrentUpload.getAccount().name, mCurrentUpload.getFile().getRemotePath());
  794. OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
  795. if (boundListener != null) {
  796. boundListener.onTransferProgress(progressRate, totalTransferredSoFar,
  797. totalToTransfer, fileName);
  798. if (MainApp.getAppContext() != null) {
  799. if (mCurrentUpload.getIsWifiRequired() && !Device.getNetworkType(MainApp.getAppContext()).
  800. equals(JobRequest.NetworkType.UNMETERED)) {
  801. cancel(mCurrentUpload.getAccount().name, mCurrentUpload.getFile().getRemotePath()
  802. , ResultCode.DELAYED_FOR_WIFI);
  803. } else if (mCurrentUpload.getIsChargingRequired() &&
  804. !Device.isCharging(MainApp.getAppContext())) {
  805. cancel(mCurrentUpload.getAccount().name, mCurrentUpload.getFile().getRemotePath()
  806. , ResultCode.DELAYED_FOR_CHARGING);
  807. }
  808. }
  809. }
  810. }
  811. /**
  812. * Builds a key for the map of listeners.
  813. *
  814. * TODO use method in IndexedForest, or refactor both to a common place
  815. * add to local database) to better policy (add to local database, then upload)
  816. *
  817. * @param accountName Local name of the ownCloud account where the file to upload belongs.
  818. * @param remotePath Remote path to upload the file to.
  819. * @return Key
  820. */
  821. private String buildRemoteName(String accountName, String remotePath) {
  822. return accountName + remotePath;
  823. }
  824. }
  825. /**
  826. * Upload worker. Performs the pending uploads in the order they were
  827. * requested.
  828. *
  829. * Created with the Looper of a new thread, started in
  830. * {@link FileUploader#onCreate()}.
  831. */
  832. private static class ServiceHandler extends Handler {
  833. // don't make it a final class, and don't remove the static ; lint will
  834. // warn about a possible memory leak
  835. FileUploader mService;
  836. public ServiceHandler(Looper looper, FileUploader service) {
  837. super(looper);
  838. if (service == null) {
  839. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  840. }
  841. mService = service;
  842. }
  843. @Override
  844. public void handleMessage(Message msg) {
  845. @SuppressWarnings("unchecked")
  846. AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
  847. if (msg.obj != null) {
  848. Iterator<String> it = requestedUploads.iterator();
  849. while (it.hasNext()) {
  850. mService.uploadFile(it.next());
  851. }
  852. }
  853. Log_OC.d(TAG, "Stopping command after id " + msg.arg1);
  854. mService.stopForeground(true);
  855. mService.stopSelf(msg.arg1);
  856. }
  857. }
  858. /**
  859. * Core upload method: sends the file(s) to upload
  860. *
  861. * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
  862. */
  863. public void uploadFile(String uploadKey) {
  864. mCurrentUpload = mPendingUploads.get(uploadKey);
  865. if (mCurrentUpload != null) {
  866. /// Check account existence
  867. if (!AccountUtils.exists(mCurrentUpload.getAccount(), this)) {
  868. Log_OC.w(TAG, "Account " + mCurrentUpload.getAccount().name +
  869. " does not exist anymore -> cancelling all its uploads");
  870. cancelUploadsForAccount(mCurrentUpload.getAccount());
  871. return;
  872. }
  873. /// OK, let's upload
  874. mUploadsStorageManager.updateDatabaseUploadStart(mCurrentUpload);
  875. notifyUploadStart(mCurrentUpload);
  876. sendBroadcastUploadStarted(mCurrentUpload);
  877. RemoteOperationResult uploadResult = null;
  878. try {
  879. /// prepare client object to send the request to the ownCloud server
  880. if (mCurrentAccount == null || !mCurrentAccount.equals(mCurrentUpload.getAccount())) {
  881. mCurrentAccount = mCurrentUpload.getAccount();
  882. mStorageManager = new FileDataStorageManager(
  883. mCurrentAccount,
  884. getContentResolver()
  885. );
  886. } // else, reuse storage manager from previous operation
  887. // always get client from client manager, to get fresh credentials in case of update
  888. OwnCloudAccount ocAccount = new OwnCloudAccount(
  889. mCurrentAccount,
  890. this
  891. );
  892. mUploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  893. getClientFor(ocAccount, this);
  894. /// perform the upload
  895. uploadResult = mCurrentUpload.execute(mUploadClient, mStorageManager);
  896. } catch (Exception e) {
  897. Log_OC.e(TAG, "Error uploading", e);
  898. uploadResult = new RemoteOperationResult(e);
  899. } finally {
  900. Pair<UploadFileOperation, String> removeResult;
  901. if (mCurrentUpload.wasRenamed()) {
  902. removeResult = mPendingUploads.removePayload(
  903. mCurrentAccount.name,
  904. mCurrentUpload.getOldFile().getRemotePath()
  905. );
  906. // TODO: grant that name is also updated for mCurrentUpload.getOCUploadId
  907. } else {
  908. removeResult = mPendingUploads.removePayload(
  909. mCurrentAccount.name,
  910. mCurrentUpload.getRemotePath()
  911. );
  912. }
  913. mUploadsStorageManager.updateDatabaseUploadResult(uploadResult, mCurrentUpload);
  914. /// notify result
  915. notifyUploadResult(mCurrentUpload, uploadResult);
  916. sendBroadcastUploadFinished(mCurrentUpload, uploadResult, removeResult.second);
  917. }
  918. // generate new Thumbnail
  919. final ThumbnailsCacheManager.ThumbnailGenerationTask task =
  920. new ThumbnailsCacheManager.ThumbnailGenerationTask(mStorageManager, mCurrentAccount);
  921. Object[] params = new Object[2];
  922. params[0] = new File(mCurrentUpload.getOriginalStoragePath());
  923. params[1] = mCurrentUpload.getFile().getRemoteId();
  924. task.execute(params);
  925. }
  926. }
  927. /**
  928. * Creates a status notification to show the upload progress
  929. *
  930. * @param upload Upload operation starting.
  931. */
  932. private void notifyUploadStart(UploadFileOperation upload) {
  933. // / create status notification with a progress bar
  934. mLastPercent = 0;
  935. mNotificationBuilder = NotificationUtils.newNotificationBuilder(this);
  936. mNotificationBuilder
  937. .setOngoing(true)
  938. .setSmallIcon(R.drawable.notification_icon)
  939. .setTicker(getString(R.string.uploader_upload_in_progress_ticker))
  940. .setContentTitle(getString(R.string.uploader_upload_in_progress_ticker))
  941. .setProgress(100, 0, false)
  942. .setContentText(
  943. String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName())
  944. );
  945. /// includes a pending intent in the notification showing the details
  946. Intent showUploadListIntent = new Intent(this, UploadListActivity.class);
  947. showUploadListIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
  948. showUploadListIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  949. showUploadListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  950. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
  951. showUploadListIntent, 0));
  952. if (!upload.isInstantPicture() && !upload.isInstantVideo()) {
  953. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
  954. } // else wait until the upload really start (onTransferProgress is called), so that if it's discarded
  955. // due to lack of Wifi, no notification is shown
  956. // TODO generalize for automated uploads
  957. }
  958. /**
  959. * Callback method to update the progress bar in the status notification
  960. */
  961. @Override
  962. public void onTransferProgress(long progressRate, long totalTransferredSoFar,
  963. long totalToTransfer, String filePath) {
  964. int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
  965. if (percent != mLastPercent) {
  966. mNotificationBuilder.setProgress(100, percent, false);
  967. String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
  968. String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
  969. mNotificationBuilder.setContentText(text);
  970. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
  971. }
  972. mLastPercent = percent;
  973. }
  974. /**
  975. * Updates the status notification with the result of an upload operation.
  976. *
  977. * @param uploadResult Result of the upload operation.
  978. * @param upload Finished upload operation
  979. */
  980. private void notifyUploadResult(UploadFileOperation upload,
  981. RemoteOperationResult uploadResult) {
  982. Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
  983. // / cancelled operation or success -> silent removal of progress notification
  984. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  985. // Show the result: success or fail notification
  986. if (!uploadResult.isCancelled() &&
  987. !ResultCode.LOCAL_FILE_NOT_FOUND.equals(uploadResult.getCode()) &&
  988. !uploadResult.getCode().equals(ResultCode.DELAYED_FOR_WIFI) &&
  989. !uploadResult.getCode().equals(ResultCode.DELAYED_FOR_CHARGING) &&
  990. !uploadResult.getCode().equals(ResultCode.LOCK_FAILED) ) {
  991. int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker :
  992. R.string.uploader_upload_failed_ticker;
  993. String content;
  994. // check credentials error
  995. boolean needsToUpdateCredentials = (ResultCode.UNAUTHORIZED.equals(uploadResult.getCode()));
  996. tickerId = (needsToUpdateCredentials) ?
  997. R.string.uploader_upload_failed_credentials_error : tickerId;
  998. mNotificationBuilder
  999. .setTicker(getString(tickerId))
  1000. .setContentTitle(getString(tickerId))
  1001. .setAutoCancel(true)
  1002. .setOngoing(false)
  1003. .setProgress(0, 0, false);
  1004. content = ErrorMessageAdapter.getErrorCauseMessage(uploadResult, upload, getResources());
  1005. if (needsToUpdateCredentials) {
  1006. // let the user update credentials with one click
  1007. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  1008. updateAccountCredentials.putExtra(
  1009. AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount()
  1010. );
  1011. updateAccountCredentials.putExtra(
  1012. AuthenticatorActivity.EXTRA_ACTION,
  1013. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN
  1014. );
  1015. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1016. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  1017. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  1018. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
  1019. this,
  1020. (int) System.currentTimeMillis(),
  1021. updateAccountCredentials,
  1022. PendingIntent.FLAG_ONE_SHOT
  1023. ));
  1024. } else {
  1025. mNotificationBuilder.setContentText(content);
  1026. }
  1027. if (!uploadResult.isSuccess() && !needsToUpdateCredentials ) {
  1028. //in case of failure, do not show details file view (because there is no file!)
  1029. Intent showUploadListIntent = new Intent(this, UploadListActivity.class);
  1030. showUploadListIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
  1031. showUploadListIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  1032. showUploadListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  1033. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
  1034. showUploadListIntent, 0));
  1035. }
  1036. mNotificationBuilder.setContentText(content);
  1037. mNotificationManager.notify(tickerId, mNotificationBuilder.build());
  1038. if (uploadResult.isSuccess()) {
  1039. mPendingUploads.remove(upload.getAccount().name, upload.getFile().getRemotePath());
  1040. // remove success notification, with a delay of 2 seconds
  1041. NotificationUtils.cancelWithDelay(
  1042. mNotificationManager,
  1043. R.string.uploader_upload_succeeded_ticker,
  1044. 2000);
  1045. }
  1046. }
  1047. }
  1048. /**
  1049. * Sends a broadcast in order to the interested activities can update their
  1050. * view
  1051. *
  1052. * TODO - no more broadcasts, replace with a callback to subscribed listeners
  1053. */
  1054. private void sendBroadcastUploadsAdded() {
  1055. Intent start = new Intent(getUploadsAddedMessage());
  1056. // nothing else needed right now
  1057. start.setPackage(getPackageName());
  1058. sendStickyBroadcast(start);
  1059. }
  1060. /**
  1061. * Sends a broadcast in order to the interested activities can update their
  1062. * view
  1063. *
  1064. * TODO - no more broadcasts, replace with a callback to subscribed listeners
  1065. *
  1066. * @param upload Finished upload operation
  1067. */
  1068. private void sendBroadcastUploadStarted(
  1069. UploadFileOperation upload) {
  1070. Intent start = new Intent(getUploadStartMessage());
  1071. start.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  1072. start.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  1073. start.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  1074. start.setPackage(getPackageName());
  1075. sendStickyBroadcast(start);
  1076. }
  1077. /**
  1078. * Sends a broadcast in order to the interested activities can update their
  1079. * view
  1080. *
  1081. * TODO - no more broadcasts, replace with a callback to subscribed listeners
  1082. *
  1083. * @param upload Finished upload operation
  1084. * @param uploadResult Result of the upload operation
  1085. * @param unlinkedFromRemotePath Path in the uploads tree where the upload was unlinked from
  1086. */
  1087. private void sendBroadcastUploadFinished(
  1088. UploadFileOperation upload,
  1089. RemoteOperationResult uploadResult,
  1090. String unlinkedFromRemotePath) {
  1091. Intent end = new Intent(getUploadFinishMessage());
  1092. end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  1093. // path, after
  1094. // possible
  1095. // automatic
  1096. // renaming
  1097. if (upload.wasRenamed()) {
  1098. end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
  1099. }
  1100. end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  1101. end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  1102. end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
  1103. if (unlinkedFromRemotePath != null) {
  1104. end.putExtra(EXTRA_LINKED_TO_PATH, unlinkedFromRemotePath);
  1105. }
  1106. end.setPackage(getPackageName());
  1107. sendStickyBroadcast(end);
  1108. }
  1109. /**
  1110. * Remove and 'forgets' pending uploads of an account.
  1111. *
  1112. * @param account Account which uploads will be cancelled
  1113. */
  1114. private void cancelUploadsForAccount(Account account) {
  1115. mPendingUploads.remove(account.name);
  1116. mUploadsStorageManager.removeUploads(account.name);
  1117. }
  1118. }