FileUploadService.java 57 KB

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