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
.util
.AbstractList
;
23 import java
.util
.HashMap
;
24 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
.RemoteOperationResult
;
40 import com
.owncloud
.android
.operations
.UploadFileOperation
;
41 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
42 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
43 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
44 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
46 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
47 import eu
.alefzero
.webdav
.WebdavEntry
;
48 import eu
.alefzero
.webdav
.WebdavUtils
;
50 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
52 import android
.accounts
.Account
;
53 import android
.accounts
.AccountManager
;
54 import android
.app
.Notification
;
55 import android
.app
.NotificationManager
;
56 import android
.app
.PendingIntent
;
57 import android
.app
.Service
;
58 import android
.content
.Intent
;
59 import android
.os
.Binder
;
60 import android
.os
.Handler
;
61 import android
.os
.HandlerThread
;
62 import android
.os
.IBinder
;
63 import android
.os
.Looper
;
64 import android
.os
.Message
;
65 import android
.os
.Process
;
66 import android
.util
.Log
;
67 import android
.webkit
.MimeTypeMap
;
68 import android
.widget
.RemoteViews
;
70 import com
.owncloud
.android
.R
;
71 import eu
.alefzero
.webdav
.WebdavClient
;
73 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
75 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
76 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
77 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
78 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
79 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
80 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
82 public static final String KEY_FILE
= "FILE";
83 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
84 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
85 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
87 public static final String KEY_ACCOUNT
= "ACCOUNT";
89 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
90 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
91 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
92 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
94 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
95 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
96 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
98 public static final int UPLOAD_SINGLE_FILE
= 0;
99 public static final int UPLOAD_MULTIPLE_FILES
= 1;
101 private static final String TAG
= FileUploader
.class.getSimpleName();
103 private Looper mServiceLooper
;
104 private ServiceHandler mServiceHandler
;
105 private IBinder mBinder
;
106 private WebdavClient mUploadClient
= null
;
107 private Account mLastAccount
= null
;
108 private FileDataStorageManager mStorageManager
;
110 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
111 private UploadFileOperation mCurrentUpload
= null
;
113 private NotificationManager mNotificationManager
;
114 private Notification mNotification
;
115 private int mLastPercent
;
116 private RemoteViews mDefaultNotificationContentView
;
120 * Builds a key for mPendingUploads from the account and file to upload
122 * @param account Account where the file to upload is stored
123 * @param file File to upload
125 private String
buildRemoteName(Account account
, OCFile file
) {
126 return account
.name
+ file
.getRemotePath();
129 private String
buildRemoteName(Account account
, String remotePath
) {
130 return account
.name
+ remotePath
;
135 * Checks if an ownCloud server version should support chunked uploads.
137 * @param version OwnCloud version instance corresponding to an ownCloud server.
138 * @return 'True' if the ownCloud server with version supports chunked uploads.
140 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
141 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
147 * Service initialization
150 public void onCreate() {
152 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
153 HandlerThread thread
= new HandlerThread("FileUploaderThread",
154 Process
.THREAD_PRIORITY_BACKGROUND
);
156 mServiceLooper
= thread
.getLooper();
157 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
158 mBinder
= new FileUploaderBinder();
163 * Entry point to add one or several files to the queue of uploads.
165 * New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
166 * although the caller activity goes away.
169 public int onStartCommand(Intent intent
, int flags
, int startId
) {
170 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
) || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
171 Log
.e(TAG
, "Not enough information provided in intent");
172 return Service
.START_NOT_STICKY
;
174 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
175 if (uploadType
== -1) {
176 Log
.e(TAG
, "Incorrect upload type provided");
177 return Service
.START_NOT_STICKY
;
179 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
181 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
182 OCFile
[] files
= null
;
183 if (uploadType
== UPLOAD_SINGLE_FILE
) {
185 if (intent
.hasExtra(KEY_FILE
)) {
186 files
= new OCFile
[] {intent
.getParcelableExtra(KEY_FILE
) };
189 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
190 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
191 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
194 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
196 if (intent
.hasExtra(KEY_FILE
)) {
197 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO will this casting work fine?
200 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
201 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
202 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
206 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
208 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
209 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
210 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
211 boolean fixed
= false
;
213 fixed
= checkAndFixInstantUploadDirectory(storageManager
); // MUST be done BEFORE calling obtainNewOCFileToUpload
216 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
217 Log
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
218 return Service
.START_NOT_STICKY
;
220 } else if (!intent
.hasExtra(KEY_FILE
)) {
221 if (localPaths
== null
) {
222 Log
.e(TAG
, "Incorrect array for local paths provided in upload intent");
223 return Service
.START_NOT_STICKY
;
225 if (remotePaths
== null
) {
226 Log
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
227 return Service
.START_NOT_STICKY
;
229 if (localPaths
.length
!= remotePaths
.length
) {
230 Log
.e(TAG
, "Different number of remote paths and local paths!");
231 return Service
.START_NOT_STICKY
;
234 files
= new OCFile
[localPaths
.length
];
235 for (int i
=0; i
< localPaths
.length
; i
++) {
236 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!=null
)?mimeTypes
[i
]:(String
)null
), storageManager
);
240 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
241 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
242 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
243 String uploadKey
= null
;
244 UploadFileOperation newUpload
= null
;
246 for (int i
=0; i
< files
.length
; i
++) {
247 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
249 newUpload
= new ChunkedUploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
251 newUpload
= new UploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
254 newUpload
.setRemoteFolderToBeCreated();
256 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
257 newUpload
.addDatatransferProgressListener(this);
258 newUpload
.addDatatransferProgressListener((FileUploaderBinder
)mBinder
);
259 requestedUploads
.add(uploadKey
);
262 } catch (IllegalArgumentException e
) {
263 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
264 return START_NOT_STICKY
;
266 } catch (IllegalStateException e
) {
267 Log
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
268 return START_NOT_STICKY
;
270 } catch (Exception e
) {
271 Log
.e(TAG
, "Unexpected exception while processing upload intent", e
);
272 return START_NOT_STICKY
;
276 if (requestedUploads
.size() > 0) {
277 Message msg
= mServiceHandler
.obtainMessage();
279 msg
.obj
= requestedUploads
;
280 mServiceHandler
.sendMessage(msg
);
283 return Service
.START_NOT_STICKY
;
288 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
290 * Implemented to perform cancellation, pause and resume of existing uploads.
293 public IBinder
onBind(Intent arg0
) {
298 * Called when ALL the bound clients were onbound.
301 public boolean onUnbind(Intent intent
) {
302 ((FileUploaderBinder
)mBinder
).clearListeners();
303 return false
; // not accepting rebinding (default behaviour)
308 * Binder to let client components to perform operations on the queue of uploads.
310 * It provides by itself the available operations.
312 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
315 * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
317 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
320 * Cancels a pending or current upload of a remote file.
322 * @param account Owncloud account where the remote file will be stored.
323 * @param file A file in the queue of pending uploads
325 public void cancel(Account account
, OCFile file
) {
326 UploadFileOperation upload
= null
;
327 synchronized (mPendingUploads
) {
328 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
330 if (upload
!= null
) {
337 public void clearListeners() {
338 mBoundListeners
.clear();
345 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
347 * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
349 * @param account Owncloud account where the remote file will be stored.
350 * @param file A file that could be in the queue of pending uploads
352 public boolean isUploading(Account account
, OCFile file
) {
353 if (account
== null
|| file
== null
) return false
;
354 String targetKey
= buildRemoteName(account
, file
);
355 synchronized (mPendingUploads
) {
356 if (file
.isDirectory()) {
357 // this can be slow if there are many uploads :(
358 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
359 boolean found
= false
;
360 while (it
.hasNext() && !found
) {
361 found
= it
.next().startsWith(targetKey
);
365 return (mPendingUploads
.containsKey(targetKey
));
372 * Adds a listener interested in the progress of the upload for a concrete file.
374 * @param listener Object to notify about progress of transfer.
375 * @param account ownCloud account holding the file of interest.
376 * @param file {@link OCfile} of interest for listener.
378 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
379 if (account
== null
|| file
== null
|| listener
== null
) return;
380 String targetKey
= buildRemoteName(account
, file
);
381 mBoundListeners
.put(targetKey
, listener
);
387 * Removes a listener interested in the progress of the upload for a concrete file.
389 * @param listener Object to notify about progress of transfer.
390 * @param account ownCloud account holding the file of interest.
391 * @param file {@link OCfile} of interest for listener.
393 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
, Account account
, OCFile file
) {
394 if (account
== null
|| file
== null
|| listener
== null
) return;
395 String targetKey
= buildRemoteName(account
, file
);
396 if (mBoundListeners
.get(targetKey
) == listener
) {
397 mBoundListeners
.remove(targetKey
);
403 public void onTransferProgress(long progressRate
) {
404 // old way, should not be in use any more
409 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
411 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
412 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
413 if (boundListener
!= null
) {
414 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
424 * Upload worker. Performs the pending uploads in the order they were requested.
426 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
428 private static class ServiceHandler
extends Handler
{
429 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
430 FileUploader mService
;
431 public ServiceHandler(Looper looper
, FileUploader service
) {
434 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
439 public void handleMessage(Message msg
) {
440 @SuppressWarnings("unchecked")
441 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
442 if (msg
.obj
!= null
) {
443 Iterator
<String
> it
= requestedUploads
.iterator();
444 while (it
.hasNext()) {
445 mService
.uploadFile(it
.next());
448 mService
.stopSelf(msg
.arg1
);
456 * Core upload method: sends the file(s) to upload
458 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
460 public void uploadFile(String uploadKey
) {
462 synchronized(mPendingUploads
) {
463 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
466 if (mCurrentUpload
!= null
) {
468 notifyUploadStart(mCurrentUpload
);
471 /// prepare client object to send requests to the ownCloud server
472 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
473 mLastAccount
= mCurrentUpload
.getAccount();
474 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
475 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
478 /// create remote folder for instant uploads
479 if (mCurrentUpload
.isRemoteFolderToBeCreated()) {
480 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
484 /// perform the upload
485 RemoteOperationResult uploadResult
= null
;
487 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
488 if (uploadResult
.isSuccess()) {
493 synchronized(mPendingUploads
) {
494 mPendingUploads
.remove(uploadKey
);
499 notifyUploadResult(uploadResult
, mCurrentUpload
);
501 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
508 * Saves a OC File after a successful upload.
510 * A PROPFIND is necessary to keep the props in the local database synchronized with the server,
511 * specially the modification time and Etag (where available)
513 * TODO refactor this ugly thing
515 private void saveUploadedFile() {
516 OCFile file
= mCurrentUpload
.getFile();
517 long syncDate
= System
.currentTimeMillis();
518 file
.setLastSyncDateForData(syncDate
);
520 /// new PROPFIND to keep data consistent with server in theory, should return the same we already have
521 PropFindMethod propfind
= null
;
522 RemoteOperationResult result
= null
;
524 propfind
= new PropFindMethod(mUploadClient
.getBaseUri() + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
525 int status
= mUploadClient
.executeMethod(propfind
);
526 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
528 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
529 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0],
530 mUploadClient
.getBaseUri().getPath());
531 updateOCFile(file
, we
);
532 file
.setLastSyncDateForProperties(syncDate
);
535 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
538 result
= new RemoteOperationResult(isMultiStatus
, status
);
539 Log
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage());
541 } catch (Exception e
) {
542 result
= new RemoteOperationResult(e
);
543 Log
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage(), e
);
546 if (propfind
!= null
)
547 propfind
.releaseConnection();
550 /// maybe this would be better as part of UploadFileOperation... or maybe all this method
551 if (mCurrentUpload
.wasRenamed()) {
552 OCFile oldFile
= mCurrentUpload
.getOldFile();
553 if (oldFile
.fileExists()) {
554 oldFile
.setStoragePath(null
);
555 mStorageManager
.saveFile(oldFile
);
557 } // 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()
560 mStorageManager
.saveFile(file
);
564 private void updateOCFile(OCFile file
, WebdavEntry we
) {
565 file
.setCreationTimestamp(we
.createTimestamp());
566 file
.setFileLength(we
.contentLength());
567 file
.setMimetype(we
.contentType());
568 file
.setModificationTimestamp(we
.modifiedTimestamp());
569 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
570 // file.setEtag(mCurrentUpload.getEtag()); // TODO Etag, where available
574 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
575 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
576 if (instantUploadDir
== null
) {
577 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
578 OCFile newDir
= new OCFile(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
579 newDir
.setMimetype("DIR");
580 newDir
.setParentId(storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId());
581 storageManager
.saveFile(newDir
);
588 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
, FileDataStorageManager storageManager
) {
589 OCFile newFile
= new OCFile(remotePath
);
590 newFile
.setStoragePath(localPath
);
591 newFile
.setLastSyncDateForProperties(0);
592 newFile
.setLastSyncDateForData(0);
595 if (localPath
!= null
&& localPath
.length() > 0) {
596 File localFile
= new File(localPath
);
597 newFile
.setFileLength(localFile
.length());
598 newFile
.setLastSyncDateForData(localFile
.lastModified());
599 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
602 if (mimeType
== null
|| mimeType
.length() <= 0) {
604 mimeType
= MimeTypeMap
.getSingleton()
605 .getMimeTypeFromExtension(
606 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
607 } catch (IndexOutOfBoundsException e
) {
608 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
611 if (mimeType
== null
) {
612 mimeType
= "application/octet-stream";
614 newFile
.setMimetype(mimeType
);
617 String parentPath
= new File(remotePath
).getParent();
618 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
619 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
620 if (parentDir
== null
) {
621 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath
);
623 long parentDirId
= parentDir
.getFileId();
624 newFile
.setParentId(parentDirId
);
630 * Creates a status notification to show the upload progress
632 * @param upload Upload operation starting.
634 @SuppressWarnings("deprecation")
635 private void notifyUploadStart(UploadFileOperation upload
) {
636 /// create status notification with a progress bar
638 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
639 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
640 mDefaultNotificationContentView
= mNotification
.contentView
;
641 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
642 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
643 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
644 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
646 /// includes a pending intent in the notification showing the details view of the file
647 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
648 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
649 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
650 showDetailsIntent
.putExtra(FileDetailActivity
.EXTRA_MODE
, FileDetailActivity
.MODE_DETAILS
);
651 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
652 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
654 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
659 * Callback method to update the progress bar in the status notification
662 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
663 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
664 if (percent
!= mLastPercent
) {
665 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
666 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
667 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
668 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
670 mLastPercent
= percent
;
675 * Callback method to update the progress bar in the status notification (old version)
678 public void onTransferProgress(long progressRate
) {
679 // NOTHING TO DO HERE ANYMORE
684 * Updates the status notification with the result of an upload operation.
686 * @param uploadResult Result of the upload operation.
687 * @param upload Finished upload operation
689 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
690 if (uploadResult
.isCancelled()) {
691 /// cancelled operation -> silent removal of progress notification
692 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
694 } else if (uploadResult
.isSuccess()) {
695 /// success -> silent update of progress notification to success message
696 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
697 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
698 mNotification
.contentView
= mDefaultNotificationContentView
;
700 /// includes a pending intent in the notification showing the details view of the file
701 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
702 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
703 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
704 showDetailsIntent
.putExtra(FileDetailActivity
.EXTRA_MODE
, FileDetailActivity
.MODE_DETAILS
);
705 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
706 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
708 mNotification
.setLatestEventInfo( getApplicationContext(),
709 getString(R
.string
.uploader_upload_succeeded_ticker
),
710 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
711 mNotification
.contentIntent
);
713 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
715 /* Notification about multiple uploads: pending of update
716 mNotification.setLatestEventInfo( getApplicationContext(),
717 getString(R.string.uploader_upload_succeeded_ticker),
718 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
719 mNotification.contentIntent);
723 /// fail -> explicit failure notification
724 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
725 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
726 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
727 // TODO put something smart in the contentIntent below
728 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
730 String content
= null
;
731 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
||
732 uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
733 // TODO we need a class to provide error messages for the users from a RemoteOperationResult and a RemoteOperation
734 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(), getString(R
.string
.app_name
));
736 content
= String
.format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
738 finalNotification
.setLatestEventInfo( getApplicationContext(),
739 getString(R
.string
.uploader_upload_failed_ticker
),
741 finalNotification
.contentIntent
);
743 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
745 /* Notification about multiple uploads failure: pending of update
746 finalNotification.setLatestEventInfo( getApplicationContext(),
747 getString(R.string.uploader_upload_failed_ticker),
748 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
749 finalNotification.contentIntent);
757 * Sends a broadcast in order to the interested activities can update their view
759 * @param upload Finished upload operation
760 * @param uploadResult Result of the upload operation
762 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
763 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
764 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote path, after possible automatic renaming
765 if (upload
.wasRenamed()) {
766 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
768 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
769 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
770 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
771 sendStickyBroadcast(end
);