1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
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.
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.
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/>.
20 package com
.owncloud
.android
.files
.services
;
23 import java
.io
.IOException
;
24 import java
.util
.AbstractList
;
25 import java
.util
.Iterator
;
26 import java
.util
.Vector
;
27 import java
.util
.concurrent
.ConcurrentHashMap
;
28 import java
.util
.concurrent
.ConcurrentMap
;
30 import org
.apache
.http
.HttpStatus
;
31 import org
.apache
.jackrabbit
.webdav
.MultiStatus
;
32 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
34 import com
.owncloud
.android
.authentication
.AccountAuthenticator
;
35 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
36 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
37 import com
.owncloud
.android
.datamodel
.OCFile
;
38 import com
.owncloud
.android
.files
.InstantUploadBroadcastReceiver
;
39 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
40 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
41 import com
.owncloud
.android
.operations
.RemoteOperation
;
42 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
43 import com
.owncloud
.android
.operations
.UploadFileOperation
;
44 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
45 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
46 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
47 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
49 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
50 import eu
.alefzero
.webdav
.WebdavEntry
;
51 import eu
.alefzero
.webdav
.WebdavUtils
;
53 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
55 import android
.accounts
.Account
;
56 import android
.accounts
.AccountManager
;
57 import android
.accounts
.AccountsException
;
58 import android
.app
.Notification
;
59 import android
.app
.NotificationManager
;
60 import android
.app
.PendingIntent
;
61 import android
.app
.Service
;
62 import android
.content
.Intent
;
63 import android
.os
.Binder
;
64 import android
.os
.Handler
;
65 import android
.os
.HandlerThread
;
66 import android
.os
.IBinder
;
67 import android
.os
.Looper
;
68 import android
.os
.Message
;
69 import android
.os
.Process
;
70 import android
.util
.Log
;
71 import android
.webkit
.MimeTypeMap
;
72 import android
.widget
.RemoteViews
;
74 import com
.owncloud
.android
.R
;
75 import eu
.alefzero
.webdav
.WebdavClient
;
77 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
79 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
80 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
81 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
82 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
83 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
84 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
86 public static final String KEY_FILE
= "FILE";
87 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
88 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
89 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
91 public static final String KEY_ACCOUNT
= "ACCOUNT";
93 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
94 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
95 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
96 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
98 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
99 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
100 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
102 public static final int UPLOAD_SINGLE_FILE
= 0;
103 public static final int UPLOAD_MULTIPLE_FILES
= 1;
105 private static final String TAG
= FileUploader
.class.getSimpleName();
107 private Looper mServiceLooper
;
108 private ServiceHandler mServiceHandler
;
109 private IBinder mBinder
;
110 private WebdavClient mUploadClient
= null
;
111 private Account mLastAccount
= null
;
112 private FileDataStorageManager mStorageManager
;
114 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
115 private UploadFileOperation mCurrentUpload
= null
;
117 private NotificationManager mNotificationManager
;
118 private Notification mNotification
;
119 private int mLastPercent
;
120 private RemoteViews mDefaultNotificationContentView
;
124 * Builds a key for mPendingUploads from the account and file to upload
126 * @param account Account where the file to download is stored
127 * @param file File to download
129 private String
buildRemoteName(Account account
, OCFile file
) {
130 return account
.name
+ file
.getRemotePath();
133 private String
buildRemoteName(Account account
, String remotePath
) {
134 return account
.name
+ remotePath
;
139 * Checks if an ownCloud server version should support chunked uploads.
141 * @param version OwnCloud version instance corresponding to an ownCloud server.
142 * @return 'True' if the ownCloud server with version supports chunked uploads.
144 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
145 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
151 * Service initialization
154 public void onCreate() {
156 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
157 HandlerThread thread
= new HandlerThread("FileUploaderThread",
158 Process
.THREAD_PRIORITY_BACKGROUND
);
160 mServiceLooper
= thread
.getLooper();
161 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
162 mBinder
= new FileUploaderBinder();
167 * Entry point to add one or several files to the queue of uploads.
169 * New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
170 * although the caller activity goes away.
173 public int onStartCommand(Intent intent
, int flags
, int startId
) {
174 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
) || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
175 Log
.e(TAG
, "Not enough information provided in intent");
176 return Service
.START_NOT_STICKY
;
178 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
179 if (uploadType
== -1) {
180 Log
.e(TAG
, "Incorrect upload type provided");
181 return Service
.START_NOT_STICKY
;
183 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
185 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
186 OCFile
[] files
= null
;
187 if (uploadType
== UPLOAD_SINGLE_FILE
) {
189 if (intent
.hasExtra(KEY_FILE
)) {
190 files
= new OCFile
[] {intent
.getParcelableExtra(KEY_FILE
) };
193 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
194 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
195 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
198 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
200 if (intent
.hasExtra(KEY_FILE
)) {
201 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO will this casting work fine?
204 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
205 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
206 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
210 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
212 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
213 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
214 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
215 boolean fixed
= false
;
217 fixed
= checkAndFixInstantUploadDirectory(storageManager
); // MUST be done BEFORE calling obtainNewOCFileToUpload
220 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
221 Log
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
222 return Service
.START_NOT_STICKY
;
224 } else if (!intent
.hasExtra(KEY_FILE
)) {
225 if (localPaths
== null
) {
226 Log
.e(TAG
, "Incorrect array for local paths provided in upload intent");
227 return Service
.START_NOT_STICKY
;
229 if (remotePaths
== null
) {
230 Log
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
231 return Service
.START_NOT_STICKY
;
233 if (localPaths
.length
!= remotePaths
.length
) {
234 Log
.e(TAG
, "Different number of remote paths and local paths!");
235 return Service
.START_NOT_STICKY
;
238 files
= new OCFile
[localPaths
.length
];
239 for (int i
=0; i
< localPaths
.length
; i
++) {
240 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!=null
)?mimeTypes
[i
]:(String
)null
), storageManager
);
244 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
245 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
246 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
247 String uploadKey
= null
;
248 UploadFileOperation newUpload
= null
;
250 for (int i
=0; i
< files
.length
; i
++) {
251 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
253 newUpload
= new ChunkedUploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
255 newUpload
= new UploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
258 newUpload
.setRemoteFolderToBeCreated();
260 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
261 newUpload
.addDatatransferProgressListener(this);
262 requestedUploads
.add(uploadKey
);
265 } catch (IllegalArgumentException e
) {
266 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
267 return START_NOT_STICKY
;
269 } catch (IllegalStateException e
) {
270 Log
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
271 return START_NOT_STICKY
;
273 } catch (Exception e
) {
274 Log
.e(TAG
, "Unexpected exception while processing upload intent", e
);
275 return START_NOT_STICKY
;
279 if (requestedUploads
.size() > 0) {
280 Message msg
= mServiceHandler
.obtainMessage();
282 msg
.obj
= requestedUploads
;
283 mServiceHandler
.sendMessage(msg
);
286 return Service
.START_NOT_STICKY
;
291 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
293 * Implemented to perform cancellation, pause and resume of existing uploads.
296 public IBinder
onBind(Intent arg0
) {
301 * Binder to let client components to perform operations on the queue of uploads.
303 * It provides by itself the available operations.
305 public class FileUploaderBinder
extends Binder
{
308 * Cancels a pending or current upload of a remote file.
310 * @param account Owncloud account where the remote file will be stored.
311 * @param file A file in the queue of pending uploads
313 public void cancel(Account account
, OCFile file
) {
314 UploadFileOperation upload
= null
;
315 synchronized (mPendingUploads
) {
316 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
318 if (upload
!= null
) {
325 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
327 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
329 * @param account Owncloud account where the remote file will be stored.
330 * @param file A file that could be in the queue of pending uploads
332 public boolean isUploading(Account account
, OCFile file
) {
333 if (account
== null
|| file
== null
) return false
;
334 String targetKey
= buildRemoteName(account
, file
);
335 synchronized (mPendingUploads
) {
336 if (file
.isDirectory()) {
337 // this can be slow if there are many downloads :(
338 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
339 boolean found
= false
;
340 while (it
.hasNext() && !found
) {
341 found
= it
.next().startsWith(targetKey
);
345 return (mPendingUploads
.containsKey(targetKey
));
355 * Upload worker. Performs the pending uploads in the order they were requested.
357 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
359 private static class ServiceHandler
extends Handler
{
360 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
361 FileUploader mService
;
362 public ServiceHandler(Looper looper
, FileUploader service
) {
365 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
370 public void handleMessage(Message msg
) {
371 @SuppressWarnings("unchecked")
372 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
373 if (msg
.obj
!= null
) {
374 Iterator
<String
> it
= requestedUploads
.iterator();
375 while (it
.hasNext()) {
376 mService
.uploadFile(it
.next());
379 mService
.stopSelf(msg
.arg1
);
387 * Core upload method: sends the file(s) to upload
389 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
391 public void uploadFile(String uploadKey
) {
393 synchronized(mPendingUploads
) {
394 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
397 if (mCurrentUpload
!= null
) {
399 notifyUploadStart(mCurrentUpload
);
401 RemoteOperationResult uploadResult
= null
;
404 /// prepare client object to send requests to the ownCloud server
405 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
406 mLastAccount
= mCurrentUpload
.getAccount();
407 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
408 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
411 /// create remote folder for instant uploads
412 if (mCurrentUpload
.isRemoteFolderToBeCreated()) {
413 RemoteOperation operation
= new CreateFolderOperation( InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
,
414 mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId(), // TODO generalize this : INSTANT_UPLOAD_DIR could not be a child of root
416 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
420 /// perform the upload
421 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
422 if (uploadResult
.isSuccess()) {
426 } catch (AccountsException e
) {
427 Log
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
428 uploadResult
= new RemoteOperationResult(e
);
430 } catch (IOException e
) {
431 Log
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
432 uploadResult
= new RemoteOperationResult(e
);
435 synchronized(mPendingUploads
) {
436 mPendingUploads
.remove(uploadKey
);
441 notifyUploadResult(uploadResult
, mCurrentUpload
);
443 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
450 * Saves a OC File after a successful upload.
452 * A PROPFIND is necessary to keep the props in the local database synchronized with the server,
453 * specially the modification time and Etag (where available)
455 * TODO refactor this ugly thing
457 private void saveUploadedFile() {
458 OCFile file
= mCurrentUpload
.getFile();
459 long syncDate
= System
.currentTimeMillis();
460 file
.setLastSyncDateForData(syncDate
);
462 /// new PROPFIND to keep data consistent with server in theory, should return the same we already have
463 PropFindMethod propfind
= null
;
464 RemoteOperationResult result
= null
;
466 propfind
= new PropFindMethod(mUploadClient
.getBaseUri() + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
467 int status
= mUploadClient
.executeMethod(propfind
);
468 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
470 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
471 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0],
472 mUploadClient
.getBaseUri().getPath());
473 updateOCFile(file
, we
);
474 file
.setLastSyncDateForProperties(syncDate
);
477 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
480 result
= new RemoteOperationResult(isMultiStatus
, status
);
481 Log
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage());
483 } catch (Exception e
) {
484 result
= new RemoteOperationResult(e
);
485 Log
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage(), e
);
488 if (propfind
!= null
)
489 propfind
.releaseConnection();
492 /// maybe this would be better as part of UploadFileOperation... or maybe all this method
493 if (mCurrentUpload
.wasRenamed()) {
494 OCFile oldFile
= mCurrentUpload
.getOldFile();
495 if (oldFile
.fileExists()) {
496 oldFile
.setStoragePath(null
);
497 mStorageManager
.saveFile(oldFile
);
499 } // 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()
502 mStorageManager
.saveFile(file
);
506 private void updateOCFile(OCFile file
, WebdavEntry we
) {
507 file
.setCreationTimestamp(we
.createTimestamp());
508 file
.setFileLength(we
.contentLength());
509 file
.setMimetype(we
.contentType());
510 file
.setModificationTimestamp(we
.modifiedTimestamp());
511 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
512 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
516 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
517 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
518 if (instantUploadDir
== null
) {
519 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
520 OCFile newDir
= new OCFile(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
521 newDir
.setMimetype("DIR");
522 newDir
.setParentId(storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId());
523 storageManager
.saveFile(newDir
);
530 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
, FileDataStorageManager storageManager
) {
531 OCFile newFile
= new OCFile(remotePath
);
532 newFile
.setStoragePath(localPath
);
533 newFile
.setLastSyncDateForProperties(0);
534 newFile
.setLastSyncDateForData(0);
537 if (localPath
!= null
&& localPath
.length() > 0) {
538 File localFile
= new File(localPath
);
539 newFile
.setFileLength(localFile
.length());
540 newFile
.setLastSyncDateForData(localFile
.lastModified());
541 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
544 if (mimeType
== null
|| mimeType
.length() <= 0) {
546 mimeType
= MimeTypeMap
.getSingleton()
547 .getMimeTypeFromExtension(
548 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
549 } catch (IndexOutOfBoundsException e
) {
550 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
553 if (mimeType
== null
) {
554 mimeType
= "application/octet-stream";
556 newFile
.setMimetype(mimeType
);
559 String parentPath
= new File(remotePath
).getParent();
560 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
561 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
562 if (parentDir
== null
) {
563 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath
);
565 long parentDirId
= parentDir
.getFileId();
566 newFile
.setParentId(parentDirId
);
572 * Creates a status notification to show the upload progress
574 * @param upload Upload operation starting.
576 private void notifyUploadStart(UploadFileOperation upload
) {
577 /// create status notification with a progress bar
579 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
580 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
581 mDefaultNotificationContentView
= mNotification
.contentView
;
582 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
583 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
584 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
585 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
587 /// includes a pending intent in the notification showing the details view of the file
588 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
589 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
590 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
591 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
592 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
594 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
599 * Callback method to update the progress bar in the status notification
602 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
603 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
604 if (percent
!= mLastPercent
) {
605 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
606 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
607 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
608 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
610 mLastPercent
= percent
;
615 * Callback method to update the progress bar in the status notification (old version)
618 public void onTransferProgress(long progressRate
) {
619 // NOTHING TO DO HERE ANYMORE
624 * Updates the status notification with the result of an upload operation.
626 * @param uploadResult Result of the upload operation.
627 * @param upload Finished upload operation
629 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
630 if (uploadResult
.isCancelled()) {
631 /// cancelled operation -> silent removal of progress notification
632 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
634 } else if (uploadResult
.isSuccess()) {
635 /// success -> silent update of progress notification to success message
636 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
637 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
638 mNotification
.contentView
= mDefaultNotificationContentView
;
640 /// includes a pending intent in the notification showing the details view of the file
641 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
642 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
643 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
644 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
645 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
647 mNotification
.setLatestEventInfo( getApplicationContext(),
648 getString(R
.string
.uploader_upload_succeeded_ticker
),
649 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
650 mNotification
.contentIntent
);
652 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
654 /* Notification about multiple uploads: pending of update
655 mNotification.setLatestEventInfo( getApplicationContext(),
656 getString(R.string.uploader_upload_succeeded_ticker),
657 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
658 mNotification.contentIntent);
662 /// fail -> explicit failure notification
663 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
664 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
665 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
666 if (uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
) {
667 // let the user update credentials with one click
668 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
669 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
670 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
671 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
672 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
673 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
674 finalNotification
.contentIntent
= PendingIntent
.getActivity(this, (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
675 mUploadClient
= null
; // grant that future retries on the same account will get the fresh credentials
677 // TODO put something smart in the contentIntent below
678 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
681 String content
= null
;
682 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
||
683 uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
684 // TODO we need a class to provide error messages for the users from a RemoteOperationResult and a RemoteOperation
685 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(), getString(R
.string
.app_name
));
687 content
= String
.format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
689 finalNotification
.setLatestEventInfo( getApplicationContext(),
690 getString(R
.string
.uploader_upload_failed_ticker
),
692 finalNotification
.contentIntent
);
694 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
696 /* Notification about multiple uploads failure: pending of update
697 finalNotification.setLatestEventInfo( getApplicationContext(),
698 getString(R.string.uploader_upload_failed_ticker),
699 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
700 finalNotification.contentIntent);
708 * Sends a broadcast in order to the interested activities can update their view
710 * @param upload Finished upload operation
711 * @param uploadResult Result of the upload operation
713 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
714 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
715 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote path, after possible automatic renaming
716 if (upload
.wasRenamed()) {
717 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
719 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
720 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
721 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
722 sendStickyBroadcast(end
);