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
.authenticator
.AccountAuthenticator
;
35 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
36 import com
.owncloud
.android
.datamodel
.OCFile
;
37 import com
.owncloud
.android
.files
.InstantUploadBroadcastReceiver
;
38 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
39 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
40 import com
.owncloud
.android
.operations
.RemoteOperation
;
41 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
42 import com
.owncloud
.android
.operations
.UploadFileOperation
;
43 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
44 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
45 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
46 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
48 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
49 import eu
.alefzero
.webdav
.WebdavEntry
;
50 import eu
.alefzero
.webdav
.WebdavUtils
;
52 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
54 import android
.accounts
.Account
;
55 import android
.accounts
.AccountManager
;
56 import android
.accounts
.AccountsException
;
57 import android
.app
.Notification
;
58 import android
.app
.NotificationManager
;
59 import android
.app
.PendingIntent
;
60 import android
.app
.Service
;
61 import android
.content
.Intent
;
62 import android
.os
.Binder
;
63 import android
.os
.Handler
;
64 import android
.os
.HandlerThread
;
65 import android
.os
.IBinder
;
66 import android
.os
.Looper
;
67 import android
.os
.Message
;
68 import android
.os
.Process
;
69 import android
.util
.Log
;
70 import android
.webkit
.MimeTypeMap
;
71 import android
.widget
.RemoteViews
;
73 import com
.owncloud
.android
.R
;
74 import eu
.alefzero
.webdav
.WebdavClient
;
76 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
78 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
79 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
80 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
81 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
82 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
83 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
85 public static final String KEY_FILE
= "FILE";
86 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
87 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
88 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
90 public static final String KEY_ACCOUNT
= "ACCOUNT";
92 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
93 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
94 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
95 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
97 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
98 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
99 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
101 public static final int UPLOAD_SINGLE_FILE
= 0;
102 public static final int UPLOAD_MULTIPLE_FILES
= 1;
104 private static final String TAG
= FileUploader
.class.getSimpleName();
106 private Looper mServiceLooper
;
107 private ServiceHandler mServiceHandler
;
108 private IBinder mBinder
;
109 private WebdavClient mUploadClient
= null
;
110 private Account mLastAccount
= null
;
111 private FileDataStorageManager mStorageManager
;
113 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
114 private UploadFileOperation mCurrentUpload
= null
;
116 private NotificationManager mNotificationManager
;
117 private Notification mNotification
;
118 private int mLastPercent
;
119 private RemoteViews mDefaultNotificationContentView
;
123 * Builds a key for mPendingUploads from the account and file to upload
125 * @param account Account where the file to download is stored
126 * @param file File to download
128 private String
buildRemoteName(Account account
, OCFile file
) {
129 return account
.name
+ file
.getRemotePath();
132 private String
buildRemoteName(Account account
, String remotePath
) {
133 return account
.name
+ remotePath
;
138 * Checks if an ownCloud server version should support chunked uploads.
140 * @param version OwnCloud version instance corresponding to an ownCloud server.
141 * @return 'True' if the ownCloud server with version supports chunked uploads.
143 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
144 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
150 * Service initialization
153 public void onCreate() {
155 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
156 HandlerThread thread
= new HandlerThread("FileUploaderThread",
157 Process
.THREAD_PRIORITY_BACKGROUND
);
159 mServiceLooper
= thread
.getLooper();
160 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
161 mBinder
= new FileUploaderBinder();
166 * Entry point to add one or several files to the queue of uploads.
168 * New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
169 * although the caller activity goes away.
172 public int onStartCommand(Intent intent
, int flags
, int startId
) {
173 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
) || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
174 Log
.e(TAG
, "Not enough information provided in intent");
175 return Service
.START_NOT_STICKY
;
177 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
178 if (uploadType
== -1) {
179 Log
.e(TAG
, "Incorrect upload type provided");
180 return Service
.START_NOT_STICKY
;
182 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
184 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
185 OCFile
[] files
= null
;
186 if (uploadType
== UPLOAD_SINGLE_FILE
) {
188 if (intent
.hasExtra(KEY_FILE
)) {
189 files
= new OCFile
[] {intent
.getParcelableExtra(KEY_FILE
) };
192 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
193 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
194 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
197 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
199 if (intent
.hasExtra(KEY_FILE
)) {
200 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO will this casting work fine?
203 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
204 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
205 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
209 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
211 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
212 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
213 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
214 boolean fixed
= false
;
216 fixed
= checkAndFixInstantUploadDirectory(storageManager
); // MUST be done BEFORE calling obtainNewOCFileToUpload
219 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
220 Log
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
221 return Service
.START_NOT_STICKY
;
223 } else if (!intent
.hasExtra(KEY_FILE
)) {
224 if (localPaths
== null
) {
225 Log
.e(TAG
, "Incorrect array for local paths provided in upload intent");
226 return Service
.START_NOT_STICKY
;
228 if (remotePaths
== null
) {
229 Log
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
230 return Service
.START_NOT_STICKY
;
232 if (localPaths
.length
!= remotePaths
.length
) {
233 Log
.e(TAG
, "Different number of remote paths and local paths!");
234 return Service
.START_NOT_STICKY
;
237 files
= new OCFile
[localPaths
.length
];
238 for (int i
=0; i
< localPaths
.length
; i
++) {
239 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!=null
)?mimeTypes
[i
]:(String
)null
), storageManager
);
243 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
244 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
245 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
246 String uploadKey
= null
;
247 UploadFileOperation newUpload
= null
;
249 for (int i
=0; i
< files
.length
; i
++) {
250 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
252 newUpload
= new ChunkedUploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
254 newUpload
= new UploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
257 newUpload
.setRemoteFolderToBeCreated();
259 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
260 newUpload
.addDatatransferProgressListener(this);
261 requestedUploads
.add(uploadKey
);
264 } catch (IllegalArgumentException e
) {
265 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
266 return START_NOT_STICKY
;
268 } catch (IllegalStateException e
) {
269 Log
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
270 return START_NOT_STICKY
;
272 } catch (Exception e
) {
273 Log
.e(TAG
, "Unexpected exception while processing upload intent", e
);
274 return START_NOT_STICKY
;
278 if (requestedUploads
.size() > 0) {
279 Message msg
= mServiceHandler
.obtainMessage();
281 msg
.obj
= requestedUploads
;
282 mServiceHandler
.sendMessage(msg
);
285 return Service
.START_NOT_STICKY
;
290 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
292 * Implemented to perform cancellation, pause and resume of existing uploads.
295 public IBinder
onBind(Intent arg0
) {
300 * Binder to let client components to perform operations on the queue of uploads.
302 * It provides by itself the available operations.
304 public class FileUploaderBinder
extends Binder
{
307 * Cancels a pending or current upload of a remote file.
309 * @param account Owncloud account where the remote file will be stored.
310 * @param file A file in the queue of pending uploads
312 public void cancel(Account account
, OCFile file
) {
313 UploadFileOperation upload
= null
;
314 synchronized (mPendingUploads
) {
315 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
317 if (upload
!= null
) {
324 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
326 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
328 * @param account Owncloud account where the remote file will be stored.
329 * @param file A file that could be in the queue of pending uploads
331 public boolean isUploading(Account account
, OCFile file
) {
332 if (account
== null
|| file
== null
) return false
;
333 String targetKey
= buildRemoteName(account
, file
);
334 synchronized (mPendingUploads
) {
335 if (file
.isDirectory()) {
336 // this can be slow if there are many downloads :(
337 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
338 boolean found
= false
;
339 while (it
.hasNext() && !found
) {
340 found
= it
.next().startsWith(targetKey
);
344 return (mPendingUploads
.containsKey(targetKey
));
354 * Upload worker. Performs the pending uploads in the order they were requested.
356 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
358 private static class ServiceHandler
extends Handler
{
359 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
360 FileUploader mService
;
361 public ServiceHandler(Looper looper
, FileUploader service
) {
364 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
369 public void handleMessage(Message msg
) {
370 @SuppressWarnings("unchecked")
371 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
372 if (msg
.obj
!= null
) {
373 Iterator
<String
> it
= requestedUploads
.iterator();
374 while (it
.hasNext()) {
375 mService
.uploadFile(it
.next());
378 mService
.stopSelf(msg
.arg1
);
386 * Core upload method: sends the file(s) to upload
388 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
390 public void uploadFile(String uploadKey
) {
392 synchronized(mPendingUploads
) {
393 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
396 if (mCurrentUpload
!= null
) {
398 notifyUploadStart(mCurrentUpload
);
400 RemoteOperationResult uploadResult
= null
;
403 /// prepare client object to send requests to the ownCloud server
404 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
405 mLastAccount
= mCurrentUpload
.getAccount();
406 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
407 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
410 /// create remote folder for instant uploads
411 if (mCurrentUpload
.isRemoteFolderToBeCreated()) {
412 RemoteOperation operation
= new CreateFolderOperation( InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
,
413 mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId(), // TODO generalize this : INSTANT_UPLOAD_DIR could not be a child of root
415 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
419 /// perform the upload
420 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
421 if (uploadResult
.isSuccess()) {
425 } catch (AccountsException e
) {
426 Log
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
427 uploadResult
= new RemoteOperationResult(e
);
429 } catch (IOException e
) {
430 Log
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
431 uploadResult
= new RemoteOperationResult(e
);
434 synchronized(mPendingUploads
) {
435 mPendingUploads
.remove(uploadKey
);
440 notifyUploadResult(uploadResult
, mCurrentUpload
);
442 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
449 * Saves a OC File after a successful upload.
451 * A PROPFIND is necessary to keep the props in the local database synchronized with the server,
452 * specially the modification time and Etag (where available)
454 * TODO refactor this ugly thing
456 private void saveUploadedFile() {
457 OCFile file
= mCurrentUpload
.getFile();
458 long syncDate
= System
.currentTimeMillis();
459 file
.setLastSyncDateForData(syncDate
);
461 /// new PROPFIND to keep data consistent with server in theory, should return the same we already have
462 PropFindMethod propfind
= null
;
463 RemoteOperationResult result
= null
;
465 propfind
= new PropFindMethod(mUploadClient
.getBaseUri() + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
466 int status
= mUploadClient
.executeMethod(propfind
);
467 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
469 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
470 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0],
471 mUploadClient
.getBaseUri().getPath());
472 updateOCFile(file
, we
);
473 file
.setLastSyncDateForProperties(syncDate
);
476 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
479 result
= new RemoteOperationResult(isMultiStatus
, status
);
480 Log
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage());
482 } catch (Exception e
) {
483 result
= new RemoteOperationResult(e
);
484 Log
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage(), e
);
487 if (propfind
!= null
)
488 propfind
.releaseConnection();
491 /// maybe this would be better as part of UploadFileOperation... or maybe all this method
492 if (mCurrentUpload
.wasRenamed()) {
493 OCFile oldFile
= mCurrentUpload
.getOldFile();
494 if (oldFile
.fileExists()) {
495 oldFile
.setStoragePath(null
);
496 mStorageManager
.saveFile(oldFile
);
498 } // 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()
501 mStorageManager
.saveFile(file
);
505 private void updateOCFile(OCFile file
, WebdavEntry we
) {
506 file
.setCreationTimestamp(we
.createTimestamp());
507 file
.setFileLength(we
.contentLength());
508 file
.setMimetype(we
.contentType());
509 file
.setModificationTimestamp(we
.modifiedTimestamp());
510 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
511 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
515 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
516 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
517 if (instantUploadDir
== null
) {
518 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
519 OCFile newDir
= new OCFile(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
520 newDir
.setMimetype("DIR");
521 newDir
.setParentId(storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId());
522 storageManager
.saveFile(newDir
);
529 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
, FileDataStorageManager storageManager
) {
530 OCFile newFile
= new OCFile(remotePath
);
531 newFile
.setStoragePath(localPath
);
532 newFile
.setLastSyncDateForProperties(0);
533 newFile
.setLastSyncDateForData(0);
536 if (localPath
!= null
&& localPath
.length() > 0) {
537 File localFile
= new File(localPath
);
538 newFile
.setFileLength(localFile
.length());
539 newFile
.setLastSyncDateForData(localFile
.lastModified());
540 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
543 if (mimeType
== null
|| mimeType
.length() <= 0) {
545 mimeType
= MimeTypeMap
.getSingleton()
546 .getMimeTypeFromExtension(
547 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
548 } catch (IndexOutOfBoundsException e
) {
549 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
552 if (mimeType
== null
) {
553 mimeType
= "application/octet-stream";
555 newFile
.setMimetype(mimeType
);
558 String parentPath
= new File(remotePath
).getParent();
559 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
560 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
561 if (parentDir
== null
) {
562 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath
);
564 long parentDirId
= parentDir
.getFileId();
565 newFile
.setParentId(parentDirId
);
571 * Creates a status notification to show the upload progress
573 * @param upload Upload operation starting.
575 private void notifyUploadStart(UploadFileOperation upload
) {
576 /// create status notification with a progress bar
578 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
579 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
580 mDefaultNotificationContentView
= mNotification
.contentView
;
581 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
582 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
583 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
584 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
586 /// includes a pending intent in the notification showing the details view of the file
587 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
588 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
589 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
590 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
591 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
593 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
598 * Callback method to update the progress bar in the status notification
601 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
602 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
603 if (percent
!= mLastPercent
) {
604 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
605 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
606 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
607 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
609 mLastPercent
= percent
;
614 * Callback method to update the progress bar in the status notification (old version)
617 public void onTransferProgress(long progressRate
) {
618 // NOTHING TO DO HERE ANYMORE
623 * Updates the status notification with the result of an upload operation.
625 * @param uploadResult Result of the upload operation.
626 * @param upload Finished upload operation
628 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
629 if (uploadResult
.isCancelled()) {
630 /// cancelled operation -> silent removal of progress notification
631 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
633 } else if (uploadResult
.isSuccess()) {
634 /// success -> silent update of progress notification to success message
635 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
636 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
637 mNotification
.contentView
= mDefaultNotificationContentView
;
639 /// includes a pending intent in the notification showing the details view of the file
640 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
641 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
642 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
643 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
644 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
646 mNotification
.setLatestEventInfo( getApplicationContext(),
647 getString(R
.string
.uploader_upload_succeeded_ticker
),
648 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
649 mNotification
.contentIntent
);
651 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
653 /* Notification about multiple uploads: pending of update
654 mNotification.setLatestEventInfo( getApplicationContext(),
655 getString(R.string.uploader_upload_succeeded_ticker),
656 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
657 mNotification.contentIntent);
661 /// fail -> explicit failure notification
662 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
663 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
664 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
665 // TODO put something smart in the contentIntent below
666 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
668 String content
= null
;
669 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
||
670 uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
671 // TODO we need a class to provide error messages for the users from a RemoteOperationResult and a RemoteOperation
672 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(), getString(R
.string
.app_name
));
674 content
= String
.format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
676 finalNotification
.setLatestEventInfo( getApplicationContext(),
677 getString(R
.string
.uploader_upload_failed_ticker
),
679 finalNotification
.contentIntent
);
681 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
683 /* Notification about multiple uploads failure: pending of update
684 finalNotification.setLatestEventInfo( getApplicationContext(),
685 getString(R.string.uploader_upload_failed_ticker),
686 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
687 finalNotification.contentIntent);
695 * Sends a broadcast in order to the interested activities can update their view
697 * @param upload Finished upload operation
698 * @param uploadResult Result of the upload operation
700 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
701 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
702 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote path, after possible automatic renaming
703 if (upload
.wasRenamed()) {
704 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
706 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
707 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
708 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
709 sendStickyBroadcast(end
);