FileUploader.java 56 KB

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