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
.network
.OwnCloudClientUtils
;
58 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
59 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
60 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
61 import com
.owncloud
.android
.operations
.UploadFileOperation
;
62 import com
.owncloud
.android
.ui
.activity
.FailedUploadActivity
;
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(InstantUploadService
.INSTANT_UPLOAD_DIR
);
426 // ignoring result fail could just mean that it already exists,
427 // but local database is not synchronized the upload will be
431 // / perform the upload
432 RemoteOperationResult uploadResult
= null
;
434 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
435 if (uploadResult
.isSuccess()) {
440 synchronized (mPendingUploads
) {
441 mPendingUploads
.remove(uploadKey
);
442 Log
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
447 notifyUploadResult(uploadResult
, mCurrentUpload
);
448 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
455 * Saves a OC File after a successful upload.
457 * A PROPFIND is necessary to keep the props in the local database
458 * synchronized with the server, specially the modification time and Etag
461 * TODO refactor this ugly thing
463 private void saveUploadedFile() {
464 OCFile file
= mCurrentUpload
.getFile();
465 long syncDate
= System
.currentTimeMillis();
466 file
.setLastSyncDateForData(syncDate
);
468 // / new PROPFIND to keep data consistent with server in theory, should
469 // return the same we already have
470 PropFindMethod propfind
= null
;
471 RemoteOperationResult result
= null
;
473 propfind
= new PropFindMethod(mUploadClient
.getBaseUri()
474 + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
475 int status
= mUploadClient
.executeMethod(propfind
);
476 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
478 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
479 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], mUploadClient
.getBaseUri().getPath());
480 updateOCFile(file
, we
);
481 file
.setLastSyncDateForProperties(syncDate
);
484 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
487 result
= new RemoteOperationResult(isMultiStatus
, status
);
488 Log
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
489 + result
.getLogMessage());
491 } catch (Exception e
) {
492 result
= new RemoteOperationResult(e
);
493 Log
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
494 + result
.getLogMessage(), e
);
497 if (propfind
!= null
)
498 propfind
.releaseConnection();
501 // / maybe this would be better as part of UploadFileOperation... or
502 // maybe all this method
503 if (mCurrentUpload
.wasRenamed()) {
504 OCFile oldFile
= mCurrentUpload
.getOldFile();
505 if (oldFile
.fileExists()) {
506 oldFile
.setStoragePath(null
);
507 mStorageManager
.saveFile(oldFile
);
509 } // else: it was just an automatic renaming due to a name
510 // coincidence; nothing else is needed, the storagePath is right
511 // in the instance returned by mCurrentUpload.getFile()
514 mStorageManager
.saveFile(file
);
517 private void updateOCFile(OCFile file
, WebdavEntry we
) {
518 file
.setCreationTimestamp(we
.createTimestamp());
519 file
.setFileLength(we
.contentLength());
520 file
.setMimetype(we
.contentType());
521 file
.setModificationTimestamp(we
.modifiedTimestamp());
522 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
523 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where
527 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
528 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadService
.INSTANT_UPLOAD_DIR
);
529 if (instantUploadDir
== null
) {
530 // first instant upload in the account, or never account not
531 // synchronized after the remote InstantUpload folder was created
532 OCFile newDir
= new OCFile(InstantUploadService
.INSTANT_UPLOAD_DIR
);
533 newDir
.setMimetype("DIR");
534 OCFile path
= storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
537 newDir
.setParentId(path
.getFileId());
538 storageManager
.saveFile(newDir
);
548 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
549 FileDataStorageManager storageManager
) {
550 OCFile newFile
= new OCFile(remotePath
);
551 newFile
.setStoragePath(localPath
);
552 newFile
.setLastSyncDateForProperties(0);
553 newFile
.setLastSyncDateForData(0);
556 if (localPath
!= null
&& localPath
.length() > 0) {
557 File localFile
= new File(localPath
);
558 newFile
.setFileLength(localFile
.length());
559 newFile
.setLastSyncDateForData(localFile
.lastModified());
560 } // don't worry about not assigning size, the problems with localPath
561 // are checked when the UploadFileOperation instance is created
564 if (mimeType
== null
|| mimeType
.length() <= 0) {
566 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
567 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
568 } catch (IndexOutOfBoundsException e
) {
569 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
572 if (mimeType
== null
) {
573 mimeType
= "application/octet-stream";
575 newFile
.setMimetype(mimeType
);
578 String parentPath
= new File(remotePath
).getParent();
579 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
580 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
581 if (parentDir
== null
) {
584 getApplicationContext(),
585 "The first time the InstantUpload is running you must be online, so the target folder can successfully created by the upload process",
590 long parentDirId
= parentDir
.getFileId();
591 newFile
.setParentId(parentDirId
);
596 * Creates a status notification to show the upload progress
598 * @param upload Upload operation starting.
600 private void notifyUploadStart(UploadFileOperation upload
) {
601 // / create status notification with a progress bar
603 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
),
604 System
.currentTimeMillis());
605 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
606 mDefaultNotificationContentView
= mNotification
.contentView
;
607 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(),
608 R
.layout
.progressbar_layout
);
609 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
610 mNotification
.contentView
.setTextViewText(R
.id
.status_text
,
611 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
612 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
614 // / includes a pending intent in the notification showing the details
616 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
617 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
618 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
619 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
620 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
621 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
623 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
627 * Callback method to update the progress bar in the status notification
630 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
631 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
632 if (percent
!= mLastPercent
) {
633 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
634 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
635 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
636 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
638 mLastPercent
= percent
;
642 * Callback method to update the progress bar in the status notification
646 public void onTransferProgress(long progressRate
) {
647 // NOTHING TO DO HERE ANYMORE
651 * Updates the status notification with the result of an upload operation.
653 * @param uploadResult Result of the upload operation.
654 * @param upload Finished upload operation
656 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
657 Log
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
658 if (uploadResult
.isCancelled()) {
659 // / cancelled operation -> silent removal of progress notification
660 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
662 } else if (uploadResult
.isSuccess()) {
663 // / success -> silent update of progress notification to success
665 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove
669 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
670 mNotification
.contentView
= mDefaultNotificationContentView
;
672 // / includes a pending intent in the notification showing the
673 // details view of the file
674 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
675 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
676 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
677 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
678 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
679 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
681 mNotification
.setLatestEventInfo(getApplicationContext(),
682 getString(R
.string
.uploader_upload_succeeded_ticker
),
683 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
684 mNotification
.contentIntent
);
686 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
); // NOT
688 DbHandler db
= new DbHandler(this.getBaseContext());
689 db
.removeIUPendingFile(mCurrentUpload
.getFile().getStoragePath());
694 // / fail -> explicit failure notification
695 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
696 Notification finalNotification
= new Notification(R
.drawable
.icon
,
697 getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
698 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
700 String content
= null
;
701 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
702 || uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
703 // TODO we need a class to provide error messages for the users
704 // from a RemoteOperationResult and a RemoteOperation
705 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(),
706 getString(R
.string
.app_name
));
707 } else if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
708 content
= getString(R
.string
.failed_upload_quota_exceeded_text
);
711 .format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
714 // we add only for instant-uploads the InstantUploadActivity and the
716 Intent detailUploadIntent
= null
;
717 if (upload
.isInstant()) {
718 detailUploadIntent
= new Intent(this, InstantUploadActivity
.class);
719 detailUploadIntent
.putExtra(FileUploader
.KEY_ACCOUNT
, upload
.getAccount());
721 detailUploadIntent
= new Intent(this, FailedUploadActivity
.class);
722 detailUploadIntent
.putExtra(FailedUploadActivity
.MESSAGE
, content
);
724 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
725 (int) System
.currentTimeMillis(), detailUploadIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
726 | PendingIntent
.FLAG_ONE_SHOT
);
728 if (upload
.isInstant()) {
731 db
= new DbHandler(this.getBaseContext());
732 String message
= uploadResult
.getLogMessage() + " errorCode: " + uploadResult
.getCode();
733 Log
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
734 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
735 message
= getString(R
.string
.failed_upload_quota_exceeded_text
);
737 if (db
.updateFileState(upload
.getOriginalStoragePath(), DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
739 db
.putFileForLater(upload
.getOriginalStoragePath(), upload
.getAccount().name
, message
);
747 finalNotification
.setLatestEventInfo(getApplicationContext(),
748 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
750 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
756 * Sends a broadcast in order to the interested activities can update their
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
769 if (upload
.wasRenamed()) {
770 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
772 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
773 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
774 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
775 sendStickyBroadcast(end
);