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
.FileDetailActivity
;
63 import com
.owncloud
.android
.ui
.activity
.InstantUploadActivity
;
64 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
65 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
67 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
68 import eu
.alefzero
.webdav
.WebdavClient
;
69 import eu
.alefzero
.webdav
.WebdavEntry
;
70 import eu
.alefzero
.webdav
.WebdavUtils
;
72 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
74 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
75 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
76 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
77 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
78 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
79 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
81 public static final String KEY_FILE
= "FILE";
82 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
83 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
84 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
86 public static final String KEY_ACCOUNT
= "ACCOUNT";
88 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
89 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
90 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
91 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
93 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
94 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
95 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
97 public static final int UPLOAD_SINGLE_FILE
= 0;
98 public static final int UPLOAD_MULTIPLE_FILES
= 1;
100 private static final String TAG
= FileUploader
.class.getSimpleName();
102 private Looper mServiceLooper
;
103 private ServiceHandler mServiceHandler
;
104 private IBinder mBinder
;
105 private WebdavClient mUploadClient
= null
;
106 private Account mLastAccount
= null
;
107 private FileDataStorageManager mStorageManager
;
109 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
110 private UploadFileOperation mCurrentUpload
= null
;
112 private NotificationManager mNotificationManager
;
113 private Notification mNotification
;
114 private int mLastPercent
;
115 private RemoteViews mDefaultNotificationContentView
;
118 * Builds a key for mPendingUploads from the account and file to upload
120 * @param account Account where the file to download is stored
121 * @param file File to download
123 private String
buildRemoteName(Account account
, OCFile file
) {
124 return account
.name
+ file
.getRemotePath();
127 private String
buildRemoteName(Account account
, String remotePath
) {
128 return account
.name
+ remotePath
;
132 * Checks if an ownCloud server version should support chunked uploads.
134 * @param version OwnCloud version instance corresponding to an ownCloud
136 * @return 'True' if the ownCloud server with version supports chunked
139 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
140 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
144 * Service initialization
147 public void onCreate() {
149 Log
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
150 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
151 HandlerThread thread
= new HandlerThread("FileUploaderThread", Process
.THREAD_PRIORITY_BACKGROUND
);
153 mServiceLooper
= thread
.getLooper();
154 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
155 mBinder
= new FileUploaderBinder();
159 * Entry point to add one or several files to the queue of uploads.
161 * New uploads are added calling to startService(), resulting in a call to
162 * this method. This ensures the service will keep on working although the
163 * caller activity goes away.
166 public int onStartCommand(Intent intent
, int flags
, int startId
) {
167 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
168 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
169 Log
.e(TAG
, "Not enough information provided in intent");
170 return Service
.START_NOT_STICKY
;
172 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
173 if (uploadType
== -1) {
174 Log
.e(TAG
, "Incorrect upload type provided");
175 return Service
.START_NOT_STICKY
;
177 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
179 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
180 OCFile
[] files
= null
;
181 if (uploadType
== UPLOAD_SINGLE_FILE
) {
183 if (intent
.hasExtra(KEY_FILE
)) {
184 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
187 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
188 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
189 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
192 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
194 if (intent
.hasExtra(KEY_FILE
)) {
195 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
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
221 // obtainNewOCFileToUpload
224 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
225 Log
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
226 return Service
.START_NOT_STICKY
;
228 } else if (!intent
.hasExtra(KEY_FILE
)) {
229 if (localPaths
== null
) {
230 Log
.e(TAG
, "Incorrect array for local paths provided in upload intent");
231 return Service
.START_NOT_STICKY
;
233 if (remotePaths
== null
) {
234 Log
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
235 return Service
.START_NOT_STICKY
;
237 if (localPaths
.length
!= remotePaths
.length
) {
238 Log
.e(TAG
, "Different number of remote paths and local paths!");
239 return Service
.START_NOT_STICKY
;
242 files
= new OCFile
[localPaths
.length
];
243 for (int i
= 0; i
< localPaths
.length
; i
++) {
244 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!= null
) ? mimeTypes
[i
]
245 : (String
) null
), storageManager
);
246 if (files
[i
] == null
) {
247 // TODO @andromaex add failure Notiification
248 return Service
.START_NOT_STICKY
;
253 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
,
254 AccountAuthenticator
.KEY_OC_VERSION
));
255 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
256 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
257 String uploadKey
= null
;
258 UploadFileOperation newUpload
= null
;
260 for (int i
= 0; i
< files
.length
; i
++) {
261 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
263 newUpload
= new ChunkedUploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
,
266 newUpload
= new UploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
268 if (fixed
&& i
== 0) {
269 newUpload
.setRemoteFolderToBeCreated();
271 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
272 newUpload
.addDatatransferProgressListener(this);
273 requestedUploads
.add(uploadKey
);
276 } catch (IllegalArgumentException e
) {
277 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
278 return START_NOT_STICKY
;
280 } catch (IllegalStateException e
) {
281 Log
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
282 return START_NOT_STICKY
;
284 } catch (Exception e
) {
285 Log
.e(TAG
, "Unexpected exception while processing upload intent", e
);
286 return START_NOT_STICKY
;
290 if (requestedUploads
.size() > 0) {
291 Message msg
= mServiceHandler
.obtainMessage();
293 msg
.obj
= requestedUploads
;
294 mServiceHandler
.sendMessage(msg
);
296 Log
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
297 return Service
.START_NOT_STICKY
;
301 * Provides a binder object that clients can use to perform operations on
302 * the queue of uploads, excepting the addition of new files.
304 * Implemented to perform cancellation, pause and resume of existing
308 public IBinder
onBind(Intent arg0
) {
313 * Binder to let client components to perform operations on the queue of
316 * It provides by itself the available operations.
318 public class FileUploaderBinder
extends Binder
{
321 * Cancels a pending or current upload of a remote file.
323 * @param account Owncloud account where the remote file will be stored.
324 * @param file A file in the queue of pending uploads
326 public void cancel(Account account
, OCFile file
) {
327 UploadFileOperation upload
= null
;
328 synchronized (mPendingUploads
) {
329 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
331 if (upload
!= null
) {
337 * Returns True when the file described by 'file' is being uploaded to
338 * the ownCloud account 'account' or waiting for it
340 * If 'file' is a directory, returns 'true' if some of its descendant
341 * files is downloading or waiting to download.
343 * @param account Owncloud account where the remote file will be stored.
344 * @param file A file that could be in the queue of pending uploads
346 public boolean isUploading(Account account
, OCFile file
) {
347 if (account
== null
|| file
== null
)
349 String targetKey
= buildRemoteName(account
, file
);
350 synchronized (mPendingUploads
) {
351 if (file
.isDirectory()) {
352 // this can be slow if there are many downloads :(
353 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
354 boolean found
= false
;
355 while (it
.hasNext() && !found
) {
356 found
= it
.next().startsWith(targetKey
);
360 return (mPendingUploads
.containsKey(targetKey
));
367 * Upload worker. Performs the pending uploads in the order they were
370 * Created with the Looper of a new thread, started in
371 * {@link FileUploader#onCreate()}.
373 private static class ServiceHandler
extends Handler
{
374 // don't make it a final class, and don't remove the static ; lint will
375 // warn about a possible memory leak
376 FileUploader mService
;
378 public ServiceHandler(Looper looper
, FileUploader service
) {
381 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
386 public void handleMessage(Message msg
) {
387 @SuppressWarnings("unchecked")
388 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
389 if (msg
.obj
!= null
) {
390 Iterator
<String
> it
= requestedUploads
.iterator();
391 while (it
.hasNext()) {
392 mService
.uploadFile(it
.next());
395 mService
.stopSelf(msg
.arg1
);
400 * Core upload method: sends the file(s) to upload
402 * @param uploadKey Key to access the upload to perform, contained in
405 public void uploadFile(String uploadKey
) {
407 synchronized (mPendingUploads
) {
408 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
411 if (mCurrentUpload
!= null
) {
413 notifyUploadStart(mCurrentUpload
);
415 // / prepare client object to send requests to the ownCloud server
416 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
417 mLastAccount
= mCurrentUpload
.getAccount();
418 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
419 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
422 // / create remote folder for instant uploads
423 if (mCurrentUpload
.isRemoteFolderToBeCreated()) {
424 mUploadClient
.createDirectory(InstantUploadService
.INSTANT_UPLOAD_DIR
);
425 // ignoring result fail could just mean that it already exists,
426 // but local database is not synchronized the upload will be
430 // / perform the upload
431 RemoteOperationResult uploadResult
= null
;
433 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
434 if (uploadResult
.isSuccess()) {
439 synchronized (mPendingUploads
) {
440 mPendingUploads
.remove(uploadKey
);
441 Log
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
446 notifyUploadResult(uploadResult
, mCurrentUpload
);
447 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
454 * Saves a OC File after a successful upload.
456 * A PROPFIND is necessary to keep the props in the local database
457 * synchronized with the server, specially the modification time and Etag
460 * TODO refactor this ugly thing
462 private void saveUploadedFile() {
463 OCFile file
= mCurrentUpload
.getFile();
464 long syncDate
= System
.currentTimeMillis();
465 file
.setLastSyncDateForData(syncDate
);
467 // / new PROPFIND to keep data consistent with server in theory, should
468 // return the same we already have
469 PropFindMethod propfind
= null
;
470 RemoteOperationResult result
= null
;
472 propfind
= new PropFindMethod(mUploadClient
.getBaseUri()
473 + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
474 int status
= mUploadClient
.executeMethod(propfind
);
475 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
477 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
478 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], mUploadClient
.getBaseUri().getPath());
479 updateOCFile(file
, we
);
480 file
.setLastSyncDateForProperties(syncDate
);
483 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
486 result
= new RemoteOperationResult(isMultiStatus
, status
);
487 Log
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
488 + result
.getLogMessage());
490 } catch (Exception e
) {
491 result
= new RemoteOperationResult(e
);
492 Log
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
493 + result
.getLogMessage(), e
);
496 if (propfind
!= null
)
497 propfind
.releaseConnection();
500 // / maybe this would be better as part of UploadFileOperation... or
501 // maybe all this method
502 if (mCurrentUpload
.wasRenamed()) {
503 OCFile oldFile
= mCurrentUpload
.getOldFile();
504 if (oldFile
.fileExists()) {
505 oldFile
.setStoragePath(null
);
506 mStorageManager
.saveFile(oldFile
);
508 } // else: it was just an automatic renaming due to a name
509 // coincidence; nothing else is needed, the storagePath is right
510 // in the instance returned by mCurrentUpload.getFile()
513 mStorageManager
.saveFile(file
);
516 private void updateOCFile(OCFile file
, WebdavEntry we
) {
517 file
.setCreationTimestamp(we
.createTimestamp());
518 file
.setFileLength(we
.contentLength());
519 file
.setMimetype(we
.contentType());
520 file
.setModificationTimestamp(we
.modifiedTimestamp());
521 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
522 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where
526 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
527 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadService
.INSTANT_UPLOAD_DIR
);
528 if (instantUploadDir
== null
) {
529 // first instant upload in the account, or never account not
530 // synchronized after the remote InstantUpload folder was created
531 OCFile newDir
= new OCFile(InstantUploadService
.INSTANT_UPLOAD_DIR
);
532 newDir
.setMimetype("DIR");
533 OCFile path
= storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
536 newDir
.setParentId(path
.getFileId());
537 storageManager
.saveFile(newDir
);
547 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
548 FileDataStorageManager storageManager
) {
549 OCFile newFile
= new OCFile(remotePath
);
550 newFile
.setStoragePath(localPath
);
551 newFile
.setLastSyncDateForProperties(0);
552 newFile
.setLastSyncDateForData(0);
555 if (localPath
!= null
&& localPath
.length() > 0) {
556 File localFile
= new File(localPath
);
557 newFile
.setFileLength(localFile
.length());
558 newFile
.setLastSyncDateForData(localFile
.lastModified());
559 } // don't worry about not assigning size, the problems with localPath
560 // are checked when the UploadFileOperation instance is created
563 if (mimeType
== null
|| mimeType
.length() <= 0) {
565 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
566 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
567 } catch (IndexOutOfBoundsException e
) {
568 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
571 if (mimeType
== null
) {
572 mimeType
= "application/octet-stream";
574 newFile
.setMimetype(mimeType
);
577 String parentPath
= new File(remotePath
).getParent();
578 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
579 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
580 if (parentDir
== null
) {
583 getApplicationContext(),
584 "The first time the InstantUpload is running you must be online, so the target folder can successfully created by the upload process",
589 long parentDirId
= parentDir
.getFileId();
590 newFile
.setParentId(parentDirId
);
595 * Creates a status notification to show the upload progress
597 * @param upload Upload operation starting.
599 private void notifyUploadStart(UploadFileOperation upload
) {
600 // / create status notification with a progress bar
602 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
),
603 System
.currentTimeMillis());
604 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
605 mDefaultNotificationContentView
= mNotification
.contentView
;
606 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(),
607 R
.layout
.progressbar_layout
);
608 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
609 mNotification
.contentView
.setTextViewText(R
.id
.status_text
,
610 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
611 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
613 // / includes a pending intent in the notification showing the details
615 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
616 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
617 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
618 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
619 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
620 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
622 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
626 * Callback method to update the progress bar in the status notification
629 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
630 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
631 if (percent
!= mLastPercent
) {
632 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
633 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
634 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
635 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
637 mLastPercent
= percent
;
641 * Callback method to update the progress bar in the status notification
645 public void onTransferProgress(long progressRate
) {
646 // NOTHING TO DO HERE ANYMORE
650 * Updates the status notification with the result of an upload operation.
652 * @param uploadResult Result of the upload operation.
653 * @param upload Finished upload operation
655 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
656 Log
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
657 if (uploadResult
.isCancelled()) {
658 // / cancelled operation -> silent removal of progress notification
659 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
661 } else if (uploadResult
.isSuccess()) {
662 // / success -> silent update of progress notification to success
664 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove
668 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
669 mNotification
.contentView
= mDefaultNotificationContentView
;
671 // / includes a pending intent in the notification showing the
672 // details view of the file
673 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
674 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
675 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
676 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
677 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
678 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
680 mNotification
.setLatestEventInfo(getApplicationContext(),
681 getString(R
.string
.uploader_upload_succeeded_ticker
),
682 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
683 mNotification
.contentIntent
);
685 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
); // NOT
687 DbHandler db
= new DbHandler(this.getBaseContext());
688 db
.removeIUPendingFile(mCurrentUpload
.getFile().getStoragePath());
693 // / fail -> explicit failure notification
694 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
695 Notification finalNotification
= new Notification(R
.drawable
.icon
,
696 getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
697 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
699 Intent detailUploudIntent
= new Intent(this, InstantUploadActivity
.class);
700 detailUploudIntent
.putExtra(FileUploader
.KEY_ACCOUNT
, upload
.getAccount());
701 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
702 (int) System
.currentTimeMillis(), detailUploudIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
703 | PendingIntent
.FLAG_ONE_SHOT
);
705 String content
= null
;
706 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
707 || uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
708 // TODO we need a class to provide error messages for the users
709 // from a RemoteOperationResult and a RemoteOperation
710 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(),
711 getString(R
.string
.app_name
));
714 .format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
716 finalNotification
.setLatestEventInfo(getApplicationContext(),
717 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
719 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
721 DbHandler db
= new DbHandler(this.getBaseContext());
722 String message
= uploadResult
.getLogMessage() + " errorCode: " + uploadResult
.getCode();
723 Log
.e(TAG
, message
+" Http-Code: "+uploadResult
.getHttpCode());
724 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
725 message
= getString(R
.string
.failed_upload_quota_exceeded_text
);
727 if (db
.updateFileState(upload
.getOriginalStoragePath(), DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
, message
) == 0) {
728 db
.putFileForLater(upload
.getOriginalStoragePath(), upload
.getAccount().name
, message
);
737 * Sends a broadcast in order to the interested activities can update their
740 * @param upload Finished upload operation
741 * @param uploadResult Result of the upload operation
743 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
744 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
745 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
750 if (upload
.wasRenamed()) {
751 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
753 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
754 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
755 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
756 sendStickyBroadcast(end
);