FileUploadService.java 42 KB

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