FileUploadService.java 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author LukeOwncloud
  5. * Copyright (C) 2015 ownCloud Inc.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2,
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package com.owncloud.android.files.services;
  21. import java.io.File;
  22. import java.io.IOException;
  23. import java.util.ArrayList;
  24. import java.util.Date;
  25. import java.util.HashMap;
  26. import java.util.Iterator;
  27. import java.util.Map;
  28. import java.util.Map.Entry;
  29. import java.util.Set;
  30. import java.util.concurrent.ConcurrentHashMap;
  31. import java.util.concurrent.ConcurrentMap;
  32. import java.util.concurrent.ExecutorService;
  33. import java.util.concurrent.Executors;
  34. import java.util.concurrent.atomic.AtomicBoolean;
  35. import android.accounts.Account;
  36. import android.accounts.AccountManager;
  37. import android.accounts.AccountsException;
  38. import android.app.NotificationManager;
  39. import android.app.PendingIntent;
  40. import android.app.Service;
  41. import android.content.Context;
  42. import android.content.Intent;
  43. import android.os.Binder;
  44. import android.os.Handler;
  45. import android.os.HandlerThread;
  46. import android.os.IBinder;
  47. import android.os.Looper;
  48. import android.os.Message;
  49. import android.os.Parcelable;
  50. import android.support.v4.app.NotificationCompat;
  51. import android.webkit.MimeTypeMap;
  52. import com.owncloud.android.R;
  53. import com.owncloud.android.authentication.AccountUtils;
  54. import com.owncloud.android.authentication.AuthenticatorActivity;
  55. import com.owncloud.android.datamodel.FileDataStorageManager;
  56. import com.owncloud.android.datamodel.OCFile;
  57. import com.owncloud.android.db.UploadDbHandler;
  58. import com.owncloud.android.db.UploadDbHandler.UploadStatus;
  59. import com.owncloud.android.db.UploadDbObject;
  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.accounts.AccountUtils.Constants;
  64. import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  65. import com.owncloud.android.lib.common.operations.OperationCancelledException;
  66. import com.owncloud.android.lib.common.operations.RemoteOperation;
  67. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  68. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  69. import com.owncloud.android.lib.common.utils.Log_OC;
  70. import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
  71. import com.owncloud.android.lib.resources.files.FileUtils;
  72. import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
  73. import com.owncloud.android.lib.resources.files.RemoteFile;
  74. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  75. import com.owncloud.android.notifications.NotificationBuilderWithProgressBar;
  76. import com.owncloud.android.notifications.NotificationDelayer;
  77. import com.owncloud.android.operations.CreateFolderOperation;
  78. import com.owncloud.android.operations.UploadFileOperation;
  79. import com.owncloud.android.operations.common.SyncOperation;
  80. import com.owncloud.android.ui.activity.FileActivity;
  81. import com.owncloud.android.ui.activity.UploadListActivity;
  82. import com.owncloud.android.utils.DisplayUtils;
  83. import com.owncloud.android.utils.ErrorMessageAdapter;
  84. import com.owncloud.android.utils.UploadUtils;
  85. import com.owncloud.android.utils.UriUtils;
  86. /**
  87. * Service for uploading files. Invoke using context.startService(...). Files to
  88. * be uploaded are stored persistently using {@link UploadDbHandler}.
  89. *
  90. * On next invocation of {@link FileUploadService} uploaded files which
  91. * previously failed will be uploaded again until either upload succeeded or a
  92. * fatal error occured.
  93. *
  94. * Every file passed to this service is uploaded. No filtering is performed.
  95. * However, Intent keys (e.g., KEY_WIFI_ONLY) are obeyed.
  96. *
  97. */
  98. public class FileUploadService extends Service implements OnDatatransferProgressListener {
  99. private volatile Looper mServiceLooper;
  100. private volatile ServiceHandler mServiceHandler;
  101. private ExecutorService uploadExecutor;
  102. public FileUploadService() {
  103. super();
  104. }
  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 ACCOUNT_NAME = "ACCOUNT_NAME";
  111. public static final String KEY_FILE = "FILE";
  112. public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
  113. public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
  114. public static final String KEY_MIME_TYPE = "MIME_TYPE";
  115. /**
  116. * Call this Service with only this Intent key if all pending uploads are to be retried.
  117. */
  118. private static final String KEY_RETRY = "KEY_RETRY";
  119. /**
  120. * Call this Service with KEY_RETRY and KEY_RETRY_REMOTE_PATH to retry
  121. * download of file identified by KEY_RETRY_REMOTE_PATH.
  122. */
  123. private static final String KEY_RETRY_REMOTE_PATH = "KEY_RETRY_REMOTE_PATH";
  124. /**
  125. * {@link Account} to which file is to be uploaded.
  126. */
  127. public static final String KEY_ACCOUNT = "ACCOUNT";
  128. /**
  129. * Set whether single file or multiple files are to be uploaded. Value must be of type {@link UploadQuantity}.
  130. */
  131. public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
  132. /**
  133. * Set to true if remote file is to be overwritten. Default action is to upload with different name.
  134. */
  135. public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
  136. /**
  137. * Set to true if remote folder is to be created if it does not exist.
  138. */
  139. public static final String KEY_CREATE_REMOTE_FOLDER = "CREATE_REMOTE_FOLDER";
  140. /**
  141. * Set to true if upload is to performed only when connected via wifi.
  142. */
  143. public static final String KEY_WIFI_ONLY = "WIFI_ONLY";
  144. /**
  145. * Set to true if upload is to performed only when phone is being charged.
  146. */
  147. public static final String KEY_WHILE_CHARGING_ONLY = "KEY_WHILE_CHARGING_ONLY";
  148. /**
  149. * Set to future UNIX timestamp. Upload will not be performed before this timestamp.
  150. */
  151. public static final String KEY_UPLOAD_TIMESTAMP= "KEY_UPLOAD_TIMESTAMP";
  152. public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
  153. /**
  154. * Describes local behavior for upload.
  155. */
  156. public enum LocalBehaviour {
  157. /**
  158. * Creates a copy of file and stores it in tmp folder inside owncloud
  159. * folder on sd-card. After upload it is moved to local owncloud
  160. * storage. Original file stays untouched.
  161. */
  162. LOCAL_BEHAVIOUR_COPY(0),
  163. /**
  164. * Upload file from current storage. Afterwards original file is move to
  165. * local owncloud storage.
  166. */
  167. LOCAL_BEHAVIOUR_MOVE(1),
  168. /**
  169. * Just uploads file and leaves it where it is. Original file stays
  170. * untouched.
  171. */
  172. LOCAL_BEHAVIOUR_FORGET(2);
  173. private final int value;
  174. LocalBehaviour(int value) {
  175. this.value = value;
  176. }
  177. public int getValue() {
  178. return value;
  179. }
  180. }
  181. public enum UploadQuantity {
  182. UPLOAD_SINGLE_FILE(0), UPLOAD_MULTIPLE_FILES(1);
  183. private final int value;
  184. UploadQuantity(int value) {
  185. this.value = value;
  186. }
  187. public int getValue() {
  188. return value;
  189. }
  190. };
  191. private static final String TAG = FileUploadService.class.getSimpleName();
  192. private IBinder mBinder;
  193. private OwnCloudClient mUploadClient = null;
  194. private Account mLastAccount = null;
  195. private FileDataStorageManager mStorageManager;
  196. //since there can be only one instance of an Android service, there also just one db connection.
  197. private UploadDbHandler mDb = null;
  198. private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
  199. private final AtomicBoolean mCancellationPossible = new AtomicBoolean(false);
  200. /**
  201. * List of uploads that are currently pending. Maps from remotePath to where file
  202. * is being uploaded to {@link UploadFileOperation}.
  203. */
  204. private ConcurrentMap<String, UploadDbObject> mPendingUploads = new ConcurrentHashMap<String, UploadDbObject>();
  205. /**
  206. * {@link UploadFileOperation} object of ongoing upload. Can be null. Note: There can only be one concurrent upload!
  207. */
  208. private UploadFileOperation mCurrentUpload = null;
  209. private NotificationManager mNotificationManager;
  210. private NotificationCompat.Builder mNotificationBuilder;
  211. private int mLastPercent;
  212. private static final String MIME_TYPE_PDF = "application/pdf";
  213. private static final String FILE_EXTENSION_PDF = ".pdf";
  214. public static String getUploadFinishMessage() {
  215. return FileUploadService.class.getName().toString() + UPLOAD_FINISH_MESSAGE;
  216. }
  217. /**
  218. * Builds a key for mPendingUploads from the account and file to upload
  219. *
  220. * @param account Account where the file to upload is stored
  221. * @param file File to upload
  222. */
  223. private String buildRemoteName(Account account, OCFile file) {
  224. return account.name + file.getRemotePath();
  225. }
  226. private String buildRemoteName(Account account, String remotePath) {
  227. return account.name + remotePath;
  228. }
  229. private String buildRemoteName(UploadDbObject uploadDbObject) {
  230. return uploadDbObject.getAccountName() + uploadDbObject.getRemotePath();
  231. }
  232. /**
  233. * Checks if an ownCloud server version should support chunked uploads.
  234. *
  235. * @param version OwnCloud version instance corresponding to an ownCloud
  236. * server.
  237. * @return 'True' if the ownCloud server with version supports chunked
  238. * uploads.
  239. */
  240. private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
  241. return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
  242. }
  243. /**
  244. * Service initialization
  245. */
  246. @Override
  247. public void onCreate() {
  248. super.onCreate();
  249. Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.size() + " - onCreate");
  250. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  251. mBinder = new FileUploaderBinder();
  252. mDb = UploadDbHandler.getInstance(this);
  253. // mDb.recreateDb(); //for testing only
  254. //when this service starts there is no upload in progress. if db says so, app probably crashed before.
  255. mDb.setAllCurrentToUploadLater();
  256. HandlerThread thread = new HandlerThread("FileUploadService-Requester");
  257. thread.start();
  258. mServiceLooper = thread.getLooper();
  259. mServiceHandler = new ServiceHandler(mServiceLooper);
  260. uploadExecutor = Executors.newFixedThreadPool(1);
  261. Log_OC.d(TAG, "FileUploadService.retry() called by onCreate()");
  262. FileUploadService.retry(getApplicationContext());
  263. }
  264. @Override
  265. public void onDestroy() {
  266. Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.size() + " - onDestroy");
  267. mServiceLooper.quit();
  268. uploadExecutor.shutdown();
  269. }
  270. private final class ServiceHandler extends Handler {
  271. public ServiceHandler(Looper looper) {
  272. super(looper);
  273. }
  274. @Override
  275. public void handleMessage(Message msg) {
  276. onHandleIntent((Intent) msg.obj, (int)msg.arg1);
  277. }
  278. }
  279. @Override
  280. public void onStart(Intent intent, int intentStartId) {
  281. Message msg = mServiceHandler.obtainMessage();
  282. msg.arg1 = intentStartId;
  283. msg.obj = intent;
  284. mServiceHandler.sendMessage(msg);
  285. }
  286. @Override
  287. public int onStartCommand(Intent intent, int flags, int startId) {
  288. onStart(intent, startId);
  289. return START_STICKY; // if service is killed by OS before calling
  290. // stopSelf(), tell OS to restart service with
  291. // null-intent.
  292. }
  293. /**
  294. * The IntentService calls this method from the default worker thread with
  295. * the intent that started the service. When this method returns,
  296. * IntentService stops the service, as appropriate.
  297. *
  298. * Note: We use an IntentService here. It does not provide simultaneous
  299. * requests, but instead internally queues them and gets them to this
  300. * onHandleIntent method one after another. This makes implementation less
  301. * error-prone but prevents files to be added to list while another upload
  302. * is active. If everything else works fine, fixing this should be a TODO.
  303. *
  304. * Entry point to add one or several files to the queue of uploads.
  305. *
  306. * New uploads are added calling to startService(), resulting in a call to
  307. * this method. This ensures the service will keep on working although the
  308. * caller activity goes away.
  309. *
  310. * First, onHandleIntent() stores all information associated with the upload
  311. * in a {@link UploadDbObject} which is stored persistently using
  312. * {@link UploadDbHandler}. Then, the oldest, pending upload from
  313. * {@link UploadDbHandler} is taken and upload is started.
  314. * @param intentStartId
  315. */
  316. protected void onHandleIntent(Intent intent, int intentStartId) {
  317. Log_OC.d(TAG, "onHandleIntent start");
  318. Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.size() + " - before adding new uploads.");
  319. if (intent == null || intent.hasExtra(KEY_RETRY)) {
  320. Log_OC.d(TAG, "Received null intent.");
  321. // service was restarted by OS or connectivity change was detected or
  322. // retry of pending upload was requested.
  323. // ==> First check persistent uploads, then perform upload.
  324. int countAddedEntries = 0;
  325. UploadDbObject[] list = mDb.getPendingUploads();
  326. for (UploadDbObject uploadDbObject : list) {
  327. Log_OC.d(TAG, "Retrieved from DB: " + uploadDbObject.toFormattedString());
  328. String uploadKey = buildRemoteName(uploadDbObject);
  329. UploadDbObject previous = mPendingUploads.putIfAbsent(uploadKey, uploadDbObject);
  330. if(previous == null) {
  331. Log_OC.d(TAG, "mPendingUploads added: " + uploadDbObject.toFormattedString());
  332. countAddedEntries++;
  333. } else {
  334. //already pending. ignore.
  335. }
  336. }
  337. Log_OC.d(TAG, "added " + countAddedEntries
  338. + " entrie(s) to mPendingUploads (this should be 0 except for the first time).");
  339. // null intent is received when charging or wifi state changes.
  340. // fake a mDb change event, so that GUI can update the reason for
  341. // LATER status of uploads.
  342. mDb.notifyObserversNow();
  343. } else {
  344. Log_OC.d(TAG, "Receive upload intent.");
  345. UploadQuantity uploadType = (UploadQuantity) intent.getSerializableExtra(KEY_UPLOAD_TYPE);
  346. if (uploadType == null) {
  347. Log_OC.e(TAG, "Incorrect or no upload type provided");
  348. return;
  349. }
  350. Account account = intent.getParcelableExtra(KEY_ACCOUNT);
  351. if (!AccountUtils.exists(account, getApplicationContext())) {
  352. Log_OC.e(TAG, "KEY_ACCOUNT no set or provided KEY_ACCOUNT does not exist");
  353. return;
  354. }
  355. OCFile[] files = null;
  356. // if KEY_FILE given, use it
  357. if (intent.hasExtra(KEY_FILE)) {
  358. if (uploadType == UploadQuantity.UPLOAD_SINGLE_FILE) {
  359. files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) };
  360. } else {
  361. files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE);
  362. }
  363. } else { // else use KEY_LOCAL_FILE and KEY_REMOTE_FILE
  364. if (!intent.hasExtra(KEY_LOCAL_FILE) || !intent.hasExtra(KEY_REMOTE_FILE)) {
  365. Log_OC.e(TAG, "Not enough information provided in intent");
  366. return;
  367. }
  368. String[] localPaths;
  369. String[] remotePaths;
  370. String[] mimeTypes;
  371. if (uploadType == UploadQuantity.UPLOAD_SINGLE_FILE) {
  372. localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
  373. remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
  374. mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
  375. } else {
  376. localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
  377. remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
  378. mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
  379. }
  380. if (localPaths.length != remotePaths.length) {
  381. Log_OC.e(TAG, "Different number of remote paths and local paths!");
  382. return;
  383. }
  384. files = new OCFile[localPaths.length];
  385. for (int i = 0; i < localPaths.length; i++) {
  386. files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i],
  387. ((mimeTypes != null) ? mimeTypes[i] : (String) null));
  388. if (files[i] == null) {
  389. Log_OC.e(TAG, "obtainNewOCFileToUpload() returned null for remotePaths[i]:" + remotePaths[i]
  390. + " and localPaths[i]:" + localPaths[i]);
  391. return;
  392. }
  393. }
  394. }
  395. // at this point variable "OCFile[] files" is loaded correctly.
  396. boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
  397. boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
  398. boolean isUseWifiOnly = intent.getBooleanExtra(KEY_WIFI_ONLY, true);
  399. boolean isWhileChargingOnly = intent.getBooleanExtra(KEY_WHILE_CHARGING_ONLY, false);
  400. long uploadTimestamp = intent.getLongExtra(KEY_UPLOAD_TIMESTAMP, -1);
  401. LocalBehaviour localAction = (LocalBehaviour) intent.getSerializableExtra(KEY_LOCAL_BEHAVIOUR);
  402. if (localAction == null)
  403. localAction = LocalBehaviour.LOCAL_BEHAVIOUR_COPY;
  404. // save always persistently path of upload, so it can be retried if
  405. // failed.
  406. for (int i = 0; i < files.length; i++) {
  407. UploadDbObject uploadObject = new UploadDbObject(files[i]);
  408. uploadObject.setAccountName(account.name);
  409. uploadObject.setForceOverwrite(forceOverwrite);
  410. uploadObject.setCreateRemoteFolder(isCreateRemoteFolder);
  411. uploadObject.setLocalAction(localAction);
  412. uploadObject.setUseWifiOnly(isUseWifiOnly);
  413. uploadObject.setWhileChargingOnly(isWhileChargingOnly);
  414. uploadObject.setUploadTimestamp(uploadTimestamp);
  415. uploadObject.setUploadStatus(UploadStatus.UPLOAD_LATER);
  416. String uploadKey = buildRemoteName(uploadObject);
  417. UploadDbObject previous = mPendingUploads.putIfAbsent(uploadKey, uploadObject);
  418. if(previous == null)
  419. {
  420. Log_OC.d(TAG, "mPendingUploads added: " + uploadObject.toFormattedString());
  421. // if upload was not queued before, we can add it to
  422. // database because the user wants the file to be uploaded.
  423. // however, it can happened that the user uploaded the same
  424. // file before in which case there is an old db entry.
  425. // delete that to be sure we have the latest one.
  426. if(mDb.removeUpload(uploadObject.getLocalPath())>0) {
  427. Log_OC.w(TAG, "There was an old DB entry " + uploadObject.getLocalPath()
  428. + " which had to be removed in order to add new one.");
  429. }
  430. boolean success = mDb.storeUpload(uploadObject);
  431. if(!success) {
  432. Log_OC.e(TAG, "Could not add upload " + uploadObject.getLocalPath()
  433. + " to database. This should not happen.");
  434. }
  435. } else {
  436. Log_OC.w(TAG, "FileUploadService got upload intent for file which is already queued: "
  437. + uploadObject.getRemotePath());
  438. // upload already pending. ignore.
  439. }
  440. }
  441. }
  442. // at this point mPendingUploads is filled.
  443. Iterator<String> it;
  444. if (intent != null && intent.getStringExtra(KEY_RETRY_REMOTE_PATH) != null) {
  445. ArrayList<String> list = new ArrayList<String>(1);
  446. String remotePath = intent.getStringExtra(KEY_RETRY_REMOTE_PATH);
  447. list.add(remotePath);
  448. it = list.iterator();
  449. // update db status for upload
  450. UploadDbObject uploadDbObject = mPendingUploads.get(remotePath);
  451. uploadDbObject.setUploadStatus(UploadStatus.UPLOAD_LATER);
  452. uploadDbObject.setLastResult(null);
  453. mDb.updateUploadStatus(uploadDbObject);
  454. Log_OC.d(TAG, "Start uploading " + remotePath);
  455. } else {
  456. it = mPendingUploads.keySet().iterator();
  457. }
  458. if (it.hasNext()) {
  459. while (it.hasNext()) {
  460. String upload = it.next();
  461. UploadDbObject uploadDbObject = mPendingUploads.get(upload);
  462. if (uploadDbObject == null) {
  463. Log_OC.e(TAG, "Cannot upload null. Fix that!");
  464. continue;
  465. }
  466. UploadTask uploadTask = new UploadTask(uploadDbObject);
  467. uploadExecutor.submit(uploadTask);
  468. }
  469. StopSelfTask stopSelfTask = new StopSelfTask(intentStartId);
  470. uploadExecutor.submit(stopSelfTask);
  471. } else {
  472. stopSelf(intentStartId);
  473. }
  474. Log_OC.d(TAG, "onHandleIntent end");
  475. }
  476. /**
  477. * Stops this services if latest intent id is intentStartId.
  478. */
  479. public class StopSelfTask implements Runnable {
  480. int intentStartId;
  481. public StopSelfTask(int intentStartId) {
  482. this.intentStartId = intentStartId;
  483. }
  484. @Override
  485. public void run() {
  486. stopSelf(intentStartId);
  487. }
  488. }
  489. /**
  490. * Tries uploading uploadDbObject, creates notifications, and updates mDb.
  491. */
  492. public class UploadTask implements Runnable {
  493. UploadDbObject uploadDbObject;
  494. public UploadTask(UploadDbObject uploadDbObject) {
  495. this.uploadDbObject = uploadDbObject;
  496. }
  497. @Override
  498. public void run() {
  499. Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.size() + " - before uploading.");
  500. switch (canUploadFileNow(uploadDbObject)) {
  501. case NOW:
  502. Log_OC.d(TAG, "Calling uploadFile for " + uploadDbObject.getRemotePath());
  503. RemoteOperationResult uploadResult = uploadFile(uploadDbObject);
  504. //TODO store renamed upload path?
  505. updateDatabaseUploadResult(uploadResult, mCurrentUpload);
  506. notifyUploadResult(uploadResult, mCurrentUpload);
  507. sendFinalBroadcast(uploadResult, mCurrentUpload);
  508. // TODO: Disable for testing of menu actions in uploads view
  509. // if (!shouldRetryFailedUpload(uploadResult)) {
  510. // Log_OC.d(TAG, "Upload with result " + uploadResult.getCode() + ": " + uploadResult.getLogMessage()
  511. // + " will be abandoned.");
  512. // mPendingUploads.remove(buildRemoteName(uploadDbObject));
  513. // }
  514. Log_OC.d(TAG, "mCurrentUpload = null");
  515. mCurrentUpload = null;
  516. break;
  517. case LATER:
  518. // Schedule retry for later upload. Delay can be due to:
  519. // KEY_WIFI_ONLY - done by ConnectivityActionReceiver
  520. // KEY_WHILE_CHARGING_ONLY - TODO add PowerConnectionReceiver
  521. // KEY_UPLOAD_TIMESTAMP - TODO use AlarmManager to wake up this service
  522. break;
  523. case FILE_GONE:
  524. mDb.updateUploadStatus(uploadDbObject.getLocalPath(), UploadStatus.UPLOAD_FAILED_GIVE_UP,
  525. new RemoteOperationResult(ResultCode.FILE_NOT_FOUND));
  526. if (mPendingUploads.remove(uploadDbObject.getRemotePath()) == null) {
  527. Log_OC.w(TAG, "Could remove " + uploadDbObject.getRemotePath()
  528. + " from mPendingUploads because it does not exist.");
  529. }
  530. break;
  531. case ERROR:
  532. Log_OC.e(TAG, "canUploadFileNow() returned ERROR. Fix that!");
  533. break;
  534. }
  535. Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.size() + " - after uploading.");
  536. }
  537. }
  538. /**
  539. * Returns the reason as String why state of uploadDbObject is LATER. If
  540. * upload state != LATER return null.
  541. */
  542. static public String getUploadLaterReason(Context context, UploadDbObject uploadDbObject) {
  543. StringBuilder reason = new StringBuilder();
  544. Date now = new Date();
  545. if (now.getTime() < uploadDbObject.getUploadTimestamp()) {
  546. reason.append("Waiting for " + DisplayUtils.unixTimeToHumanReadable(uploadDbObject.getUploadTimestamp()));
  547. }
  548. if (uploadDbObject.isUseWifiOnly() && !UploadUtils.isConnectedViaWiFi(context)) {
  549. if (reason.length() > 0) {
  550. reason.append(" and wifi connectivity");
  551. } else {
  552. reason.append("Waiting for wifi connectivity");
  553. }
  554. }
  555. if (uploadDbObject.isWhileChargingOnly() && !UploadUtils.isCharging(context)) {
  556. if (reason.length() > 0) {
  557. reason.append(" and charging");
  558. } else {
  559. reason.append("Waiting for charging");
  560. }
  561. }
  562. reason.append(".");
  563. if (reason.length() > 1) {
  564. return reason.toString();
  565. }
  566. if (uploadDbObject.getUploadStatus() == UploadStatus.UPLOAD_LATER) {
  567. return "Upload is pending and will start shortly.";
  568. }
  569. return null;
  570. }
  571. /**
  572. * Provides a binder object that clients can use to perform operations on
  573. * the queue of uploads, excepting the addition of new files.
  574. *
  575. * Implemented to perform cancellation, pause and resume of existing
  576. * uploads.
  577. */
  578. @Override
  579. public IBinder onBind(Intent arg0) {
  580. return mBinder;
  581. }
  582. /**
  583. * Called when ALL the bound clients were onbound.
  584. */
  585. @Override
  586. public boolean onUnbind(Intent intent) {
  587. ((FileUploaderBinder) mBinder).clearListeners();
  588. return false; // not accepting rebinding (default behaviour)
  589. }
  590. /**
  591. * Binder to let client components to perform operations on the queue of
  592. * uploads.
  593. *
  594. * It provides by itself the available operations.
  595. */
  596. public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
  597. /**
  598. * Map of listeners that will be reported about progress of uploads from
  599. * a {@link FileUploaderBinder} instance
  600. */
  601. private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
  602. /**
  603. * Returns ongoing upload operation. May be null.
  604. */
  605. public UploadFileOperation getCurrentUploadOperation() {
  606. return mCurrentUpload;
  607. }
  608. /**
  609. * Cancels a pending or current upload of a remote file.
  610. *
  611. * @param account Owncloud account where the remote file will be stored.
  612. * @param file A file in the queue of pending uploads
  613. */
  614. public void cancel(Account account, OCFile file) {
  615. // updating current references (i.e., uploadStatus of current
  616. // upload) is handled by updateDataseUploadResult() which is called
  617. // after upload finishes. Following cancel call makes sure that is
  618. // does finish right now.
  619. if (mCurrentUpload != null && mCurrentUpload.isUploadInProgress()) {
  620. Log_OC.d(TAG, "Calling cancel for " + file.getRemotePath() + " during upload operation.");
  621. mCurrentUpload.cancel();
  622. } else if(mCancellationPossible.get()){
  623. Log_OC.d(TAG, "Calling cancel for " + file.getRemotePath() + " during preparing for upload.");
  624. mCancellationRequested.set(true);
  625. } else {
  626. Log_OC.d(TAG, "Calling cancel for " + file.getRemotePath() + " while upload is pending.");
  627. // upload not in progress, but pending.
  628. // in this case we have to update the db here.
  629. UploadDbObject upload = mPendingUploads.remove(buildRemoteName(account, file));
  630. upload.setUploadStatus(UploadStatus.UPLOAD_CANCELLED);
  631. upload.setLastResult(new RemoteOperationResult(ResultCode.CANCELLED));
  632. // storagePath inside upload is the temporary path. file
  633. // contains the correct path used as db reference.
  634. upload.getOCFile().setStoragePath(file.getStoragePath());
  635. mDb.updateUploadStatus(upload);
  636. }
  637. }
  638. /**
  639. * Cancels a pending or current upload for an account
  640. *
  641. * @param account Owncloud accountName where the remote file will be stored.
  642. */
  643. public void cancel(Account account) {
  644. Log_OC.d(TAG, "Account= " + account.name);
  645. if (mCurrentUpload != null) {
  646. Log_OC.d(TAG, "Current Upload Account= " + mCurrentUpload.getAccount().name);
  647. if (mCurrentUpload.getAccount().name.equals(account.name)) {
  648. mCurrentUpload.cancel();
  649. }
  650. }
  651. // Cancel pending uploads
  652. cancelUploadForAccount(account.name);
  653. }
  654. public void remove(Account account, OCFile file) {
  655. UploadDbObject upload = mPendingUploads.remove(buildRemoteName(account, file));
  656. if(upload == null) {
  657. Log_OC.e(TAG, "Could not delete upload "+file+" from mPendingUploads.");
  658. }
  659. int d = mDb.removeUpload(file.getStoragePath());
  660. if(d == 0) {
  661. Log_OC.e(TAG, "Could not delete upload "+file.getStoragePath()+" from database.");
  662. }
  663. }
  664. /**
  665. * Puts upload in upload list and tell FileUploadService to upload items in list.
  666. */
  667. public void retry(Account account, UploadDbObject upload) {
  668. String uploadKey = buildRemoteName(upload);
  669. mPendingUploads.put(uploadKey, upload);
  670. FileUploadService.retry(getApplicationContext(), uploadKey);
  671. }
  672. public void clearListeners() {
  673. mBoundListeners.clear();
  674. }
  675. /**
  676. * Returns True when the file described by 'file' is being uploaded to
  677. * the ownCloud account 'account' or waiting for it
  678. *
  679. * If 'file' is a directory, returns 'true' if some of its descendant
  680. * files is uploading or waiting to upload.
  681. *
  682. * Warning: If remote file exists and !forceOverwrite the original file
  683. * is being returned here. That is, it seems as if the original file is
  684. * being updated when actually a new file is being uploaded.
  685. *
  686. * @param account Owncloud account where the remote file will be stored.
  687. * @param file A file that could be in the queue of pending uploads
  688. */
  689. public boolean isUploading(Account account, OCFile file) {
  690. if (account == null || file == null)
  691. return false;
  692. String targetKey = buildRemoteName(account, file);
  693. synchronized (mPendingUploads) {
  694. if (file.isFolder()) {
  695. // this can be slow if there are many uploads :(
  696. Iterator<String> it = mPendingUploads.keySet().iterator();
  697. boolean found = false;
  698. while (it.hasNext() && !found) {
  699. found = it.next().startsWith(targetKey);
  700. }
  701. return found;
  702. } else {
  703. return (mPendingUploads.containsKey(targetKey));
  704. }
  705. }
  706. }
  707. /**
  708. * Adds a listener interested in the progress of the upload for a
  709. * concrete file.
  710. *
  711. * @param listener Object to notify about progress of transfer.
  712. * @param account ownCloud account holding the file of interest.
  713. * @param file {@link OCFile} of interest for listener.
  714. */
  715. public void addDatatransferProgressListener(OnDatatransferProgressListener listener, Account account,
  716. OCFile file) {
  717. if (account == null || file == null || listener == null)
  718. return;
  719. String targetKey = buildRemoteName(account, file);
  720. mBoundListeners.put(targetKey, listener);
  721. }
  722. /**
  723. * Removes a listener interested in the progress of the upload for a
  724. * concrete file.
  725. *
  726. * @param listener Object to notify about progress of transfer.
  727. * @param account ownCloud account holding the file of interest.
  728. * @param file {@link OCFile} of interest for listener.
  729. */
  730. public void removeDatatransferProgressListener(OnDatatransferProgressListener listener, Account account,
  731. OCFile file) {
  732. if (account == null || file == null || listener == null)
  733. return;
  734. String targetKey = buildRemoteName(account, file);
  735. if (mBoundListeners.get(targetKey) == listener) {
  736. mBoundListeners.remove(targetKey);
  737. }
  738. }
  739. @Override
  740. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
  741. String localFileName) {
  742. Set<Entry<String, UploadDbObject>> uploads = mPendingUploads.entrySet();
  743. UploadFileOperation currentUpload = mCurrentUpload;
  744. if (currentUpload == null) {
  745. Log_OC.e(TAG, "Found no current upload with remote path " + localFileName + ". Ignore.");
  746. return;
  747. }
  748. String key = buildRemoteName(currentUpload.getAccount(), currentUpload.getFile());
  749. OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
  750. if (boundListener != null) {
  751. boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, localFileName);
  752. }
  753. }
  754. }
  755. enum CanUploadFileNowStatus {NOW, LATER, FILE_GONE, ERROR};
  756. /**
  757. * Returns true when the file may be uploaded now. This methods checks all
  758. * restraints of the passed {@link UploadDbObject}, these include
  759. * isUseWifiOnly(), check if local file exists, check if file was already
  760. * uploaded...
  761. *
  762. * If return value is CanUploadFileNowStatus.NOW, uploadFile() may be
  763. * called.
  764. *
  765. * @return CanUploadFileNowStatus.NOW is upload may proceed, <br>
  766. * CanUploadFileNowStatus.LATER if upload should be performed at a
  767. * later time, <br>
  768. * CanUploadFileNowStatus.ERROR if a severe error happened, calling
  769. * entity should remove upload from queue.
  770. *
  771. */
  772. private CanUploadFileNowStatus canUploadFileNow(UploadDbObject uploadDbObject) {
  773. if (uploadDbObject.getUploadStatus() == UploadStatus.UPLOAD_SUCCEEDED) {
  774. Log_OC.w(TAG, "Already succeeded uploadObject was again scheduled for upload. Fix that!");
  775. return CanUploadFileNowStatus.ERROR;
  776. }
  777. if (uploadDbObject.isUseWifiOnly()
  778. && !UploadUtils.isConnectedViaWiFi(getApplicationContext())) {
  779. Log_OC.d(TAG, "Do not start upload because it is wifi-only.");
  780. return CanUploadFileNowStatus.LATER;
  781. }
  782. if(uploadDbObject.isWhileChargingOnly() && !UploadUtils.isCharging(getApplicationContext())) {
  783. Log_OC.d(TAG, "Do not start upload because it is while charging only.");
  784. return CanUploadFileNowStatus.LATER;
  785. }
  786. Date now = new Date();
  787. if (now.getTime() < uploadDbObject.getUploadTimestamp()) {
  788. Log_OC.d(
  789. TAG,
  790. "Do not start upload because it is schedule for "
  791. + DisplayUtils.unixTimeToHumanReadable(uploadDbObject.getUploadTimestamp()));
  792. return CanUploadFileNowStatus.LATER;
  793. }
  794. if (!new File(uploadDbObject.getLocalPath()).exists()) {
  795. Log_OC.d(TAG, "Do not start upload because local file does not exist.");
  796. return CanUploadFileNowStatus.FILE_GONE;
  797. }
  798. return CanUploadFileNowStatus.NOW;
  799. }
  800. /**
  801. * Core upload method: sends the file(s) to upload. This function blocks
  802. * until upload succeeded or failed.
  803. *
  804. * Before uploading starts mCurrentUpload is set.
  805. *
  806. * @param uploadDbObject Key to access the upload to perform, contained in
  807. * mPendingUploads
  808. * @return RemoteOperationResult of upload operation.
  809. */
  810. private RemoteOperationResult uploadFile(UploadDbObject uploadDbObject) {
  811. if (mCurrentUpload != null) {
  812. Log_OC.e(TAG,
  813. "mCurrentUpload != null. Meaning there is another upload in progress, cannot start a new one. Fix that!");
  814. return new RemoteOperationResult(new IllegalStateException("mCurrentUpload != null when calling uploadFile()"));
  815. }
  816. AccountManager aMgr = AccountManager.get(this);
  817. Account account = uploadDbObject.getAccount(getApplicationContext());
  818. String version = aMgr.getUserData(account, Constants.KEY_OC_VERSION);
  819. OwnCloudVersion ocv = new OwnCloudVersion(version);
  820. boolean chunked = FileUploadService.chunkedUploadIsSupported(ocv);
  821. String uploadKey = null;
  822. uploadKey = buildRemoteName(account, uploadDbObject.getRemotePath());
  823. OCFile file = uploadDbObject.getOCFile();
  824. Log_OC.d(TAG, "mCurrentUpload = new UploadFileOperation");
  825. mCurrentUpload = new UploadFileOperation(account, file, chunked, uploadDbObject.isForceOverwrite(),
  826. uploadDbObject.getLocalAction(), getApplicationContext());
  827. if (uploadDbObject.isCreateRemoteFolder()) {
  828. mCurrentUpload.setRemoteFolderToBeCreated();
  829. }
  830. mCurrentUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
  831. mCurrentUpload.addDatatransferProgressListener(this);
  832. mCancellationRequested.set(false);
  833. mCancellationPossible.set(true);
  834. notifyUploadStart(mCurrentUpload);
  835. RemoteOperationResult uploadResult = null, grantResult = null;
  836. try {
  837. // prepare client object to send requests to the ownCloud
  838. // server
  839. if (mUploadClient == null || !mLastAccount.equals(mCurrentUpload.getAccount())) {
  840. mLastAccount = mCurrentUpload.getAccount();
  841. mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
  842. OwnCloudAccount ocAccount = new OwnCloudAccount(mLastAccount, this);
  843. mUploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, this);
  844. }
  845. // check the existence of the parent folder for the file to
  846. // upload
  847. String remoteParentPath = new File(mCurrentUpload.getRemotePath()).getParent();
  848. remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ? remoteParentPath : remoteParentPath
  849. + OCFile.PATH_SEPARATOR;
  850. //TODO this might take a moment and should thus be cancelable, for now: cancel afterwards.
  851. grantResult = grantFolderExistence(mCurrentUpload, remoteParentPath);
  852. if(mCancellationRequested.get()) {
  853. throw new OperationCancelledException();
  854. }
  855. mCancellationPossible.set(false);
  856. // perform the upload
  857. if (grantResult.isSuccess()) {
  858. OCFile parent = mStorageManager.getFileByPath(remoteParentPath);
  859. mCurrentUpload.getFile().setParentId(parent.getFileId());
  860. // inside this call the remote path may be changed (if remote
  861. // file exists and !forceOverwrite) in this case the map from
  862. // mPendingUploads is wrong. This results in an upload
  863. // indication in the GUI showing that the original file is being
  864. // uploaded (instead that a new one is created)
  865. uploadResult = mCurrentUpload.execute(mUploadClient);
  866. if (uploadResult.isSuccess()) {
  867. saveUploadedFile(mCurrentUpload);
  868. }
  869. } else {
  870. uploadResult = grantResult;
  871. }
  872. } catch (AccountsException e) {
  873. Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  874. uploadResult = new RemoteOperationResult(e);
  875. } catch (IOException e) {
  876. Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  877. uploadResult = new RemoteOperationResult(e);
  878. } catch (OperationCancelledException e) {
  879. uploadResult = new RemoteOperationResult(e);
  880. } finally {
  881. Log_OC.d(TAG, "Remove CurrentUploadItem from pending upload Item Map.");
  882. if (uploadResult.isException()) {
  883. // enforce the creation of a new client object for next
  884. // uploads; this grant that a new socket will
  885. // be created in the future if the current exception is due
  886. // to an abrupt lose of network connection
  887. mUploadClient = null;
  888. }
  889. }
  890. return uploadResult;
  891. }
  892. /**
  893. * Checks the existence of the folder where the current file will be
  894. * uploaded both in the remote server and in the local database.
  895. *
  896. * If the upload is set to enforce the creation of the folder, the method
  897. * tries to create it both remote and locally.
  898. *
  899. * @param pathToGrant Full remote path whose existence will be granted.
  900. * @return An {@link OCFile} instance corresponding to the folder where the
  901. * file will be uploaded.
  902. */
  903. private RemoteOperationResult grantFolderExistence(UploadFileOperation currentUpload, String pathToGrant) {
  904. RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, this, false);
  905. RemoteOperationResult result = operation.execute(mUploadClient);
  906. if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND
  907. && currentUpload.isRemoteFolderToBeCreated()) {
  908. SyncOperation syncOp = new CreateFolderOperation(pathToGrant, true);
  909. result = syncOp.execute(mUploadClient, mStorageManager);
  910. }
  911. if (result.isSuccess()) {
  912. OCFile parentDir = mStorageManager.getFileByPath(pathToGrant);
  913. if (parentDir == null) {
  914. parentDir = createLocalFolder(pathToGrant);
  915. }
  916. if (parentDir != null) {
  917. result = new RemoteOperationResult(ResultCode.OK);
  918. } else {
  919. result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  920. }
  921. }
  922. return result;
  923. }
  924. private OCFile createLocalFolder(String remotePath) {
  925. String parentPath = new File(remotePath).getParent();
  926. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
  927. OCFile parent = mStorageManager.getFileByPath(parentPath);
  928. if (parent == null) {
  929. parent = createLocalFolder(parentPath);
  930. }
  931. if (parent != null) {
  932. OCFile createdFolder = new OCFile(remotePath);
  933. createdFolder.setMimetype("DIR");
  934. createdFolder.setParentId(parent.getFileId());
  935. mStorageManager.saveFile(createdFolder);
  936. return createdFolder;
  937. }
  938. return null;
  939. }
  940. /**
  941. * Saves a OC File after a successful upload.
  942. *
  943. * A PROPFIND is necessary to keep the props in the local database
  944. * synchronized with the server, specially the modification time and Etag
  945. * (where available)
  946. *
  947. * TODO refactor this ugly thing
  948. */
  949. private void saveUploadedFile(UploadFileOperation currentUpload) {
  950. OCFile file = currentUpload.getFile();
  951. if (file.fileExists()) {
  952. file = mStorageManager.getFileById(file.getFileId());
  953. }
  954. long syncDate = System.currentTimeMillis();
  955. file.setLastSyncDateForData(syncDate);
  956. // new PROPFIND to keep data consistent with server
  957. // in theory, should return the same we already have
  958. ReadRemoteFileOperation operation = new ReadRemoteFileOperation(currentUpload.getRemotePath());
  959. RemoteOperationResult result = operation.execute(mUploadClient);
  960. if (result.isSuccess()) {
  961. updateOCFile(file, (RemoteFile) result.getData().get(0));
  962. file.setLastSyncDateForProperties(syncDate);
  963. }
  964. // / maybe this would be better as part of UploadFileOperation... or
  965. // maybe all this method
  966. if (currentUpload.wasRenamed()) {
  967. OCFile oldFile = currentUpload.getOldFile();
  968. if (oldFile.fileExists()) {
  969. oldFile.setStoragePath(null);
  970. mStorageManager.saveFile(oldFile);
  971. } // else: it was just an automatic renaming due to a name
  972. // coincidence; nothing else is needed, the storagePath is right
  973. // in the instance returned by mCurrentUpload.getFile()
  974. }
  975. file.setNeedsUpdateThumbnail(true);
  976. mStorageManager.saveFile(file);
  977. }
  978. private void updateOCFile(OCFile file, RemoteFile remoteFile) {
  979. file.setCreationTimestamp(remoteFile.getCreationTimestamp());
  980. file.setFileLength(remoteFile.getLength());
  981. file.setMimetype(remoteFile.getMimeType());
  982. file.setModificationTimestamp(remoteFile.getModifiedTimestamp());
  983. file.setModificationTimestampAtLastSyncForData(remoteFile.getModifiedTimestamp());
  984. // file.setEtag(remoteFile.getEtag()); // TODO Etag, where available
  985. file.setRemoteId(remoteFile.getRemoteId());
  986. }
  987. private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType) {
  988. // MIME type
  989. if (mimeType == null || mimeType.length() <= 0) {
  990. try {
  991. mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
  992. remotePath.substring(remotePath.lastIndexOf('.') + 1));
  993. } catch (IndexOutOfBoundsException e) {
  994. Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
  995. }
  996. }
  997. if (mimeType == null) {
  998. mimeType = "application/octet-stream";
  999. }
  1000. if (isPdfFileFromContentProviderWithoutExtension(localPath, mimeType)){
  1001. remotePath += FILE_EXTENSION_PDF;
  1002. }
  1003. OCFile newFile = new OCFile(remotePath);
  1004. newFile.setStoragePath(localPath);
  1005. newFile.setLastSyncDateForProperties(0);
  1006. newFile.setLastSyncDateForData(0);
  1007. // size
  1008. if (localPath != null && localPath.length() > 0) {
  1009. File localFile = new File(localPath);
  1010. newFile.setFileLength(localFile.length());
  1011. newFile.setLastSyncDateForData(localFile.lastModified());
  1012. } // don't worry about not assigning size, the problems with localPath
  1013. // are checked when the UploadFileOperation instance is created
  1014. newFile.setMimetype(mimeType);
  1015. return newFile;
  1016. }
  1017. /**
  1018. * Creates a status notification to show the upload progress
  1019. *
  1020. * @param upload Upload operation starting.
  1021. */
  1022. private void notifyUploadStart(UploadFileOperation upload) {
  1023. // / create status notification with a progress bar
  1024. mLastPercent = 0;
  1025. mNotificationBuilder = NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
  1026. mNotificationBuilder
  1027. .setOngoing(true)
  1028. .setSmallIcon(R.drawable.notification_icon)
  1029. .setTicker(getString(R.string.uploader_upload_in_progress_ticker))
  1030. .setContentTitle(getString(R.string.uploader_upload_in_progress_ticker))
  1031. .setProgress(100, 0, false)
  1032. .setContentText(
  1033. String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
  1034. // // / includes a pending intent in the notification showing the details
  1035. // // view of the file
  1036. // Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
  1037. // showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, (Parcelable)upload.getFile());
  1038. // showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  1039. // showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  1040. Intent showUploadListIntent = new Intent(this, UploadListActivity.class);
  1041. showUploadListIntent.putExtra(FileActivity.EXTRA_FILE, (Parcelable)upload.getFile());
  1042. showUploadListIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  1043. showUploadListIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1044. showUploadListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  1045. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
  1046. showUploadListIntent, 0));
  1047. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
  1048. updateDatabaseUploadStart(mCurrentUpload);
  1049. }
  1050. /**
  1051. * Updates the persistent upload database that upload is in progress.
  1052. */
  1053. private void updateDatabaseUploadStart(UploadFileOperation upload) {
  1054. mDb.updateUploadStatus(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_IN_PROGRESS, null);
  1055. }
  1056. /**
  1057. * Callback method to update the progress bar in the status notification
  1058. */
  1059. @Override
  1060. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath) {
  1061. int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
  1062. if (percent != mLastPercent) {
  1063. mNotificationBuilder.setProgress(100, percent, false);
  1064. String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
  1065. String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
  1066. mNotificationBuilder.setContentText(text);
  1067. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
  1068. }
  1069. mLastPercent = percent;
  1070. }
  1071. /**
  1072. * Updates the status notification with the result of an upload operation.
  1073. *
  1074. * @param uploadResult Result of the upload operation.
  1075. * @param upload Finished upload operation
  1076. */
  1077. private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
  1078. Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
  1079. // / cancelled operation or success -> silent removal of progress
  1080. // notification
  1081. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  1082. // Show the result: success or fail notification
  1083. if (!uploadResult.isCancelled()) {
  1084. int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker
  1085. : R.string.uploader_upload_failed_ticker;
  1086. String content = null;
  1087. // check credentials error
  1088. boolean needsToUpdateCredentials = (uploadResult.getCode() == ResultCode.UNAUTHORIZED || uploadResult
  1089. .isIdPRedirection());
  1090. tickerId = (needsToUpdateCredentials) ? R.string.uploader_upload_failed_credentials_error : tickerId;
  1091. mNotificationBuilder.setTicker(getString(tickerId)).setContentTitle(getString(tickerId))
  1092. .setAutoCancel(true).setOngoing(false).setProgress(0, 0, false);
  1093. content = ErrorMessageAdapter.getErrorCauseMessage(uploadResult, upload, getResources());
  1094. if (needsToUpdateCredentials) {
  1095. // let the user update credentials with one click
  1096. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  1097. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount());
  1098. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
  1099. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
  1100. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1101. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  1102. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  1103. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
  1104. updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));
  1105. mUploadClient = null;
  1106. // grant that future retries on the same account will get the
  1107. // fresh credentials
  1108. }
  1109. if(!uploadResult.isSuccess()){
  1110. //in case of failure, do not show details file view (because there is no file!)
  1111. Intent showUploadListIntent = new Intent(this, UploadListActivity.class);
  1112. showUploadListIntent.putExtra(FileActivity.EXTRA_FILE, (Parcelable)upload.getFile());
  1113. showUploadListIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  1114. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
  1115. showUploadListIntent, 0));
  1116. }
  1117. mNotificationBuilder.setContentText(content);
  1118. mNotificationManager.notify(tickerId, mNotificationBuilder.build());
  1119. if (uploadResult.isSuccess()) {
  1120. // remove success notification, with a delay of 2 seconds
  1121. NotificationDelayer.cancelWithDelay(mNotificationManager, R.string.uploader_upload_succeeded_ticker,
  1122. 2000);
  1123. }
  1124. }
  1125. }
  1126. /**
  1127. * Updates the persistent upload database with upload result.
  1128. */
  1129. private void updateDatabaseUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
  1130. // result: success or fail notification
  1131. Log_OC.d(TAG, "updateDataseUploadResult uploadResult: " + uploadResult + " upload: " + upload);
  1132. if (uploadResult.isCancelled()) {
  1133. mDb.updateUploadStatus(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_CANCELLED, uploadResult);
  1134. } else {
  1135. if (uploadResult.isSuccess()) {
  1136. mDb.updateUploadStatus(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_SUCCEEDED, uploadResult);
  1137. } else {
  1138. // TODO: Disable for testing of menu actions in uploads view
  1139. // if (shouldRetryFailedUpload(uploadResult)) {
  1140. // mDb.updateUploadStatus(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_FAILED_RETRY, uploadResult);
  1141. // } else {
  1142. // mDb.updateUploadStatus(upload.getOriginalStoragePath(),
  1143. // UploadDbHandler.UploadStatus.UPLOAD_FAILED_GIVE_UP, uploadResult);
  1144. // }
  1145. }
  1146. }
  1147. }
  1148. // TODO: Disable for testing of menu actions in uploads view
  1149. //
  1150. // /**
  1151. // * Determines whether with given uploadResult the upload should be retried later.
  1152. // * @param uploadResult
  1153. // * @return true if upload should be retried later, false if is should be abandoned.
  1154. // */
  1155. // private boolean shouldRetryFailedUpload(RemoteOperationResult uploadResult) {
  1156. // if (uploadResult.isSuccess()) {
  1157. // return false;
  1158. // }
  1159. // switch (uploadResult.getCode()) {
  1160. // case HOST_NOT_AVAILABLE:
  1161. // case NO_NETWORK_CONNECTION:
  1162. // case TIMEOUT:
  1163. // case WRONG_CONNECTION: // SocketException
  1164. // return true;
  1165. // default:
  1166. // return false;
  1167. // }
  1168. // }
  1169. /**
  1170. * Sends a broadcast in order to the interested activities can update their
  1171. * view
  1172. * @param uploadResult Result of the upload operation
  1173. * @param upload Finished upload operation
  1174. */
  1175. private void sendFinalBroadcast(RemoteOperationResult uploadResult, UploadFileOperation upload) {
  1176. Intent end = new Intent(getUploadFinishMessage());
  1177. end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  1178. // path, after
  1179. // possible
  1180. // automatic
  1181. // renaming
  1182. if (upload.wasRenamed()) {
  1183. end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
  1184. }
  1185. end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  1186. end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  1187. end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
  1188. sendStickyBroadcast(end);
  1189. }
  1190. /**
  1191. * Checks if content provider, using the content:// scheme, returns a file with mime-type
  1192. * 'application/pdf' but file has not extension
  1193. * @param localPath
  1194. * @param mimeType
  1195. * @return true if is needed to add the pdf file extension to the file
  1196. */
  1197. private boolean isPdfFileFromContentProviderWithoutExtension(String localPath, String mimeType) {
  1198. return localPath.startsWith(UriUtils.URI_CONTENT_SCHEME) &&
  1199. mimeType.equals(MIME_TYPE_PDF) &&
  1200. !localPath.endsWith(FILE_EXTENSION_PDF);
  1201. }
  1202. /**
  1203. * Remove uploads of an account
  1204. * @param accountName Name of an OC account
  1205. */
  1206. private void cancelUploadForAccount(String accountName){
  1207. // this can be slow if there are many uploads :(
  1208. Iterator<String> it = mPendingUploads.keySet().iterator();
  1209. Log_OC.d(TAG, "Number of pending updloads= " + mPendingUploads.size());
  1210. while (it.hasNext()) {
  1211. String key = it.next();
  1212. Log_OC.d(TAG, "mPendingUploads CANCELLED " + key);
  1213. if (key.startsWith(accountName)) {
  1214. synchronized (mPendingUploads) {
  1215. mPendingUploads.remove(key);
  1216. }
  1217. }
  1218. }
  1219. }
  1220. /**
  1221. * Call if all pending uploads are to be retried.
  1222. */
  1223. public static void retry(Context context) {
  1224. retry(context, null);
  1225. }
  1226. /**
  1227. * Call to retry upload identified by remotePath
  1228. */
  1229. private static void retry(Context context, String remotePath) {
  1230. Log_OC.d(TAG, "FileUploadService.retry()");
  1231. Intent i = new Intent(context, FileUploadService.class);
  1232. i.putExtra(FileUploadService.KEY_RETRY, true);
  1233. if(remotePath != null) {
  1234. i.putExtra(FileUploadService.KEY_RETRY_REMOTE_PATH, remotePath);
  1235. }
  1236. context.startService(i);
  1237. }
  1238. }