FileUploader.java 56 KB

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