FileUploader.java 31 KB

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