1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
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.
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.
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/>.
19 package com
.owncloud
.android
.files
.services
;
22 import java
.io
.IOException
;
23 import java
.util
.AbstractList
;
24 import java
.util
.Iterator
;
25 import java
.util
.Vector
;
26 import java
.util
.concurrent
.ConcurrentHashMap
;
27 import java
.util
.concurrent
.ConcurrentMap
;
29 import org
.apache
.http
.HttpStatus
;
30 import org
.apache
.jackrabbit
.webdav
.MultiStatus
;
31 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
33 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
34 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
35 import com
.owncloud
.android
.datamodel
.OCFile
;
36 import com
.owncloud
.android
.files
.InstantUploadBroadcastReceiver
;
37 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
38 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
39 import com
.owncloud
.android
.operations
.RemoteOperation
;
40 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
41 import com
.owncloud
.android
.operations
.UploadFileOperation
;
42 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
43 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
44 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
45 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
47 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
48 import eu
.alefzero
.webdav
.WebdavEntry
;
49 import eu
.alefzero
.webdav
.WebdavUtils
;
51 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
53 import android
.accounts
.Account
;
54 import android
.accounts
.AccountManager
;
55 import android
.accounts
.AccountsException
;
56 import android
.app
.Notification
;
57 import android
.app
.NotificationManager
;
58 import android
.app
.PendingIntent
;
59 import android
.app
.Service
;
60 import android
.content
.Intent
;
61 import android
.os
.Binder
;
62 import android
.os
.Handler
;
63 import android
.os
.HandlerThread
;
64 import android
.os
.IBinder
;
65 import android
.os
.Looper
;
66 import android
.os
.Message
;
67 import android
.os
.Process
;
68 import android
.util
.Log
;
69 import android
.webkit
.MimeTypeMap
;
70 import android
.widget
.RemoteViews
;
72 import com
.owncloud
.android
.R
;
73 import eu
.alefzero
.webdav
.WebdavClient
;
75 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
77 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
78 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
79 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
80 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
81 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
82 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
84 public static final String KEY_FILE
= "FILE";
85 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
86 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
87 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
89 public static final String KEY_ACCOUNT
= "ACCOUNT";
91 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
92 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
93 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
94 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
96 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
97 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
98 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
100 public static final int UPLOAD_SINGLE_FILE
= 0;
101 public static final int UPLOAD_MULTIPLE_FILES
= 1;
103 private static final String TAG
= FileUploader
.class.getSimpleName();
105 private Looper mServiceLooper
;
106 private ServiceHandler mServiceHandler
;
107 private IBinder mBinder
;
108 private WebdavClient mUploadClient
= null
;
109 private Account mLastAccount
= null
;
110 private FileDataStorageManager mStorageManager
;
112 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
113 private UploadFileOperation mCurrentUpload
= null
;
115 private NotificationManager mNotificationManager
;
116 private Notification mNotification
;
117 private int mLastPercent
;
118 private RemoteViews mDefaultNotificationContentView
;
122 * Builds a key for mPendingUploads from the account and file to upload
124 * @param account Account where the file to download is stored
125 * @param file File to download
127 private String
buildRemoteName(Account account
, OCFile file
) {
128 return account
.name
+ file
.getRemotePath();
131 private String
buildRemoteName(Account account
, String remotePath
) {
132 return account
.name
+ remotePath
;
137 * Checks if an ownCloud server version should support chunked uploads.
139 * @param version OwnCloud version instance corresponding to an ownCloud server.
140 * @return 'True' if the ownCloud server with version supports chunked uploads.
142 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
143 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
149 * Service initialization
152 public void onCreate() {
154 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
155 HandlerThread thread
= new HandlerThread("FileUploaderThread",
156 Process
.THREAD_PRIORITY_BACKGROUND
);
158 mServiceLooper
= thread
.getLooper();
159 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
160 mBinder
= new FileUploaderBinder();
165 * Entry point to add one or several files to the queue of uploads.
167 * New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
168 * although the caller activity goes away.
171 public int onStartCommand(Intent intent
, int flags
, int startId
) {
172 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
) || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
173 Log
.e(TAG
, "Not enough information provided in intent");
174 return Service
.START_NOT_STICKY
;
176 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
177 if (uploadType
== -1) {
178 Log
.e(TAG
, "Incorrect upload type provided");
179 return Service
.START_NOT_STICKY
;
181 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
183 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
184 OCFile
[] files
= null
;
185 if (uploadType
== UPLOAD_SINGLE_FILE
) {
187 if (intent
.hasExtra(KEY_FILE
)) {
188 files
= new OCFile
[] {intent
.getParcelableExtra(KEY_FILE
) };
191 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
192 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
193 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
196 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
198 if (intent
.hasExtra(KEY_FILE
)) {
199 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO will this casting work fine?
202 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
203 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
204 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
208 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
210 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
211 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
212 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
213 boolean fixed
= false
;
215 fixed
= checkAndFixInstantUploadDirectory(storageManager
); // MUST be done BEFORE calling obtainNewOCFileToUpload
218 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
219 Log
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
220 return Service
.START_NOT_STICKY
;
222 } else if (!intent
.hasExtra(KEY_FILE
)) {
223 if (localPaths
== null
) {
224 Log
.e(TAG
, "Incorrect array for local paths provided in upload intent");
225 return Service
.START_NOT_STICKY
;
227 if (remotePaths
== null
) {
228 Log
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
229 return Service
.START_NOT_STICKY
;
231 if (localPaths
.length
!= remotePaths
.length
) {
232 Log
.e(TAG
, "Different number of remote paths and local paths!");
233 return Service
.START_NOT_STICKY
;
236 files
= new OCFile
[localPaths
.length
];
237 for (int i
=0; i
< localPaths
.length
; i
++) {
238 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!=null
)?mimeTypes
[i
]:(String
)null
), storageManager
);
242 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
243 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
244 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
245 String uploadKey
= null
;
246 UploadFileOperation newUpload
= null
;
248 for (int i
=0; i
< files
.length
; i
++) {
249 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
251 newUpload
= new ChunkedUploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
253 newUpload
= new UploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
256 newUpload
.setRemoteFolderToBeCreated();
258 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
259 newUpload
.addDatatransferProgressListener(this);
260 requestedUploads
.add(uploadKey
);
263 } catch (IllegalArgumentException e
) {
264 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
265 return START_NOT_STICKY
;
267 } catch (IllegalStateException e
) {
268 Log
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
269 return START_NOT_STICKY
;
271 } catch (Exception e
) {
272 Log
.e(TAG
, "Unexpected exception while processing upload intent", e
);
273 return START_NOT_STICKY
;
277 if (requestedUploads
.size() > 0) {
278 Message msg
= mServiceHandler
.obtainMessage();
280 msg
.obj
= requestedUploads
;
281 mServiceHandler
.sendMessage(msg
);
284 return Service
.START_NOT_STICKY
;
289 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
291 * Implemented to perform cancellation, pause and resume of existing uploads.
294 public IBinder
onBind(Intent arg0
) {
299 * Binder to let client components to perform operations on the queue of uploads.
301 * It provides by itself the available operations.
303 public class FileUploaderBinder
extends Binder
{
306 * Cancels a pending or current upload of a remote file.
308 * @param account Owncloud account where the remote file will be stored.
309 * @param file A file in the queue of pending uploads
311 public void cancel(Account account
, OCFile file
) {
312 UploadFileOperation upload
= null
;
313 synchronized (mPendingUploads
) {
314 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
316 if (upload
!= null
) {
323 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
325 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
327 * @param account Owncloud account where the remote file will be stored.
328 * @param file A file that could be in the queue of pending uploads
330 public boolean isUploading(Account account
, OCFile file
) {
331 String targetKey
= buildRemoteName(account
, file
);
332 synchronized (mPendingUploads
) {
333 if (file
.isDirectory()) {
334 // this can be slow if there are many downloads :(
335 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
336 boolean found
= false
;
337 while (it
.hasNext() && !found
) {
338 found
= it
.next().startsWith(targetKey
);
342 return (mPendingUploads
.containsKey(targetKey
));
352 * Upload worker. Performs the pending uploads in the order they were requested.
354 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
356 private static class ServiceHandler
extends Handler
{
357 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
358 FileUploader mService
;
359 public ServiceHandler(Looper looper
, FileUploader service
) {
362 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
367 public void handleMessage(Message msg
) {
368 @SuppressWarnings("unchecked")
369 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
370 if (msg
.obj
!= null
) {
371 Iterator
<String
> it
= requestedUploads
.iterator();
372 while (it
.hasNext()) {
373 mService
.uploadFile(it
.next());
376 mService
.stopSelf(msg
.arg1
);
384 * Core upload method: sends the file(s) to upload
386 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
388 public void uploadFile(String uploadKey
) {
390 synchronized(mPendingUploads
) {
391 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
394 if (mCurrentUpload
!= null
) {
396 notifyUploadStart(mCurrentUpload
);
398 RemoteOperationResult uploadResult
= null
;
401 /// prepare client object to send requests to the ownCloud server
402 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
403 mLastAccount
= mCurrentUpload
.getAccount();
404 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
405 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
408 /// create remote folder for instant uploads
409 if (mCurrentUpload
.isRemoteFolderToBeCreated()) {
410 RemoteOperation operation
= new CreateFolderOperation( InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
,
411 mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId(), // TODO generalize this : INSTANT_UPLOAD_DIR could not be a child of root
413 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
417 /// perform the upload
418 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
419 if (uploadResult
.isSuccess()) {
423 } catch (AccountsException e
) {
424 Log
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
425 uploadResult
= new RemoteOperationResult(e
);
427 } catch (IOException e
) {
428 Log
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
429 uploadResult
= new RemoteOperationResult(e
);
432 synchronized(mPendingUploads
) {
433 mPendingUploads
.remove(uploadKey
);
438 notifyUploadResult(uploadResult
, mCurrentUpload
);
440 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
447 * Saves a OC File after a successful upload.
449 * A PROPFIND is necessary to keep the props in the local database synchronized with the server,
450 * specially the modification time and Etag (where available)
452 * TODO refactor this ugly thing
454 private void saveUploadedFile() {
455 OCFile file
= mCurrentUpload
.getFile();
456 long syncDate
= System
.currentTimeMillis();
457 file
.setLastSyncDateForData(syncDate
);
459 /// new PROPFIND to keep data consistent with server in theory, should return the same we already have
460 PropFindMethod propfind
= null
;
461 RemoteOperationResult result
= null
;
463 propfind
= new PropFindMethod(mUploadClient
.getBaseUri() + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
464 int status
= mUploadClient
.executeMethod(propfind
);
465 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
467 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
468 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0],
469 mUploadClient
.getBaseUri().getPath());
470 updateOCFile(file
, we
);
471 file
.setLastSyncDateForProperties(syncDate
);
474 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
477 result
= new RemoteOperationResult(isMultiStatus
, status
);
478 Log
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage());
480 } catch (Exception e
) {
481 result
= new RemoteOperationResult(e
);
482 Log
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage(), e
);
485 if (propfind
!= null
)
486 propfind
.releaseConnection();
489 /// maybe this would be better as part of UploadFileOperation... or maybe all this method
490 if (mCurrentUpload
.wasRenamed()) {
491 OCFile oldFile
= mCurrentUpload
.getOldFile();
492 if (oldFile
.fileExists()) {
493 oldFile
.setStoragePath(null
);
494 mStorageManager
.saveFile(oldFile
);
496 } // 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()
499 mStorageManager
.saveFile(file
);
503 private void updateOCFile(OCFile file
, WebdavEntry we
) {
504 file
.setCreationTimestamp(we
.createTimestamp());
505 file
.setFileLength(we
.contentLength());
506 file
.setMimetype(we
.contentType());
507 file
.setModificationTimestamp(we
.modifiedTimestamp());
508 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
509 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
513 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
514 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
515 if (instantUploadDir
== null
) {
516 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
517 OCFile newDir
= new OCFile(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
518 newDir
.setMimetype("DIR");
519 newDir
.setParentId(storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId());
520 storageManager
.saveFile(newDir
);
527 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
, FileDataStorageManager storageManager
) {
528 OCFile newFile
= new OCFile(remotePath
);
529 newFile
.setStoragePath(localPath
);
530 newFile
.setLastSyncDateForProperties(0);
531 newFile
.setLastSyncDateForData(0);
534 if (localPath
!= null
&& localPath
.length() > 0) {
535 File localFile
= new File(localPath
);
536 newFile
.setFileLength(localFile
.length());
537 newFile
.setLastSyncDateForData(localFile
.lastModified());
538 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
541 if (mimeType
== null
|| mimeType
.length() <= 0) {
543 mimeType
= MimeTypeMap
.getSingleton()
544 .getMimeTypeFromExtension(
545 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
546 } catch (IndexOutOfBoundsException e
) {
547 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
550 if (mimeType
== null
) {
551 mimeType
= "application/octet-stream";
553 newFile
.setMimetype(mimeType
);
556 String parentPath
= new File(remotePath
).getParent();
557 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
558 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
559 if (parentDir
== null
) {
560 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath
);
562 long parentDirId
= parentDir
.getFileId();
563 newFile
.setParentId(parentDirId
);
569 * Creates a status notification to show the upload progress
571 * @param upload Upload operation starting.
573 private void notifyUploadStart(UploadFileOperation upload
) {
574 /// create status notification with a progress bar
576 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
577 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
578 mDefaultNotificationContentView
= mNotification
.contentView
;
579 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
580 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
581 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
582 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
584 /// includes a pending intent in the notification showing the details view of the file
585 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
586 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
587 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
588 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
589 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
591 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
596 * Callback method to update the progress bar in the status notification
599 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
600 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
601 if (percent
!= mLastPercent
) {
602 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
603 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
604 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
605 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
607 mLastPercent
= percent
;
612 * Callback method to update the progress bar in the status notification (old version)
615 public void onTransferProgress(long progressRate
) {
616 // NOTHING TO DO HERE ANYMORE
621 * Updates the status notification with the result of an upload operation.
623 * @param uploadResult Result of the upload operation.
624 * @param upload Finished upload operation
626 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
627 if (uploadResult
.isCancelled()) {
628 /// cancelled operation -> silent removal of progress notification
629 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
631 } else if (uploadResult
.isSuccess()) {
632 /// success -> silent update of progress notification to success message
633 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
634 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
635 mNotification
.contentView
= mDefaultNotificationContentView
;
637 /// includes a pending intent in the notification showing the details view of the file
638 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
639 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
640 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
641 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
642 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
644 mNotification
.setLatestEventInfo( getApplicationContext(),
645 getString(R
.string
.uploader_upload_succeeded_ticker
),
646 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
647 mNotification
.contentIntent
);
649 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
651 /* Notification about multiple uploads: pending of update
652 mNotification.setLatestEventInfo( getApplicationContext(),
653 getString(R.string.uploader_upload_succeeded_ticker),
654 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
655 mNotification.contentIntent);
659 /// fail -> explicit failure notification
660 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
661 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
662 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
663 // TODO put something smart in the contentIntent below
664 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
666 String content
= null
;
667 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
||
668 uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
669 // TODO we need a class to provide error messages for the users from a RemoteOperationResult and a RemoteOperation
670 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(), getString(R
.string
.app_name
));
672 content
= String
.format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
674 finalNotification
.setLatestEventInfo( getApplicationContext(),
675 getString(R
.string
.uploader_upload_failed_ticker
),
677 finalNotification
.contentIntent
);
679 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
681 /* Notification about multiple uploads failure: pending of update
682 finalNotification.setLatestEventInfo( getApplicationContext(),
683 getString(R.string.uploader_upload_failed_ticker),
684 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
685 finalNotification.contentIntent);
693 * Sends a broadcast in order to the interested activities can update their view
695 * @param upload Finished upload operation
696 * @param uploadResult Result of the upload operation
698 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
699 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
700 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote path, after possible automatic renaming
701 if (upload
.wasRenamed()) {
702 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
704 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
705 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
706 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
707 sendStickyBroadcast(end
);