FileUploadService.java 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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.AbstractList;
  22. import java.util.HashMap;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Map.Entry;
  27. import java.util.Set;
  28. import java.util.Vector;
  29. import java.util.concurrent.ConcurrentHashMap;
  30. import java.util.concurrent.ConcurrentMap;
  31. import android.accounts.Account;
  32. import android.accounts.AccountManager;
  33. import android.accounts.AccountsException;
  34. import android.app.NotificationManager;
  35. import android.app.PendingIntent;
  36. import android.app.Service;
  37. import android.content.BroadcastReceiver;
  38. import android.content.Context;
  39. import android.content.Intent;
  40. import android.content.IntentFilter;
  41. import android.net.ConnectivityManager;
  42. import android.os.Binder;
  43. import android.os.Handler;
  44. import android.os.HandlerThread;
  45. import android.os.IBinder;
  46. import android.os.Looper;
  47. import android.os.Message;
  48. import android.os.Process;
  49. import android.support.v4.app.NotificationCompat;
  50. import android.webkit.MimeTypeMap;
  51. import com.owncloud.android.R;
  52. import com.owncloud.android.authentication.AccountUtils;
  53. import com.owncloud.android.authentication.AuthenticatorActivity;
  54. import com.owncloud.android.datamodel.FileDataStorageManager;
  55. import com.owncloud.android.datamodel.OCFile;
  56. import com.owncloud.android.db.UploadDbHandler;
  57. import com.owncloud.android.db.UploadDbHandler.UploadStatus;
  58. import com.owncloud.android.db.UploadDbObject;
  59. import com.owncloud.android.files.InstantUploadBroadcastReceiver;
  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.RemoteOperation;
  66. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  67. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  68. import com.owncloud.android.lib.common.utils.Log_OC;
  69. import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
  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.utils.ErrorMessageAdapter;
  81. import com.owncloud.android.utils.UriUtils;
  82. /**
  83. * Service for uploading files. Invoke using context.startService(...). This
  84. * service retries until upload succeeded. Files to be uploaded are stored
  85. * persistent using {@link UploadDbHandler}.
  86. *
  87. * @author LukeOwncloud
  88. *
  89. */
  90. @SuppressWarnings("unused")
  91. public class FileUploadService extends Service {
  92. private static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
  93. public static final String EXTRA_UPLOAD_RESULT = "RESULT";
  94. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  95. public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
  96. public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
  97. public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
  98. public static final String KEY_FILE = "FILE";
  99. public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
  100. public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
  101. public static final String KEY_MIME_TYPE = "MIME_TYPE";
  102. public static final String KEY_ACCOUNT = "ACCOUNT";
  103. public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
  104. public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
  105. public static final String KEY_CREATE_REMOTE_FOLDER = "CREATE_REMOTE_FOLDER";
  106. public static final String KEY_WIFI_ONLY = "WIFI_ONLY";
  107. public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
  108. /**
  109. * Describes local behavior for upload.
  110. */
  111. public enum LocalBehaviour {
  112. /**
  113. * Creates a copy of file and stores it in tmp folder inside owncloud
  114. * folder on sd-card. After upload it is moved to local owncloud
  115. * storage. Original file stays untouched.
  116. */
  117. LOCAL_BEHAVIOUR_COPY(0),
  118. /**
  119. * Upload file from current storage. Afterwards original file is move to
  120. * local owncloud storage.
  121. */
  122. LOCAL_BEHAVIOUR_MOVE(1),
  123. /**
  124. * Just uploads file and leaves it where it is. Original file stays
  125. * untouched.
  126. */
  127. LOCAL_BEHAVIOUR_FORGET(2);
  128. private final int value;
  129. private LocalBehaviour(int value) {
  130. this.value = value;
  131. }
  132. public int getValue() {
  133. return value;
  134. }
  135. }
  136. public enum UploadSingleMulti {
  137. UPLOAD_SINGLE_FILE(0), UPLOAD_MULTIPLE_FILES(1);
  138. private final int value;
  139. private UploadSingleMulti(int value) {
  140. this.value = value;
  141. }
  142. public int getValue() {
  143. return value;
  144. }
  145. };
  146. // public static final int UPLOAD_SINGLE_FILE = 0;
  147. // public static final int UPLOAD_MULTIPLE_FILES = 1;
  148. private static final String TAG = FileUploadService.class.getSimpleName();
  149. private Looper mServiceLooper;
  150. private ServiceHandler mServiceHandler;
  151. private IBinder mBinder;
  152. private ConnectivityChangeReceiver mConnectivityChangeReceiver;
  153. private OwnCloudClient mUploadClient = null;
  154. private Account mLastAccount = null;
  155. private FileDataStorageManager mStorageManager;
  156. //since there can be only one instance of an Android service, there also just one db connection.
  157. private UploadDbHandler mDb = null;
  158. /**
  159. * List of uploads that currently in progress. Maps from remotePath to where file
  160. * is being uploaded to {@link UploadFileOperation}.
  161. */
  162. private ConcurrentMap<String, UploadFileOperation> mActiveUploads = new ConcurrentHashMap<String, UploadFileOperation>();
  163. private NotificationManager mNotificationManager;
  164. private NotificationCompat.Builder mNotificationBuilder;
  165. private static final String MIME_TYPE_PDF = "application/pdf";
  166. private static final String FILE_EXTENSION_PDF = ".pdf";
  167. public static String getUploadFinishMessage() {
  168. return FileUploadService.class.getName().toString() + UPLOAD_FINISH_MESSAGE;
  169. }
  170. /**
  171. * Builds a key for mPendingUploads from the account and file to upload
  172. *
  173. * @param account Account where the file to upload is stored
  174. * @param file File to upload
  175. */
  176. private String buildRemoteName(Account account, OCFile file) {
  177. return account.name + file.getRemotePath();
  178. }
  179. private String buildRemoteName(Account account, String remotePath) {
  180. return account.name + remotePath;
  181. }
  182. /**
  183. * Checks if an ownCloud server version should support chunked uploads.
  184. *
  185. * @param version OwnCloud version instance corresponding to an ownCloud
  186. * server.
  187. * @return 'True' if the ownCloud server with version supports chunked
  188. * uploads.
  189. */
  190. private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
  191. return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
  192. }
  193. /**
  194. * Service initialization
  195. */
  196. @Override
  197. public void onCreate() {
  198. super.onCreate();
  199. Log_OC.i(TAG, "mPendingUploads size:" + mActiveUploads.size());
  200. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  201. HandlerThread thread = new HandlerThread("FileUploaderThread", Process.THREAD_PRIORITY_BACKGROUND);
  202. thread.start();
  203. mServiceLooper = thread.getLooper();
  204. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  205. mBinder = new FileUploaderBinder();
  206. mConnectivityChangeReceiver = new ConnectivityChangeReceiver();
  207. registerReceiver(mConnectivityChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
  208. mDb = UploadDbHandler.getInstance(this.getBaseContext());
  209. mDb.recreateDb(); //for testing only
  210. }
  211. public class ConnectivityChangeReceiver extends BroadcastReceiver {
  212. @Override
  213. public void onReceive(Context arg0, Intent arg1) {
  214. if(InstantUploadBroadcastReceiver.isOnline(getApplicationContext()))
  215. {
  216. // upload pending wifi only files.
  217. onStartCommand(null, 0, 0);
  218. }
  219. }
  220. }
  221. @Override
  222. public void onDestroy() {
  223. mDb.close();
  224. unregisterReceiver(mConnectivityChangeReceiver);
  225. super.onDestroy();
  226. }
  227. /**
  228. * Entry point to add one or several files to the queue of uploads.
  229. *
  230. * New uploads are added calling to startService(), resulting in a call to
  231. * this method. This ensures the service will keep on working although the
  232. * caller activity goes away.
  233. *
  234. * First, onStartCommand() stores all information associated with the upload
  235. * in a {@link UploadDbObject} which is stored persistently using
  236. * {@link UploadDbHandler}. Then, {@link ServiceHandler} is invoked which
  237. * performs the upload and updates the DB entry (upload success, failure,
  238. * retry, ...)
  239. *
  240. * TODO: correct return values. should not always be NOT_STICKY.
  241. */
  242. @Override
  243. public int onStartCommand(Intent intent, int flags, int startId) {
  244. AbstractList<UploadDbObject> requestedUploads = new Vector<UploadDbObject>();
  245. if (intent == null) {
  246. // service was restarted by OS (after return START_STICKY and kill
  247. // service) or connectivity change was detected. ==> check persistent upload
  248. // list.
  249. //
  250. List<UploadDbObject> list = mDb.getAllPendingUploads();
  251. for (UploadDbObject uploadDbObject : list) {
  252. uploadDbObject.setUploadStatus(UploadStatus.UPLOAD_LATER);
  253. uploadDbObject.setLastResult(null);
  254. mDb.updateUpload(uploadDbObject);
  255. }
  256. requestedUploads.addAll(list);
  257. } else {
  258. UploadSingleMulti uploadType = (UploadSingleMulti) intent.getSerializableExtra(KEY_UPLOAD_TYPE);
  259. if (uploadType == null) {
  260. Log_OC.e(TAG, "Incorrect or no upload type provided");
  261. return Service.START_NOT_STICKY;
  262. }
  263. Account account = intent.getParcelableExtra(KEY_ACCOUNT);
  264. if (!AccountUtils.exists(account, getApplicationContext())) {
  265. Log_OC.e(TAG, "KEY_ACCOUNT no set or provided KEY_ACCOUNT does not exist");
  266. return Service.START_NOT_STICKY;
  267. }
  268. OCFile[] files = null;
  269. // if KEY_FILE given, use it
  270. if (intent.hasExtra(KEY_FILE)) {
  271. if (uploadType == UploadSingleMulti.UPLOAD_SINGLE_FILE) {
  272. files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) };
  273. } else {
  274. files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE);
  275. }
  276. } else { // else use KEY_LOCAL_FILE and KEY_REMOTE_FILE
  277. if (!intent.hasExtra(KEY_LOCAL_FILE) || !intent.hasExtra(KEY_REMOTE_FILE)) {
  278. Log_OC.e(TAG, "Not enough information provided in intent");
  279. return Service.START_NOT_STICKY;
  280. }
  281. String[] localPaths;
  282. String[] remotePaths;
  283. String[] mimeTypes;
  284. if (uploadType == UploadSingleMulti.UPLOAD_SINGLE_FILE) {
  285. localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
  286. remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
  287. mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
  288. } else {
  289. localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
  290. remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
  291. mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
  292. }
  293. if (localPaths.length != remotePaths.length) {
  294. Log_OC.e(TAG, "Different number of remote paths and local paths!");
  295. return Service.START_NOT_STICKY;
  296. }
  297. files = new OCFile[localPaths.length];
  298. for (int i = 0; i < localPaths.length; i++) {
  299. files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i],
  300. ((mimeTypes != null) ? mimeTypes[i] : (String) null));
  301. if (files[i] == null) {
  302. Log_OC.e(TAG, "obtainNewOCFileToUpload() returned null for remotePaths[i]:" + remotePaths[i]
  303. + " and localPaths[i]:" + localPaths[i]);
  304. return Service.START_NOT_STICKY;
  305. }
  306. }
  307. }
  308. // at this point variable "OCFile[] files" is loaded correctly.
  309. boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
  310. boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
  311. boolean isUseWifiOnly = intent.getBooleanExtra(KEY_WIFI_ONLY, true);
  312. LocalBehaviour localAction = (LocalBehaviour) intent.getSerializableExtra(KEY_LOCAL_BEHAVIOUR);
  313. if (localAction == null)
  314. localAction = LocalBehaviour.LOCAL_BEHAVIOUR_COPY;
  315. // save always persistently path of upload, so it can be retried if
  316. // failed.
  317. for (int i = 0; i < files.length; i++) {
  318. UploadDbObject uploadObject = new UploadDbObject();
  319. uploadObject.setRemotePath(files[i].getRemotePath());
  320. uploadObject.setLocalPath(files[i].getStoragePath());
  321. uploadObject.setMimeType(files[i].getMimetype());
  322. uploadObject.setAccountName(account.name);
  323. uploadObject.setForceOverwrite(forceOverwrite);
  324. uploadObject.setCreateRemoteFolder(isCreateRemoteFolder);
  325. uploadObject.setLocalAction(localAction);
  326. uploadObject.setUseWifiOnly(isUseWifiOnly);
  327. uploadObject.setUploadStatus(UploadStatus.UPLOAD_LATER);
  328. boolean success = mDb.storeUpload(uploadObject);
  329. if(!success) {
  330. Log_OC.e(TAG, "Could not add upload to database. It is probably a duplicate. Ignore.");
  331. } else {
  332. requestedUploads.add(uploadObject);
  333. }
  334. }
  335. // TODO check if would be clever to read entries from
  336. // UploadDbHandler and add to requestedUploads at this point
  337. }
  338. Log_OC.i(TAG, "mPendingUploads size:" + mActiveUploads.size());
  339. if (requestedUploads.size() > 0) {
  340. Message msg = mServiceHandler.obtainMessage();
  341. msg.arg1 = startId;
  342. msg.obj = requestedUploads;
  343. mServiceHandler.sendMessage(msg);
  344. return Service.START_STICKY; // there is work to do. If killed this
  345. // service should be restarted
  346. // eventually.
  347. }
  348. return Service.START_NOT_STICKY; //nothing to do. do not restart.
  349. }
  350. /**
  351. * Provides a binder object that clients can use to perform operations on
  352. * the queue of uploads, excepting the addition of new files.
  353. *
  354. * Implemented to perform cancellation, pause and resume of existing
  355. * uploads.
  356. */
  357. @Override
  358. public IBinder onBind(Intent arg0) {
  359. return mBinder;
  360. }
  361. /**
  362. * Called when ALL the bound clients were onbound.
  363. */
  364. @Override
  365. public boolean onUnbind(Intent intent) {
  366. ((FileUploaderBinder) mBinder).clearListeners();
  367. return false; // not accepting rebinding (default behaviour)
  368. }
  369. /**
  370. * Binder to let client components to perform operations on the queue of
  371. * uploads.
  372. *
  373. * It provides by itself the available operations.
  374. */
  375. public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
  376. /**
  377. * Map of listeners that will be reported about progress of uploads from
  378. * a {@link FileUploaderBinder} instance
  379. */
  380. private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
  381. /**
  382. * Cancels a pending or current upload of a remote file.
  383. *
  384. * @param account Owncloud account where the remote file will be stored.
  385. * @param file A file in the queue of pending uploads
  386. */
  387. public void cancel(Account account, OCFile file) {
  388. UploadFileOperation upload = null;
  389. synchronized (mActiveUploads) {
  390. upload = mActiveUploads.remove(buildRemoteName(account, file));
  391. }
  392. if (upload != null) {
  393. upload.cancel();
  394. }
  395. }
  396. public void clearListeners() {
  397. mBoundListeners.clear();
  398. }
  399. /**
  400. * Returns True when the file described by 'file' is being uploaded to
  401. * the ownCloud account 'account' or waiting for it
  402. *
  403. * If 'file' is a directory, returns 'true' if some of its descendant
  404. * files is uploading or waiting to upload.
  405. *
  406. * @param account Owncloud account where the remote file will be stored.
  407. * @param file A file that could be in the queue of pending uploads
  408. */
  409. public boolean isUploading(Account account, OCFile file) {
  410. if (account == null || file == null)
  411. return false;
  412. String targetKey = buildRemoteName(account, file);
  413. synchronized (mActiveUploads) {
  414. if (file.isFolder()) {
  415. // this can be slow if there are many uploads :(
  416. Iterator<String> it = mActiveUploads.keySet().iterator();
  417. boolean found = false;
  418. while (it.hasNext() && !found) {
  419. found = it.next().startsWith(targetKey);
  420. }
  421. return found;
  422. } else {
  423. return (mActiveUploads.containsKey(targetKey));
  424. }
  425. }
  426. }
  427. /**
  428. * Adds a listener interested in the progress of the upload for a
  429. * concrete file.
  430. *
  431. * @param listener Object to notify about progress of transfer.
  432. * @param account ownCloud account holding the file of interest.
  433. * @param file {@link OCfile} of interest for listener.
  434. */
  435. public void addDatatransferProgressListener(OnDatatransferProgressListener listener, Account account,
  436. OCFile file) {
  437. if (account == null || file == null || listener == null)
  438. return;
  439. String targetKey = buildRemoteName(account, file);
  440. mBoundListeners.put(targetKey, listener);
  441. }
  442. /**
  443. * Removes a listener interested in the progress of the upload for a
  444. * concrete file.
  445. *
  446. * @param listener Object to notify about progress of transfer.
  447. * @param account ownCloud account holding the file of interest.
  448. * @param file {@link OCfile} of interest for listener.
  449. */
  450. public void removeDatatransferProgressListener(OnDatatransferProgressListener listener, Account account,
  451. OCFile file) {
  452. if (account == null || file == null || listener == null)
  453. return;
  454. String targetKey = buildRemoteName(account, file);
  455. if (mBoundListeners.get(targetKey) == listener) {
  456. mBoundListeners.remove(targetKey);
  457. }
  458. }
  459. @Override
  460. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
  461. String localFileName) {
  462. Set<Entry<String, UploadFileOperation>> uploads = mActiveUploads.entrySet();
  463. UploadFileOperation currentUpload = null;
  464. //unfortunately we do not have the remote upload path here, so search through all uploads.
  465. //however, this may lead to problems, if user uploads same file twice to different destinations.
  466. //this can only be fixed by replacing localFileName with remote path.
  467. for (Entry<String, UploadFileOperation> entry : uploads) {
  468. if(entry.getValue().getStoragePath().equals(localFileName)) {
  469. if(currentUpload != null) {
  470. Log_OC.e(TAG, "Found two current uploads with same remote path " + localFileName + ". Ignore.");
  471. return;
  472. }
  473. currentUpload = entry.getValue();
  474. }
  475. }
  476. if (currentUpload == null) {
  477. Log_OC.e(TAG, "Found no current upload with remote path " + localFileName + ". Ignore.");
  478. return;
  479. }
  480. String key = buildRemoteName(currentUpload.getAccount(), currentUpload.getFile());
  481. OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
  482. if (boundListener != null) {
  483. boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, localFileName);
  484. }
  485. }
  486. }
  487. /**
  488. * Upload worker. Performs the pending uploads in the order they were
  489. * requested.
  490. *
  491. * Created with the Looper of a new thread, started in
  492. * {@link FileUploadService#onCreate()}.
  493. */
  494. private static class ServiceHandler extends Handler {
  495. // don't make it a final class, and don't remove the static ; lint will
  496. // warn about a possible memory leak
  497. FileUploadService mService;
  498. public ServiceHandler(Looper looper, FileUploadService service) {
  499. super(looper);
  500. if (service == null)
  501. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  502. mService = service;
  503. }
  504. @Override
  505. public void handleMessage(Message msg) {
  506. @SuppressWarnings("unchecked")
  507. AbstractList<UploadDbObject> requestedUploads = (AbstractList<UploadDbObject>) msg.obj;
  508. if (msg.obj != null) {
  509. Iterator<UploadDbObject> it = requestedUploads.iterator();
  510. while (it.hasNext()) {
  511. UploadDbObject uploadObject = it.next();
  512. mService.uploadFile(uploadObject);
  513. }
  514. }
  515. mService.stopSelf(msg.arg1);
  516. }
  517. }
  518. /**
  519. * Core upload method: sends the file(s) to upload. This function blocks until upload succeeded or failed.
  520. *
  521. * @param uploadDbObject Key to access the upload to perform, contained in
  522. * mPendingUploads
  523. */
  524. private void uploadFile(UploadDbObject uploadDbObject) {
  525. if(uploadDbObject.getUploadStatus() == UploadStatus.UPLOAD_SUCCEEDED) {
  526. Log_OC.w(TAG, "Already succeeded uploadObject was again scheduled for upload. Fix that!");
  527. return;
  528. }
  529. UploadFileOperation currentUpload = null;
  530. synchronized (mActiveUploads) {
  531. //How does this work? Is it thread-safe to set mCurrentUpload here?
  532. //What happens if other mCurrentUpload is currently in progress?
  533. //
  534. //It seems that upload does work, however the upload state is not set
  535. //back of the first upload when a second upload starts while first is
  536. //in progress (yellow up-arrow does not disappear of first upload)
  537. currentUpload = mActiveUploads.get(uploadDbObject.getRemotePath());
  538. //if upload not in progress, start it now
  539. if(currentUpload == null) {
  540. if (uploadDbObject.isUseWifiOnly()
  541. && !InstantUploadBroadcastReceiver.isConnectedViaWiFi(getApplicationContext())) {
  542. Log_OC.d(TAG, "Do not start upload because it is wifi-only.");
  543. return;
  544. }
  545. if (!new File(uploadDbObject.getLocalPath()).exists()) {
  546. mDb.updateUpload(uploadDbObject.getLocalPath(), UploadStatus.UPLOAD_FAILED_GIVE_UP,
  547. new RemoteOperationResult(ResultCode.FILE_NOT_FOUND));
  548. Log_OC.d(TAG, "Do not start upload because local file does not exist.");
  549. return;
  550. }
  551. AccountManager aMgr = AccountManager.get(this);
  552. Account account = uploadDbObject.getAccount(getApplicationContext());
  553. String version = aMgr.getUserData(account, Constants.KEY_OC_VERSION);
  554. OwnCloudVersion ocv = new OwnCloudVersion(version);
  555. boolean chunked = FileUploadService.chunkedUploadIsSupported(ocv);
  556. String uploadKey = null;
  557. uploadKey = buildRemoteName(account, uploadDbObject.getRemotePath());
  558. OCFile file = obtainNewOCFileToUpload(uploadDbObject.getRemotePath(), uploadDbObject.getLocalPath(),
  559. uploadDbObject.getMimeType());
  560. currentUpload = new UploadFileOperation(account, file, chunked, uploadDbObject.isForceOverwrite(),
  561. uploadDbObject.getLocalAction(), getApplicationContext());
  562. if (uploadDbObject.isCreateRemoteFolder()) {
  563. currentUpload.setRemoteFolderToBeCreated();
  564. }
  565. mActiveUploads.putIfAbsent(uploadKey, currentUpload); // Grants that
  566. // the file only upload once time
  567. currentUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
  568. }
  569. }
  570. if (currentUpload != null) {
  571. notifyUploadStart(currentUpload);
  572. RemoteOperationResult uploadResult = null, grantResult = null;
  573. try {
  574. // / prepare client object to send requests to the ownCloud
  575. // server
  576. if (mUploadClient == null || !mLastAccount.equals(currentUpload.getAccount())) {
  577. mLastAccount = currentUpload.getAccount();
  578. mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
  579. OwnCloudAccount ocAccount = new OwnCloudAccount(mLastAccount, this);
  580. mUploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, this);
  581. }
  582. // / check the existence of the parent folder for the file to
  583. // upload
  584. String remoteParentPath = new File(currentUpload.getRemotePath()).getParent();
  585. remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ? remoteParentPath
  586. : remoteParentPath + OCFile.PATH_SEPARATOR;
  587. grantResult = grantFolderExistence(currentUpload, remoteParentPath);
  588. // / perform the upload
  589. if (grantResult.isSuccess()) {
  590. OCFile parent = mStorageManager.getFileByPath(remoteParentPath);
  591. currentUpload.getFile().setParentId(parent.getFileId());
  592. uploadResult = currentUpload.execute(mUploadClient);
  593. if (uploadResult.isSuccess()) {
  594. saveUploadedFile(currentUpload);
  595. }
  596. } else {
  597. uploadResult = grantResult;
  598. }
  599. } catch (AccountsException e) {
  600. Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  601. uploadResult = new RemoteOperationResult(e);
  602. } catch (IOException e) {
  603. Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e);
  604. uploadResult = new RemoteOperationResult(e);
  605. } finally {
  606. synchronized (mActiveUploads) {
  607. mActiveUploads.remove(uploadDbObject);
  608. Log_OC.i(TAG, "Remove CurrentUploadItem from pending upload Item Map.");
  609. }
  610. if (uploadResult.isException()) {
  611. // enforce the creation of a new client object for next
  612. // uploads; this grant that a new socket will
  613. // be created in the future if the current exception is due
  614. // to an abrupt lose of network connection
  615. mUploadClient = null;
  616. }
  617. }
  618. // notify result
  619. notifyUploadResult(uploadResult, currentUpload);
  620. sendFinalBroadcast(currentUpload, uploadResult);
  621. }
  622. }
  623. /**
  624. * Checks the existence of the folder where the current file will be
  625. * uploaded both in the remote server and in the local database.
  626. *
  627. * If the upload is set to enforce the creation of the folder, the method
  628. * tries to create it both remote and locally.
  629. *
  630. * @param pathToGrant Full remote path whose existence will be granted.
  631. * @return An {@link OCFile} instance corresponding to the folder where the
  632. * file will be uploaded.
  633. */
  634. private RemoteOperationResult grantFolderExistence(UploadFileOperation currentUpload, String pathToGrant) {
  635. RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, this, false);
  636. RemoteOperationResult result = operation.execute(mUploadClient);
  637. if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND
  638. && currentUpload.isRemoteFolderToBeCreated()) {
  639. SyncOperation syncOp = new CreateFolderOperation(pathToGrant, true);
  640. result = syncOp.execute(mUploadClient, mStorageManager);
  641. }
  642. if (result.isSuccess()) {
  643. OCFile parentDir = mStorageManager.getFileByPath(pathToGrant);
  644. if (parentDir == null) {
  645. parentDir = createLocalFolder(pathToGrant);
  646. }
  647. if (parentDir != null) {
  648. result = new RemoteOperationResult(ResultCode.OK);
  649. } else {
  650. result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  651. }
  652. }
  653. return result;
  654. }
  655. private OCFile createLocalFolder(String remotePath) {
  656. String parentPath = new File(remotePath).getParent();
  657. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
  658. OCFile parent = mStorageManager.getFileByPath(parentPath);
  659. if (parent == null) {
  660. parent = createLocalFolder(parentPath);
  661. }
  662. if (parent != null) {
  663. OCFile createdFolder = new OCFile(remotePath);
  664. createdFolder.setMimetype("DIR");
  665. createdFolder.setParentId(parent.getFileId());
  666. mStorageManager.saveFile(createdFolder);
  667. return createdFolder;
  668. }
  669. return null;
  670. }
  671. /**
  672. * Saves a OC File after a successful upload.
  673. *
  674. * A PROPFIND is necessary to keep the props in the local database
  675. * synchronized with the server, specially the modification time and Etag
  676. * (where available)
  677. *
  678. * TODO refactor this ugly thing
  679. */
  680. private void saveUploadedFile(UploadFileOperation currentUpload) {
  681. OCFile file = currentUpload.getFile();
  682. if (file.fileExists()) {
  683. file = mStorageManager.getFileById(file.getFileId());
  684. }
  685. long syncDate = System.currentTimeMillis();
  686. file.setLastSyncDateForData(syncDate);
  687. // new PROPFIND to keep data consistent with server
  688. // in theory, should return the same we already have
  689. ReadRemoteFileOperation operation = new ReadRemoteFileOperation(currentUpload.getRemotePath());
  690. RemoteOperationResult result = operation.execute(mUploadClient);
  691. if (result.isSuccess()) {
  692. updateOCFile(file, (RemoteFile) result.getData().get(0));
  693. file.setLastSyncDateForProperties(syncDate);
  694. }
  695. // / maybe this would be better as part of UploadFileOperation... or
  696. // maybe all this method
  697. if (currentUpload.wasRenamed()) {
  698. OCFile oldFile = currentUpload.getOldFile();
  699. if (oldFile.fileExists()) {
  700. oldFile.setStoragePath(null);
  701. mStorageManager.saveFile(oldFile);
  702. } // else: it was just an automatic renaming due to a name
  703. // coincidence; nothing else is needed, the storagePath is right
  704. // in the instance returned by mCurrentUpload.getFile()
  705. }
  706. file.setNeedsUpdateThumbnail(true);
  707. mStorageManager.saveFile(file);
  708. }
  709. private void updateOCFile(OCFile file, RemoteFile remoteFile) {
  710. file.setCreationTimestamp(remoteFile.getCreationTimestamp());
  711. file.setFileLength(remoteFile.getLength());
  712. file.setMimetype(remoteFile.getMimeType());
  713. file.setModificationTimestamp(remoteFile.getModifiedTimestamp());
  714. file.setModificationTimestampAtLastSyncForData(remoteFile.getModifiedTimestamp());
  715. // file.setEtag(remoteFile.getEtag()); // TODO Etag, where available
  716. file.setRemoteId(remoteFile.getRemoteId());
  717. }
  718. private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType) {
  719. // MIME type
  720. if (mimeType == null || mimeType.length() <= 0) {
  721. try {
  722. mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
  723. remotePath.substring(remotePath.lastIndexOf('.') + 1));
  724. } catch (IndexOutOfBoundsException e) {
  725. Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
  726. }
  727. }
  728. if (mimeType == null) {
  729. mimeType = "application/octet-stream";
  730. }
  731. if (isPdfFileFromContentProviderWithoutExtension(localPath, mimeType)){
  732. remotePath += FILE_EXTENSION_PDF;
  733. }
  734. OCFile newFile = new OCFile(remotePath);
  735. newFile.setStoragePath(localPath);
  736. newFile.setLastSyncDateForProperties(0);
  737. newFile.setLastSyncDateForData(0);
  738. // size
  739. if (localPath != null && localPath.length() > 0) {
  740. File localFile = new File(localPath);
  741. newFile.setFileLength(localFile.length());
  742. newFile.setLastSyncDateForData(localFile.lastModified());
  743. } // don't worry about not assigning size, the problems with localPath
  744. // are checked when the UploadFileOperation instance is created
  745. newFile.setMimetype(mimeType);
  746. return newFile;
  747. }
  748. /**
  749. * Creates a status notification to show the upload progress
  750. *
  751. * @param upload Upload operation starting.
  752. */
  753. private void notifyUploadStart(UploadFileOperation upload) {
  754. // / create status notification with a progress bar
  755. mNotificationBuilder = NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
  756. mNotificationBuilder
  757. .setOngoing(true)
  758. .setSmallIcon(R.drawable.notification_icon)
  759. .setTicker(getString(R.string.uploader_upload_in_progress_ticker))
  760. .setContentTitle(getString(R.string.uploader_upload_in_progress_ticker))
  761. .setProgress(100, 0, false)
  762. .setContentText(
  763. String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
  764. // / includes a pending intent in the notification showing the details
  765. // view of the file
  766. Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
  767. showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
  768. showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  769. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  770. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
  771. showDetailsIntent, 0));
  772. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
  773. mDb.updateUpload(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_IN_PROGRESS, null);
  774. }
  775. /**
  776. * Updates the status notification with the result of an upload operation.
  777. *
  778. * @param uploadResult Result of the upload operation.
  779. * @param upload Finished upload operation
  780. */
  781. private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
  782. Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
  783. // / cancelled operation or success -> silent removal of progress
  784. // notification
  785. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  786. // Show the result: success or fail notification
  787. if (!uploadResult.isCancelled()) {
  788. int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker
  789. : R.string.uploader_upload_failed_ticker;
  790. String content = null;
  791. // check credentials error
  792. boolean needsToUpdateCredentials = (uploadResult.getCode() == ResultCode.UNAUTHORIZED || uploadResult
  793. .isIdPRedirection());
  794. tickerId = (needsToUpdateCredentials) ? R.string.uploader_upload_failed_credentials_error : tickerId;
  795. mNotificationBuilder.setTicker(getString(tickerId)).setContentTitle(getString(tickerId))
  796. .setAutoCancel(true).setOngoing(false).setProgress(0, 0, false);
  797. content = ErrorMessageAdapter.getErrorCauseMessage(uploadResult, upload, getResources());
  798. if (needsToUpdateCredentials) {
  799. // let the user update credentials with one click
  800. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  801. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount());
  802. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
  803. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
  804. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  805. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  806. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  807. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
  808. updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));
  809. mUploadClient = null;
  810. // grant that future retries on the same account will get the
  811. // fresh credentials
  812. }
  813. mNotificationBuilder.setContentText(content);
  814. mNotificationManager.notify(tickerId, mNotificationBuilder.build());
  815. if (uploadResult.isSuccess()) {
  816. mDb.updateUpload(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_SUCCEEDED, uploadResult);
  817. // remove success notification, with a delay of 2 seconds
  818. NotificationDelayer.cancelWithDelay(mNotificationManager, R.string.uploader_upload_succeeded_ticker,
  819. 2000);
  820. } else {
  821. // TODO: add other cases in which upload attempt is to be
  822. // abandoned.
  823. if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
  824. mDb.updateUpload(upload.getOriginalStoragePath(),
  825. UploadDbHandler.UploadStatus.UPLOAD_FAILED_GIVE_UP, uploadResult);
  826. } else {
  827. mDb.updateUpload(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_FAILED, uploadResult);
  828. }
  829. }
  830. } else {
  831. mDb.updateUpload(upload.getOriginalStoragePath(), UploadStatus.UPLOAD_FAILED, uploadResult);
  832. }
  833. }
  834. /**
  835. * Sends a broadcast in order to the interested activities can update their
  836. * view
  837. *
  838. * @param upload Finished upload operation
  839. * @param uploadResult Result of the upload operation
  840. */
  841. private void sendFinalBroadcast(UploadFileOperation upload, RemoteOperationResult uploadResult) {
  842. Intent end = new Intent(getUploadFinishMessage());
  843. end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  844. // path, after
  845. // possible
  846. // automatic
  847. // renaming
  848. if (upload.wasRenamed()) {
  849. end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
  850. }
  851. end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  852. end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  853. end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
  854. sendStickyBroadcast(end);
  855. }
  856. /**
  857. * Checks if content provider, using the content:// scheme, returns a file with mime-type
  858. * 'application/pdf' but file has not extension
  859. * @param localPath
  860. * @param mimeType
  861. * @return true if is needed to add the pdf file extension to the file
  862. */
  863. private boolean isPdfFileFromContentProviderWithoutExtension(String localPath, String mimeType) {
  864. return localPath.startsWith(UriUtils.URI_CONTENT_SCHEME) &&
  865. mimeType.equals(MIME_TYPE_PDF) &&
  866. !localPath.endsWith(FILE_EXTENSION_PDF);
  867. }
  868. }