FileUploader.java 53 KB

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