FileUploader.java 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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 as published by
  7. * the Free Software Foundation, either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package com.owncloud.android.files.services;
  20. import java.io.File;
  21. import java.util.AbstractList;
  22. import java.util.Iterator;
  23. import java.util.Vector;
  24. import java.util.concurrent.ConcurrentHashMap;
  25. import java.util.concurrent.ConcurrentMap;
  26. import org.apache.http.HttpStatus;
  27. import org.apache.jackrabbit.webdav.MultiStatus;
  28. import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
  29. import android.accounts.Account;
  30. import android.accounts.AccountManager;
  31. import android.app.Notification;
  32. import android.app.NotificationManager;
  33. import android.app.PendingIntent;
  34. import android.app.Service;
  35. import android.content.Intent;
  36. import android.os.Binder;
  37. import android.os.Handler;
  38. import android.os.HandlerThread;
  39. import android.os.IBinder;
  40. import android.os.Looper;
  41. import android.os.Message;
  42. import android.os.Process;
  43. import android.util.Log;
  44. import android.webkit.MimeTypeMap;
  45. import android.widget.RemoteViews;
  46. import android.widget.Toast;
  47. import com.owncloud.android.R;
  48. import com.owncloud.android.authenticator.AccountAuthenticator;
  49. import com.owncloud.android.datamodel.FileDataStorageManager;
  50. import com.owncloud.android.datamodel.OCFile;
  51. import com.owncloud.android.db.DbHandler;
  52. import com.owncloud.android.files.InstantUploadBroadcastReceiver;
  53. import com.owncloud.android.network.OwnCloudClientUtils;
  54. import com.owncloud.android.operations.ChunkedUploadFileOperation;
  55. import com.owncloud.android.operations.RemoteOperationResult;
  56. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  57. import com.owncloud.android.operations.UploadFileOperation;
  58. import com.owncloud.android.ui.activity.FileDetailActivity;
  59. import com.owncloud.android.ui.activity.InstantUploadActivity;
  60. import com.owncloud.android.ui.fragment.FileDetailFragment;
  61. import com.owncloud.android.utils.OwnCloudVersion;
  62. import eu.alefzero.webdav.OnDatatransferProgressListener;
  63. import eu.alefzero.webdav.WebdavClient;
  64. import eu.alefzero.webdav.WebdavEntry;
  65. import eu.alefzero.webdav.WebdavUtils;
  66. public class FileUploader extends Service implements OnDatatransferProgressListener {
  67. public static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
  68. public static final String EXTRA_UPLOAD_RESULT = "RESULT";
  69. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  70. public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
  71. public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
  72. public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
  73. public static final String KEY_FILE = "FILE";
  74. public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
  75. public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
  76. public static final String KEY_MIME_TYPE = "MIME_TYPE";
  77. public static final String KEY_ACCOUNT = "ACCOUNT";
  78. public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
  79. public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
  80. public static final String KEY_INSTANT_UPLOAD = "INSTANT_UPLOAD";
  81. public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
  82. public static final int LOCAL_BEHAVIOUR_COPY = 0;
  83. public static final int LOCAL_BEHAVIOUR_MOVE = 1;
  84. public static final int LOCAL_BEHAVIOUR_FORGET = 2;
  85. public static final int UPLOAD_SINGLE_FILE = 0;
  86. public static final int UPLOAD_MULTIPLE_FILES = 1;
  87. private static final String TAG = FileUploader.class.getSimpleName();
  88. private Looper mServiceLooper;
  89. private ServiceHandler mServiceHandler;
  90. private IBinder mBinder;
  91. private WebdavClient mUploadClient = null;
  92. private Account mLastAccount = null;
  93. private FileDataStorageManager mStorageManager;
  94. private ConcurrentMap<String, UploadFileOperation> mPendingUploads = new ConcurrentHashMap<String, UploadFileOperation>();
  95. private UploadFileOperation mCurrentUpload = null;
  96. private NotificationManager mNotificationManager;
  97. private Notification mNotification;
  98. private int mLastPercent;
  99. private RemoteViews mDefaultNotificationContentView;
  100. /**
  101. * Builds a key for mPendingUploads from the account and file to upload
  102. *
  103. * @param account Account where the file to download is stored
  104. * @param file File to download
  105. */
  106. private String buildRemoteName(Account account, OCFile file) {
  107. return account.name + file.getRemotePath();
  108. }
  109. private String buildRemoteName(Account account, String remotePath) {
  110. return account.name + remotePath;
  111. }
  112. /**
  113. * Checks if an ownCloud server version should support chunked uploads.
  114. *
  115. * @param version OwnCloud version instance corresponding to an ownCloud
  116. * server.
  117. * @return 'True' if the ownCloud server with version supports chunked
  118. * uploads.
  119. */
  120. private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
  121. return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
  122. }
  123. /**
  124. * Service initialization
  125. */
  126. @Override
  127. public void onCreate() {
  128. super.onCreate();
  129. Log.i(TAG, "mPendingUploads size:" + mPendingUploads.size());
  130. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  131. HandlerThread thread = new HandlerThread("FileUploaderThread", Process.THREAD_PRIORITY_BACKGROUND);
  132. thread.start();
  133. mServiceLooper = thread.getLooper();
  134. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  135. mBinder = new FileUploaderBinder();
  136. }
  137. /**
  138. * Entry point to add one or several files to the queue of uploads.
  139. *
  140. * New uploads are added calling to startService(), resulting in a call to
  141. * this method. This ensures the service will keep on working although the
  142. * caller activity goes away.
  143. */
  144. @Override
  145. public int onStartCommand(Intent intent, int flags, int startId) {
  146. if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE)
  147. || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
  148. Log.e(TAG, "Not enough information provided in intent");
  149. return Service.START_NOT_STICKY;
  150. }
  151. int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
  152. if (uploadType == -1) {
  153. Log.e(TAG, "Incorrect upload type provided");
  154. return Service.START_NOT_STICKY;
  155. }
  156. Account account = intent.getParcelableExtra(KEY_ACCOUNT);
  157. String[] localPaths = null, remotePaths = null, mimeTypes = null;
  158. OCFile[] files = null;
  159. if (uploadType == UPLOAD_SINGLE_FILE) {
  160. if (intent.hasExtra(KEY_FILE)) {
  161. files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) };
  162. } else {
  163. localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
  164. remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
  165. mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
  166. }
  167. } else { // mUploadType == UPLOAD_MULTIPLE_FILES
  168. if (intent.hasExtra(KEY_FILE)) {
  169. files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO
  170. // will
  171. // this
  172. // casting
  173. // work
  174. // fine?
  175. } else {
  176. localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
  177. remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
  178. mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
  179. }
  180. }
  181. FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
  182. boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
  183. boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
  184. int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_COPY);
  185. boolean fixed = false;
  186. if (isInstant) {
  187. fixed = checkAndFixInstantUploadDirectory(storageManager); // MUST
  188. // be
  189. // done
  190. // BEFORE
  191. // calling
  192. // obtainNewOCFileToUpload
  193. }
  194. if (intent.hasExtra(KEY_FILE) && files == null) {
  195. Log.e(TAG, "Incorrect array for OCFiles provided in upload intent");
  196. return Service.START_NOT_STICKY;
  197. } else if (!intent.hasExtra(KEY_FILE)) {
  198. if (localPaths == null) {
  199. Log.e(TAG, "Incorrect array for local paths provided in upload intent");
  200. return Service.START_NOT_STICKY;
  201. }
  202. if (remotePaths == null) {
  203. Log.e(TAG, "Incorrect array for remote paths provided in upload intent");
  204. return Service.START_NOT_STICKY;
  205. }
  206. if (localPaths.length != remotePaths.length) {
  207. Log.e(TAG, "Different number of remote paths and local paths!");
  208. return Service.START_NOT_STICKY;
  209. }
  210. files = new OCFile[localPaths.length];
  211. for (int i = 0; i < localPaths.length; i++) {
  212. files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes != null) ? mimeTypes[i]
  213. : (String) null), storageManager);
  214. if (files[i] == null) {
  215. // TODO @andromaex add failure Notiification
  216. return Service.START_NOT_STICKY;
  217. }
  218. }
  219. }
  220. OwnCloudVersion ocv = new OwnCloudVersion(AccountManager.get(this).getUserData(account,
  221. AccountAuthenticator.KEY_OC_VERSION));
  222. boolean chunked = FileUploader.chunkedUploadIsSupported(ocv);
  223. AbstractList<String> requestedUploads = new Vector<String>();
  224. String uploadKey = null;
  225. UploadFileOperation newUpload = null;
  226. try {
  227. for (int i = 0; i < files.length; i++) {
  228. uploadKey = buildRemoteName(account, files[i].getRemotePath());
  229. if (chunked) {
  230. newUpload = new ChunkedUploadFileOperation(account, files[i], isInstant, forceOverwrite,
  231. localAction);
  232. } else {
  233. newUpload = new UploadFileOperation(account, files[i], isInstant, forceOverwrite, localAction);
  234. }
  235. if (fixed && i == 0) {
  236. newUpload.setRemoteFolderToBeCreated();
  237. }
  238. mPendingUploads.putIfAbsent(uploadKey, newUpload);
  239. newUpload.addDatatransferProgressListener(this);
  240. requestedUploads.add(uploadKey);
  241. }
  242. } catch (IllegalArgumentException e) {
  243. Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  244. return START_NOT_STICKY;
  245. } catch (IllegalStateException e) {
  246. Log.e(TAG, "Bad information provided in intent: " + e.getMessage());
  247. return START_NOT_STICKY;
  248. } catch (Exception e) {
  249. Log.e(TAG, "Unexpected exception while processing upload intent", e);
  250. return START_NOT_STICKY;
  251. }
  252. if (requestedUploads.size() > 0) {
  253. Message msg = mServiceHandler.obtainMessage();
  254. msg.arg1 = startId;
  255. msg.obj = requestedUploads;
  256. mServiceHandler.sendMessage(msg);
  257. }
  258. Log.i(TAG, "mPendingUploads size:" + mPendingUploads.size());
  259. return Service.START_NOT_STICKY;
  260. }
  261. /**
  262. * Provides a binder object that clients can use to perform operations on
  263. * the queue of uploads, excepting the addition of new files.
  264. *
  265. * Implemented to perform cancellation, pause and resume of existing
  266. * uploads.
  267. */
  268. @Override
  269. public IBinder onBind(Intent arg0) {
  270. return mBinder;
  271. }
  272. /**
  273. * Binder to let client components to perform operations on the queue of
  274. * uploads.
  275. *
  276. * It provides by itself the available operations.
  277. */
  278. public class FileUploaderBinder extends Binder {
  279. /**
  280. * Cancels a pending or current upload of a remote file.
  281. *
  282. * @param account Owncloud account where the remote file will be stored.
  283. * @param file A file in the queue of pending uploads
  284. */
  285. public void cancel(Account account, OCFile file) {
  286. UploadFileOperation upload = null;
  287. synchronized (mPendingUploads) {
  288. upload = mPendingUploads.remove(buildRemoteName(account, file));
  289. }
  290. if (upload != null) {
  291. upload.cancel();
  292. }
  293. }
  294. /**
  295. * Returns True when the file described by 'file' is being uploaded to
  296. * the ownCloud account 'account' or waiting for it
  297. *
  298. * If 'file' is a directory, returns 'true' if some of its descendant
  299. * files is downloading or waiting to download.
  300. *
  301. * @param account Owncloud account where the remote file will be stored.
  302. * @param file A file that could be in the queue of pending uploads
  303. */
  304. public boolean isUploading(Account account, OCFile file) {
  305. if (account == null || file == null)
  306. return false;
  307. String targetKey = buildRemoteName(account, file);
  308. synchronized (mPendingUploads) {
  309. if (file.isDirectory()) {
  310. // this can be slow if there are many downloads :(
  311. Iterator<String> it = mPendingUploads.keySet().iterator();
  312. boolean found = false;
  313. while (it.hasNext() && !found) {
  314. found = it.next().startsWith(targetKey);
  315. }
  316. return found;
  317. } else {
  318. return (mPendingUploads.containsKey(targetKey));
  319. }
  320. }
  321. }
  322. }
  323. /**
  324. * Upload worker. Performs the pending uploads in the order they were
  325. * requested.
  326. *
  327. * Created with the Looper of a new thread, started in
  328. * {@link FileUploader#onCreate()}.
  329. */
  330. private static class ServiceHandler extends Handler {
  331. // don't make it a final class, and don't remove the static ; lint will
  332. // warn about a possible memory leak
  333. FileUploader mService;
  334. public ServiceHandler(Looper looper, FileUploader service) {
  335. super(looper);
  336. if (service == null)
  337. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  338. mService = service;
  339. }
  340. @Override
  341. public void handleMessage(Message msg) {
  342. @SuppressWarnings("unchecked")
  343. AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
  344. if (msg.obj != null) {
  345. Iterator<String> it = requestedUploads.iterator();
  346. while (it.hasNext()) {
  347. mService.uploadFile(it.next());
  348. }
  349. }
  350. mService.stopSelf(msg.arg1);
  351. }
  352. }
  353. /**
  354. * Core upload method: sends the file(s) to upload
  355. *
  356. * @param uploadKey Key to access the upload to perform, contained in
  357. * mPendingUploads
  358. */
  359. public void uploadFile(String uploadKey) {
  360. synchronized (mPendingUploads) {
  361. mCurrentUpload = mPendingUploads.get(uploadKey);
  362. }
  363. if (mCurrentUpload != null) {
  364. notifyUploadStart(mCurrentUpload);
  365. // / prepare client object to send requests to the ownCloud server
  366. if (mUploadClient == null || !mLastAccount.equals(mCurrentUpload.getAccount())) {
  367. mLastAccount = mCurrentUpload.getAccount();
  368. mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
  369. mUploadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
  370. }
  371. // / create remote folder for instant uploads
  372. if (mCurrentUpload.isRemoteFolderToBeCreated()) {
  373. mUploadClient.createDirectory(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR); // ignoring
  374. // result;
  375. // fail
  376. // could
  377. // just
  378. // mean
  379. // that
  380. // it
  381. // already
  382. // exists,
  383. // but
  384. // local
  385. // database
  386. // is
  387. // not
  388. // synchronized;
  389. // the
  390. // upload
  391. // will
  392. // be
  393. // tried
  394. // anyway
  395. }
  396. // / perform the upload
  397. RemoteOperationResult uploadResult = null;
  398. try {
  399. uploadResult = mCurrentUpload.execute(mUploadClient);
  400. if (uploadResult.isSuccess()) {
  401. saveUploadedFile();
  402. }
  403. } finally {
  404. synchronized (mPendingUploads) {
  405. mPendingUploads.remove(uploadKey);
  406. Log.i(TAG, "Remove CurrentUploadItem from pending upload Item Map.");
  407. }
  408. }
  409. // notify result
  410. notifyUploadResult(uploadResult, mCurrentUpload);
  411. sendFinalBroadcast(mCurrentUpload, uploadResult);
  412. }
  413. }
  414. /**
  415. * Saves a OC File after a successful upload.
  416. *
  417. * A PROPFIND is necessary to keep the props in the local database
  418. * synchronized with the server, specially the modification time and Etag
  419. * (where available)
  420. *
  421. * TODO refactor this ugly thing
  422. */
  423. private void saveUploadedFile() {
  424. OCFile file = mCurrentUpload.getFile();
  425. long syncDate = System.currentTimeMillis();
  426. file.setLastSyncDateForData(syncDate);
  427. // / new PROPFIND to keep data consistent with server in theory, should
  428. // return the same we already have
  429. PropFindMethod propfind = null;
  430. RemoteOperationResult result = null;
  431. try {
  432. propfind = new PropFindMethod(mUploadClient.getBaseUri()
  433. + WebdavUtils.encodePath(mCurrentUpload.getRemotePath()));
  434. int status = mUploadClient.executeMethod(propfind);
  435. boolean isMultiStatus = (status == HttpStatus.SC_MULTI_STATUS);
  436. if (isMultiStatus) {
  437. MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
  438. WebdavEntry we = new WebdavEntry(resp.getResponses()[0], mUploadClient.getBaseUri().getPath());
  439. updateOCFile(file, we);
  440. file.setLastSyncDateForProperties(syncDate);
  441. } else {
  442. mUploadClient.exhaustResponse(propfind.getResponseBodyAsStream());
  443. }
  444. result = new RemoteOperationResult(isMultiStatus, status);
  445. Log.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": "
  446. + result.getLogMessage());
  447. } catch (Exception e) {
  448. result = new RemoteOperationResult(e);
  449. Log.e(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": "
  450. + result.getLogMessage(), e);
  451. } finally {
  452. if (propfind != null)
  453. propfind.releaseConnection();
  454. }
  455. // / maybe this would be better as part of UploadFileOperation... or
  456. // maybe all this method
  457. if (mCurrentUpload.wasRenamed()) {
  458. OCFile oldFile = mCurrentUpload.getOldFile();
  459. if (oldFile.fileExists()) {
  460. oldFile.setStoragePath(null);
  461. mStorageManager.saveFile(oldFile);
  462. } // else: it was just an automatic renaming due to a name
  463. // coincidence; nothing else is needed, the storagePath is right
  464. // in the instance returned by mCurrentUpload.getFile()
  465. }
  466. mStorageManager.saveFile(file);
  467. }
  468. private void updateOCFile(OCFile file, WebdavEntry we) {
  469. file.setCreationTimestamp(we.createTimestamp());
  470. file.setFileLength(we.contentLength());
  471. file.setMimetype(we.contentType());
  472. file.setModificationTimestamp(we.modifiedTimestamp());
  473. file.setModificationTimestampAtLastSyncForData(we.modifiedTimestamp());
  474. // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where
  475. // available
  476. }
  477. private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager) {
  478. OCFile instantUploadDir = storageManager.getFileByPath(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
  479. if (instantUploadDir == null) {
  480. // first instant upload in the account, or never account not
  481. // synchronized after the remote InstantUpload folder was created
  482. OCFile newDir = new OCFile(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
  483. newDir.setMimetype("DIR");
  484. OCFile path = storageManager.getFileByPath(OCFile.PATH_SEPARATOR);
  485. if (path != null) {
  486. newDir.setParentId(path.getFileId());
  487. storageManager.saveFile(newDir);
  488. return true;
  489. } else {
  490. return false;
  491. }
  492. }
  493. return false;
  494. }
  495. private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType,
  496. FileDataStorageManager storageManager) {
  497. OCFile newFile = new OCFile(remotePath);
  498. newFile.setStoragePath(localPath);
  499. newFile.setLastSyncDateForProperties(0);
  500. newFile.setLastSyncDateForData(0);
  501. // size
  502. if (localPath != null && localPath.length() > 0) {
  503. File localFile = new File(localPath);
  504. newFile.setFileLength(localFile.length());
  505. newFile.setLastSyncDateForData(localFile.lastModified());
  506. } // don't worry about not assigning size, the problems with localPath
  507. // are checked when the UploadFileOperation instance is created
  508. // MIME type
  509. if (mimeType == null || mimeType.length() <= 0) {
  510. try {
  511. mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
  512. remotePath.substring(remotePath.lastIndexOf('.') + 1));
  513. } catch (IndexOutOfBoundsException e) {
  514. Log.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
  515. }
  516. }
  517. if (mimeType == null) {
  518. mimeType = "application/octet-stream";
  519. }
  520. newFile.setMimetype(mimeType);
  521. // parent dir
  522. String parentPath = new File(remotePath).getParent();
  523. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
  524. OCFile parentDir = storageManager.getFileByPath(parentPath);
  525. if (parentDir == null) {
  526. Toast t = Toast
  527. .makeText(
  528. getApplicationContext(),
  529. "The first time the InstantUpload is running you must be online, so the target folder can successfully created by the upload process",
  530. 30);
  531. t.show();
  532. return null;
  533. }
  534. long parentDirId = parentDir.getFileId();
  535. newFile.setParentId(parentDirId);
  536. return newFile;
  537. }
  538. /**
  539. * Creates a status notification to show the upload progress
  540. *
  541. * @param upload Upload operation starting.
  542. */
  543. private void notifyUploadStart(UploadFileOperation upload) {
  544. // / create status notification with a progress bar
  545. mLastPercent = 0;
  546. mNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_in_progress_ticker),
  547. System.currentTimeMillis());
  548. mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
  549. mDefaultNotificationContentView = mNotification.contentView;
  550. mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(),
  551. R.layout.progressbar_layout);
  552. mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
  553. mNotification.contentView.setTextViewText(R.id.status_text,
  554. String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
  555. mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
  556. // / includes a pending intent in the notification showing the details
  557. // view of the file
  558. Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
  559. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
  560. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
  561. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  562. mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
  563. (int) System.currentTimeMillis(), showDetailsIntent, 0);
  564. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
  565. }
  566. /**
  567. * Callback method to update the progress bar in the status notification
  568. */
  569. @Override
  570. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
  571. int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
  572. if (percent != mLastPercent) {
  573. mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
  574. String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
  575. mNotification.contentView.setTextViewText(R.id.status_text, text);
  576. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
  577. }
  578. mLastPercent = percent;
  579. }
  580. /**
  581. * Callback method to update the progress bar in the status notification
  582. * (old version)
  583. */
  584. @Override
  585. public void onTransferProgress(long progressRate) {
  586. // NOTHING TO DO HERE ANYMORE
  587. }
  588. /**
  589. * Updates the status notification with the result of an upload operation.
  590. *
  591. * @param uploadResult Result of the upload operation.
  592. * @param upload Finished upload operation
  593. */
  594. private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
  595. Log.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
  596. if (uploadResult.isCancelled()) {
  597. // / cancelled operation -> silent removal of progress notification
  598. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  599. } else if (uploadResult.isSuccess()) {
  600. // / success -> silent update of progress notification to success
  601. // message
  602. mNotification.flags ^= Notification.FLAG_ONGOING_EVENT; // remove
  603. // the
  604. // ongoing
  605. // flag
  606. mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
  607. mNotification.contentView = mDefaultNotificationContentView;
  608. // / includes a pending intent in the notification showing the
  609. // details view of the file
  610. Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
  611. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
  612. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
  613. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  614. mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
  615. (int) System.currentTimeMillis(), showDetailsIntent, 0);
  616. mNotification.setLatestEventInfo(getApplicationContext(),
  617. getString(R.string.uploader_upload_succeeded_ticker),
  618. String.format(getString(R.string.uploader_upload_succeeded_content_single), upload.getFileName()),
  619. mNotification.contentIntent);
  620. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification); // NOT
  621. // AN
  622. DbHandler db = new DbHandler(this.getBaseContext());
  623. db.removeIUPendingFile(mCurrentUpload.getFile().getStoragePath());
  624. db.close();
  625. } else {
  626. // / fail -> explicit failure notification
  627. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  628. Notification finalNotification = new Notification(R.drawable.icon,
  629. getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
  630. finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
  631. Intent detailUploudIntent = new Intent(this, InstantUploadActivity.class);
  632. detailUploudIntent.putExtra(FileUploader.KEY_ACCOUNT, upload.getAccount());
  633. finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
  634. (int) System.currentTimeMillis(), detailUploudIntent, PendingIntent.FLAG_UPDATE_CURRENT
  635. | PendingIntent.FLAG_ONE_SHOT);
  636. String content = null;
  637. if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL
  638. || uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
  639. // TODO we need a class to provide error messages for the users
  640. // from a RemoteOperationResult and a RemoteOperation
  641. content = String.format(getString(R.string.error__upload__local_file_not_copied), upload.getFileName(),
  642. getString(R.string.app_name));
  643. } else {
  644. content = String
  645. .format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
  646. }
  647. finalNotification.setLatestEventInfo(getApplicationContext(),
  648. getString(R.string.uploader_upload_failed_ticker), content, finalNotification.contentIntent);
  649. mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
  650. DbHandler db = new DbHandler(this.getBaseContext());
  651. if (db.updateFileState(upload.getOriginalStoragePath(), DbHandler.UPLOAD_STATUS_UPLOAD_FAILED) == 0) {
  652. db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name);
  653. }
  654. db.close();
  655. }
  656. }
  657. /**
  658. * Sends a broadcast in order to the interested activities can update their
  659. * view
  660. *
  661. * @param upload Finished upload operation
  662. * @param uploadResult Result of the upload operation
  663. */
  664. private void sendFinalBroadcast(UploadFileOperation upload, RemoteOperationResult uploadResult) {
  665. Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
  666. end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  667. // path, after
  668. // possible
  669. // automatic
  670. // renaming
  671. if (upload.wasRenamed()) {
  672. end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
  673. }
  674. end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  675. end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  676. end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
  677. sendStickyBroadcast(end);
  678. }
  679. }