FileUploader.java 32 KB

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