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