FileUploader.java 42 KB

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