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
.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 android
.accounts
.Account
;
34 import android
.accounts
.AccountManager
;
35 import android
.app
.Notification
;
36 import android
.app
.NotificationManager
;
37 import android
.app
.PendingIntent
;
38 import android
.app
.Service
;
39 import android
.content
.Intent
;
40 import android
.os
.Binder
;
41 import android
.os
.Handler
;
42 import android
.os
.HandlerThread
;
43 import android
.os
.IBinder
;
44 import android
.os
.Looper
;
45 import android
.os
.Message
;
46 import android
.os
.Process
;
47 import android
.util
.Log
;
48 import android
.webkit
.MimeTypeMap
;
49 import android
.widget
.RemoteViews
;
50 import android
.widget
.Toast
;
52 import com
.owncloud
.android
.R
;
53 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
54 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
55 import com
.owncloud
.android
.datamodel
.OCFile
;
56 import com
.owncloud
.android
.db
.DbHandler
;
57 import com
.owncloud
.android
.files
.InstantUploadBroadcastReceiver
;
58 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
59 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
60 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
61 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
62 import com
.owncloud
.android
.operations
.UploadFileOperation
;
63 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
64 import com
.owncloud
.android
.ui
.activity
.InstantUploadActivity
;
65 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
66 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
68 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
69 import eu
.alefzero
.webdav
.WebdavClient
;
70 import eu
.alefzero
.webdav
.WebdavEntry
;
71 import eu
.alefzero
.webdav
.WebdavUtils
;
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
;
119 * Builds a key for mPendingUploads from the account and file to upload
121 * @param account Account where the file to download is stored
122 * @param file File to download
124 private String
buildRemoteName(Account account
, OCFile file
) {
125 return account
.name
+ file
.getRemotePath();
128 private String
buildRemoteName(Account account
, String remotePath
) {
129 return account
.name
+ remotePath
;
133 * Checks if an ownCloud server version should support chunked uploads.
135 * @param version OwnCloud version instance corresponding to an ownCloud
137 * @return 'True' if the ownCloud server with version supports chunked
140 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
141 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
145 * Service initialization
148 public void onCreate() {
150 Log
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
151 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
152 HandlerThread thread
= new HandlerThread("FileUploaderThread", Process
.THREAD_PRIORITY_BACKGROUND
);
154 mServiceLooper
= thread
.getLooper();
155 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
156 mBinder
= new FileUploaderBinder();
160 * Entry point to add one or several files to the queue of uploads.
162 * New uploads are added calling to startService(), resulting in a call to
163 * this method. This ensures the service will keep on working although the
164 * caller activity goes away.
167 public int onStartCommand(Intent intent
, int flags
, int startId
) {
168 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
169 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
170 Log
.e(TAG
, "Not enough information provided in intent");
171 return Service
.START_NOT_STICKY
;
173 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
174 if (uploadType
== -1) {
175 Log
.e(TAG
, "Incorrect upload type provided");
176 return Service
.START_NOT_STICKY
;
178 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
180 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
181 OCFile
[] files
= null
;
182 if (uploadType
== UPLOAD_SINGLE_FILE
) {
184 if (intent
.hasExtra(KEY_FILE
)) {
185 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
188 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
189 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
190 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
193 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
195 if (intent
.hasExtra(KEY_FILE
)) {
196 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
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
222 // obtainNewOCFileToUpload
225 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
226 Log
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
227 return Service
.START_NOT_STICKY
;
229 } else if (!intent
.hasExtra(KEY_FILE
)) {
230 if (localPaths
== null
) {
231 Log
.e(TAG
, "Incorrect array for local paths provided in upload intent");
232 return Service
.START_NOT_STICKY
;
234 if (remotePaths
== null
) {
235 Log
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
236 return Service
.START_NOT_STICKY
;
238 if (localPaths
.length
!= remotePaths
.length
) {
239 Log
.e(TAG
, "Different number of remote paths and local paths!");
240 return Service
.START_NOT_STICKY
;
243 files
= new OCFile
[localPaths
.length
];
244 for (int i
= 0; i
< localPaths
.length
; i
++) {
245 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!= null
) ? mimeTypes
[i
]
246 : (String
) null
), storageManager
);
247 if (files
[i
] == null
) {
248 // TODO @andromaex add failure Notiification
249 return Service
.START_NOT_STICKY
;
254 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
,
255 AccountAuthenticator
.KEY_OC_VERSION
));
256 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
257 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
258 String uploadKey
= null
;
259 UploadFileOperation newUpload
= null
;
261 for (int i
= 0; i
< files
.length
; i
++) {
262 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
264 newUpload
= new ChunkedUploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
,
267 newUpload
= new UploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
269 if (fixed
&& i
== 0) {
270 newUpload
.setRemoteFolderToBeCreated();
272 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
273 newUpload
.addDatatransferProgressListener(this);
274 requestedUploads
.add(uploadKey
);
277 } catch (IllegalArgumentException e
) {
278 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
279 return START_NOT_STICKY
;
281 } catch (IllegalStateException e
) {
282 Log
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
283 return START_NOT_STICKY
;
285 } catch (Exception e
) {
286 Log
.e(TAG
, "Unexpected exception while processing upload intent", e
);
287 return START_NOT_STICKY
;
291 if (requestedUploads
.size() > 0) {
292 Message msg
= mServiceHandler
.obtainMessage();
294 msg
.obj
= requestedUploads
;
295 mServiceHandler
.sendMessage(msg
);
297 Log
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
298 return Service
.START_NOT_STICKY
;
302 * Provides a binder object that clients can use to perform operations on
303 * the queue of uploads, excepting the addition of new files.
305 * Implemented to perform cancellation, pause and resume of existing
309 public IBinder
onBind(Intent arg0
) {
314 * Binder to let client components to perform operations on the queue of
317 * It provides by itself the available operations.
319 public class FileUploaderBinder
extends Binder
{
322 * Cancels a pending or current upload of a remote file.
324 * @param account Owncloud account where the remote file will be stored.
325 * @param file A file in the queue of pending uploads
327 public void cancel(Account account
, OCFile file
) {
328 UploadFileOperation upload
= null
;
329 synchronized (mPendingUploads
) {
330 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
332 if (upload
!= null
) {
338 * Returns True when the file described by 'file' is being uploaded to
339 * the ownCloud account 'account' or waiting for it
341 * If 'file' is a directory, returns 'true' if some of its descendant
342 * files is downloading or waiting to download.
344 * @param account Owncloud account where the remote file will be stored.
345 * @param file A file that could be in the queue of pending uploads
347 public boolean isUploading(Account account
, OCFile file
) {
348 if (account
== null
|| file
== null
)
350 String targetKey
= buildRemoteName(account
, file
);
351 synchronized (mPendingUploads
) {
352 if (file
.isDirectory()) {
353 // this can be slow if there are many downloads :(
354 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
355 boolean found
= false
;
356 while (it
.hasNext() && !found
) {
357 found
= it
.next().startsWith(targetKey
);
361 return (mPendingUploads
.containsKey(targetKey
));
368 * Upload worker. Performs the pending uploads in the order they were
371 * Created with the Looper of a new thread, started in
372 * {@link FileUploader#onCreate()}.
374 private static class ServiceHandler
extends Handler
{
375 // don't make it a final class, and don't remove the static ; lint will
376 // warn about a possible memory leak
377 FileUploader mService
;
379 public ServiceHandler(Looper looper
, FileUploader service
) {
382 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
387 public void handleMessage(Message msg
) {
388 @SuppressWarnings("unchecked")
389 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
390 if (msg
.obj
!= null
) {
391 Iterator
<String
> it
= requestedUploads
.iterator();
392 while (it
.hasNext()) {
393 mService
.uploadFile(it
.next());
396 mService
.stopSelf(msg
.arg1
);
401 * Core upload method: sends the file(s) to upload
403 * @param uploadKey Key to access the upload to perform, contained in
406 public void uploadFile(String uploadKey
) {
408 synchronized (mPendingUploads
) {
409 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
412 if (mCurrentUpload
!= null
) {
414 notifyUploadStart(mCurrentUpload
);
416 // / prepare client object to send requests to the ownCloud server
417 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
418 mLastAccount
= mCurrentUpload
.getAccount();
419 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
420 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
423 // / create remote folder for instant uploads
424 if (mCurrentUpload
.isRemoteFolderToBeCreated()) {
425 mUploadClient
.createDirectory(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
); // ignoring
449 // / perform the upload
450 RemoteOperationResult uploadResult
= null
;
452 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
453 if (uploadResult
.isSuccess()) {
458 synchronized (mPendingUploads
) {
459 mPendingUploads
.remove(uploadKey
);
460 Log
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
465 notifyUploadResult(uploadResult
, mCurrentUpload
);
466 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
473 * Saves a OC File after a successful upload.
475 * A PROPFIND is necessary to keep the props in the local database
476 * synchronized with the server, specially the modification time and Etag
479 * TODO refactor this ugly thing
481 private void saveUploadedFile() {
482 OCFile file
= mCurrentUpload
.getFile();
483 long syncDate
= System
.currentTimeMillis();
484 file
.setLastSyncDateForData(syncDate
);
486 // / new PROPFIND to keep data consistent with server in theory, should
487 // return the same we already have
488 PropFindMethod propfind
= null
;
489 RemoteOperationResult result
= null
;
491 propfind
= new PropFindMethod(mUploadClient
.getBaseUri()
492 + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
493 int status
= mUploadClient
.executeMethod(propfind
);
494 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
496 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
497 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], mUploadClient
.getBaseUri().getPath());
498 updateOCFile(file
, we
);
499 file
.setLastSyncDateForProperties(syncDate
);
502 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
505 result
= new RemoteOperationResult(isMultiStatus
, status
);
506 Log
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
507 + result
.getLogMessage());
509 } catch (Exception e
) {
510 result
= new RemoteOperationResult(e
);
511 Log
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
512 + result
.getLogMessage(), e
);
515 if (propfind
!= null
)
516 propfind
.releaseConnection();
519 // / maybe this would be better as part of UploadFileOperation... or
520 // maybe all this method
521 if (mCurrentUpload
.wasRenamed()) {
522 OCFile oldFile
= mCurrentUpload
.getOldFile();
523 if (oldFile
.fileExists()) {
524 oldFile
.setStoragePath(null
);
525 mStorageManager
.saveFile(oldFile
);
527 } // else: it was just an automatic renaming due to a name
528 // coincidence; nothing else is needed, the storagePath is right
529 // in the instance returned by mCurrentUpload.getFile()
532 mStorageManager
.saveFile(file
);
535 private void updateOCFile(OCFile file
, WebdavEntry we
) {
536 file
.setCreationTimestamp(we
.createTimestamp());
537 file
.setFileLength(we
.contentLength());
538 file
.setMimetype(we
.contentType());
539 file
.setModificationTimestamp(we
.modifiedTimestamp());
540 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
541 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where
545 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
546 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
547 if (instantUploadDir
== null
) {
548 // first instant upload in the account, or never account not
549 // synchronized after the remote InstantUpload folder was created
550 OCFile newDir
= new OCFile(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
551 newDir
.setMimetype("DIR");
552 OCFile path
= storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
555 newDir
.setParentId(path
.getFileId());
556 storageManager
.saveFile(newDir
);
566 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
567 FileDataStorageManager storageManager
) {
568 OCFile newFile
= new OCFile(remotePath
);
569 newFile
.setStoragePath(localPath
);
570 newFile
.setLastSyncDateForProperties(0);
571 newFile
.setLastSyncDateForData(0);
574 if (localPath
!= null
&& localPath
.length() > 0) {
575 File localFile
= new File(localPath
);
576 newFile
.setFileLength(localFile
.length());
577 newFile
.setLastSyncDateForData(localFile
.lastModified());
578 } // don't worry about not assigning size, the problems with localPath
579 // are checked when the UploadFileOperation instance is created
582 if (mimeType
== null
|| mimeType
.length() <= 0) {
584 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
585 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
586 } catch (IndexOutOfBoundsException e
) {
587 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
590 if (mimeType
== null
) {
591 mimeType
= "application/octet-stream";
593 newFile
.setMimetype(mimeType
);
596 String parentPath
= new File(remotePath
).getParent();
597 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
598 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
599 if (parentDir
== null
) {
602 getApplicationContext(),
603 "The first time the InstantUpload is running you must be online, so the target folder can successfully created by the upload process",
608 long parentDirId
= parentDir
.getFileId();
609 newFile
.setParentId(parentDirId
);
614 * Creates a status notification to show the upload progress
616 * @param upload Upload operation starting.
618 private void notifyUploadStart(UploadFileOperation upload
) {
619 // / create status notification with a progress bar
621 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
),
622 System
.currentTimeMillis());
623 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
624 mDefaultNotificationContentView
= mNotification
.contentView
;
625 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(),
626 R
.layout
.progressbar_layout
);
627 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
628 mNotification
.contentView
.setTextViewText(R
.id
.status_text
,
629 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
630 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
632 // / includes a pending intent in the notification showing the details
634 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
635 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
636 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
637 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
638 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
639 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
641 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
645 * Callback method to update the progress bar in the status notification
648 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
649 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
650 if (percent
!= mLastPercent
) {
651 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
652 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
653 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
654 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
656 mLastPercent
= percent
;
660 * Callback method to update the progress bar in the status notification
664 public void onTransferProgress(long progressRate
) {
665 // NOTHING TO DO HERE ANYMORE
669 * Updates the status notification with the result of an upload operation.
671 * @param uploadResult Result of the upload operation.
672 * @param upload Finished upload operation
674 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
675 Log
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
676 if (uploadResult
.isCancelled()) {
677 // / cancelled operation -> silent removal of progress notification
678 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
680 } else if (uploadResult
.isSuccess()) {
681 // / success -> silent update of progress notification to success
683 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove
687 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
688 mNotification
.contentView
= mDefaultNotificationContentView
;
690 // / includes a pending intent in the notification showing the
691 // details view of the file
692 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
693 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
694 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
695 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
696 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
697 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
699 mNotification
.setLatestEventInfo(getApplicationContext(),
700 getString(R
.string
.uploader_upload_succeeded_ticker
),
701 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
702 mNotification
.contentIntent
);
704 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
); // NOT
706 DbHandler db
= new DbHandler(this.getBaseContext());
707 db
.removeIUPendingFile(mCurrentUpload
.getFile().getStoragePath());
712 // / fail -> explicit failure notification
713 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
714 Notification finalNotification
= new Notification(R
.drawable
.icon
,
715 getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
716 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
718 Intent detailUploudIntent
= new Intent(this, InstantUploadActivity
.class);
719 detailUploudIntent
.putExtra(FileUploader
.KEY_ACCOUNT
, upload
.getAccount());
720 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
721 (int) System
.currentTimeMillis(), detailUploudIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
722 | PendingIntent
.FLAG_ONE_SHOT
);
724 String content
= null
;
725 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
726 || uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
727 // TODO we need a class to provide error messages for the users
728 // from a RemoteOperationResult and a RemoteOperation
729 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(),
730 getString(R
.string
.app_name
));
733 .format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
735 finalNotification
.setLatestEventInfo(getApplicationContext(),
736 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
738 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
740 DbHandler db
= new DbHandler(this.getBaseContext());
741 if (db
.updateFileState(upload
.getOriginalStoragePath(), DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
) == 0) {
742 db
.putFileForLater(upload
.getOriginalStoragePath(), upload
.getAccount().name
);
751 * Sends a broadcast in order to the interested activities can update their
754 * @param upload Finished upload operation
755 * @param uploadResult Result of the upload operation
757 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
758 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
759 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
764 if (upload
.wasRenamed()) {
765 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
767 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
768 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
769 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
770 sendStickyBroadcast(end
);