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
.Log_OC
;
53 import com
.owncloud
.android
.R
;
54 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
55 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
56 import com
.owncloud
.android
.datamodel
.OCFile
;
57 import com
.owncloud
.android
.db
.DbHandler
;
58 import com
.owncloud
.android
.files
.InstantUploadBroadcastReceiver
;
59 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
60 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
61 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
62 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
63 import com
.owncloud
.android
.operations
.UploadFileOperation
;
64 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
65 import com
.owncloud
.android
.ui
.activity
.InstantUploadActivity
;
66 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
67 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
69 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
70 import eu
.alefzero
.webdav
.WebdavClient
;
71 import eu
.alefzero
.webdav
.WebdavEntry
;
72 import eu
.alefzero
.webdav
.WebdavUtils
;
74 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
76 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
77 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
78 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
79 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
80 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
81 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
83 public static final String KEY_FILE
= "FILE";
84 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
85 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
86 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
88 public static final String KEY_ACCOUNT
= "ACCOUNT";
90 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
91 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
92 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
93 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
95 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
96 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
97 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
99 public static final int UPLOAD_SINGLE_FILE
= 0;
100 public static final int UPLOAD_MULTIPLE_FILES
= 1;
102 private static final String TAG
= FileUploader
.class.getSimpleName();
104 private Looper mServiceLooper
;
105 private ServiceHandler mServiceHandler
;
106 private IBinder mBinder
;
107 private WebdavClient mUploadClient
= null
;
108 private Account mLastAccount
= null
;
109 private FileDataStorageManager mStorageManager
;
111 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
112 private UploadFileOperation mCurrentUpload
= null
;
114 private NotificationManager mNotificationManager
;
115 private Notification mNotification
;
116 private int mLastPercent
;
117 private RemoteViews mDefaultNotificationContentView
;
120 * Builds a key for mPendingUploads from the account and file to upload
122 * @param account Account where the file to download is stored
123 * @param file File to download
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
;
134 * Checks if an ownCloud server version should support chunked uploads.
136 * @param version OwnCloud version instance corresponding to an ownCloud
138 * @return 'True' if the ownCloud server with version supports chunked
141 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
142 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
146 * Service initialization
149 public void onCreate() {
151 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
152 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
153 HandlerThread thread
= new HandlerThread("FileUploaderThread", Process
.THREAD_PRIORITY_BACKGROUND
);
155 mServiceLooper
= thread
.getLooper();
156 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
157 mBinder
= new FileUploaderBinder();
161 * Entry point to add one or several files to the queue of uploads.
163 * New uploads are added calling to startService(), resulting in a call to
164 * this method. This ensures the service will keep on working although the
165 * caller activity goes away.
168 public int onStartCommand(Intent intent
, int flags
, int startId
) {
169 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
170 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
171 Log_OC
.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_OC
.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
205 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
206 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
207 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
211 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
213 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
214 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
215 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
216 boolean fixed
= false
;
218 fixed
= checkAndFixInstantUploadDirectory(storageManager
); // MUST
223 // obtainNewOCFileToUpload
226 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
227 Log_OC
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
228 return Service
.START_NOT_STICKY
;
230 } else if (!intent
.hasExtra(KEY_FILE
)) {
231 if (localPaths
== null
) {
232 Log_OC
.e(TAG
, "Incorrect array for local paths provided in upload intent");
233 return Service
.START_NOT_STICKY
;
235 if (remotePaths
== null
) {
236 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
237 return Service
.START_NOT_STICKY
;
239 if (localPaths
.length
!= remotePaths
.length
) {
240 Log_OC
.e(TAG
, "Different number of remote paths and local paths!");
241 return Service
.START_NOT_STICKY
;
244 files
= new OCFile
[localPaths
.length
];
245 for (int i
= 0; i
< localPaths
.length
; i
++) {
246 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!= null
) ? mimeTypes
[i
]
247 : (String
) null
), storageManager
);
248 if (files
[i
] == null
) {
249 // TODO @andromaex add failure Notiification
250 return Service
.START_NOT_STICKY
;
255 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
,
256 AccountAuthenticator
.KEY_OC_VERSION
));
257 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
258 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
259 String uploadKey
= null
;
260 UploadFileOperation newUpload
= null
;
262 for (int i
= 0; i
< files
.length
; i
++) {
263 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
265 newUpload
= new ChunkedUploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
,
268 newUpload
= new UploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
270 if (fixed
&& i
== 0) {
271 newUpload
.setRemoteFolderToBeCreated();
273 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
274 newUpload
.addDatatransferProgressListener(this);
275 requestedUploads
.add(uploadKey
);
278 } catch (IllegalArgumentException e
) {
279 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
280 return START_NOT_STICKY
;
282 } catch (IllegalStateException e
) {
283 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
284 return START_NOT_STICKY
;
286 } catch (Exception e
) {
287 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
288 return START_NOT_STICKY
;
292 if (requestedUploads
.size() > 0) {
293 Message msg
= mServiceHandler
.obtainMessage();
295 msg
.obj
= requestedUploads
;
296 mServiceHandler
.sendMessage(msg
);
298 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
299 return Service
.START_NOT_STICKY
;
303 * Provides a binder object that clients can use to perform operations on
304 * the queue of uploads, excepting the addition of new files.
306 * Implemented to perform cancellation, pause and resume of existing
310 public IBinder
onBind(Intent arg0
) {
315 * Binder to let client components to perform operations on the queue of
318 * It provides by itself the available operations.
320 public class FileUploaderBinder
extends Binder
{
323 * Cancels a pending or current upload of a remote file.
325 * @param account Owncloud account where the remote file will be stored.
326 * @param file A file in the queue of pending uploads
328 public void cancel(Account account
, OCFile file
) {
329 UploadFileOperation upload
= null
;
330 synchronized (mPendingUploads
) {
331 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
333 if (upload
!= null
) {
339 * Returns True when the file described by 'file' is being uploaded to
340 * the ownCloud account 'account' or waiting for it
342 * If 'file' is a directory, returns 'true' if some of its descendant
343 * files is downloading or waiting to download.
345 * @param account Owncloud account where the remote file will be stored.
346 * @param file A file that could be in the queue of pending uploads
348 public boolean isUploading(Account account
, OCFile file
) {
349 if (account
== null
|| file
== null
)
351 String targetKey
= buildRemoteName(account
, file
);
352 synchronized (mPendingUploads
) {
353 if (file
.isDirectory()) {
354 // this can be slow if there are many downloads :(
355 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
356 boolean found
= false
;
357 while (it
.hasNext() && !found
) {
358 found
= it
.next().startsWith(targetKey
);
362 return (mPendingUploads
.containsKey(targetKey
));
369 * Upload worker. Performs the pending uploads in the order they were
372 * Created with the Looper of a new thread, started in
373 * {@link FileUploader#onCreate()}.
375 private static class ServiceHandler
extends Handler
{
376 // don't make it a final class, and don't remove the static ; lint will
377 // warn about a possible memory leak
378 FileUploader mService
;
380 public ServiceHandler(Looper looper
, FileUploader service
) {
383 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
388 public void handleMessage(Message msg
) {
389 @SuppressWarnings("unchecked")
390 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
391 if (msg
.obj
!= null
) {
392 Iterator
<String
> it
= requestedUploads
.iterator();
393 while (it
.hasNext()) {
394 mService
.uploadFile(it
.next());
397 mService
.stopSelf(msg
.arg1
);
402 * Core upload method: sends the file(s) to upload
404 * @param uploadKey Key to access the upload to perform, contained in
407 public void uploadFile(String uploadKey
) {
409 synchronized (mPendingUploads
) {
410 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
413 if (mCurrentUpload
!= null
) {
415 notifyUploadStart(mCurrentUpload
);
417 // / prepare client object to send requests to the ownCloud server
418 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
419 mLastAccount
= mCurrentUpload
.getAccount();
420 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
421 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
424 // / create remote folder for instant uploads
425 if (mCurrentUpload
.isRemoteFolderToBeCreated()) {
426 mUploadClient
.createDirectory(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
); // ignoring
450 // / perform the upload
451 RemoteOperationResult uploadResult
= null
;
453 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
454 if (uploadResult
.isSuccess()) {
459 synchronized (mPendingUploads
) {
460 mPendingUploads
.remove(uploadKey
);
461 Log_OC
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
466 notifyUploadResult(uploadResult
, mCurrentUpload
);
467 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
474 * Saves a OC File after a successful upload.
476 * A PROPFIND is necessary to keep the props in the local database
477 * synchronized with the server, specially the modification time and Etag
480 * TODO refactor this ugly thing
482 private void saveUploadedFile() {
483 OCFile file
= mCurrentUpload
.getFile();
484 long syncDate
= System
.currentTimeMillis();
485 file
.setLastSyncDateForData(syncDate
);
487 // / new PROPFIND to keep data consistent with server in theory, should
488 // return the same we already have
489 PropFindMethod propfind
= null
;
490 RemoteOperationResult result
= null
;
492 propfind
= new PropFindMethod(mUploadClient
.getBaseUri()
493 + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
494 int status
= mUploadClient
.executeMethod(propfind
);
495 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
497 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
498 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], mUploadClient
.getBaseUri().getPath());
499 updateOCFile(file
, we
);
500 file
.setLastSyncDateForProperties(syncDate
);
503 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
506 result
= new RemoteOperationResult(isMultiStatus
, status
);
507 Log_OC
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
508 + result
.getLogMessage());
510 } catch (Exception e
) {
511 result
= new RemoteOperationResult(e
);
512 Log_OC
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": "
513 + result
.getLogMessage(), e
);
516 if (propfind
!= null
)
517 propfind
.releaseConnection();
520 // / maybe this would be better as part of UploadFileOperation... or
521 // maybe all this method
522 if (mCurrentUpload
.wasRenamed()) {
523 OCFile oldFile
= mCurrentUpload
.getOldFile();
524 if (oldFile
.fileExists()) {
525 oldFile
.setStoragePath(null
);
526 mStorageManager
.saveFile(oldFile
);
528 } // else: it was just an automatic renaming due to a name
529 // coincidence; nothing else is needed, the storagePath is right
530 // in the instance returned by mCurrentUpload.getFile()
533 mStorageManager
.saveFile(file
);
536 private void updateOCFile(OCFile file
, WebdavEntry we
) {
537 file
.setCreationTimestamp(we
.createTimestamp());
538 file
.setFileLength(we
.contentLength());
539 file
.setMimetype(we
.contentType());
540 file
.setModificationTimestamp(we
.modifiedTimestamp());
541 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
542 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where
546 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
547 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
548 if (instantUploadDir
== null
) {
549 // first instant upload in the account, or never account not
550 // synchronized after the remote InstantUpload folder was created
551 OCFile newDir
= new OCFile(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
552 newDir
.setMimetype("DIR");
553 OCFile path
= storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
556 newDir
.setParentId(path
.getFileId());
557 storageManager
.saveFile(newDir
);
567 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
568 FileDataStorageManager storageManager
) {
569 OCFile newFile
= new OCFile(remotePath
);
570 newFile
.setStoragePath(localPath
);
571 newFile
.setLastSyncDateForProperties(0);
572 newFile
.setLastSyncDateForData(0);
575 if (localPath
!= null
&& localPath
.length() > 0) {
576 File localFile
= new File(localPath
);
577 newFile
.setFileLength(localFile
.length());
578 newFile
.setLastSyncDateForData(localFile
.lastModified());
579 } // don't worry about not assigning size, the problems with localPath
580 // are checked when the UploadFileOperation instance is created
583 if (mimeType
== null
|| mimeType
.length() <= 0) {
585 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
586 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
587 } catch (IndexOutOfBoundsException e
) {
588 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
591 if (mimeType
== null
) {
592 mimeType
= "application/octet-stream";
594 newFile
.setMimetype(mimeType
);
597 String parentPath
= new File(remotePath
).getParent();
598 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
599 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
600 if (parentDir
== null
) {
603 getApplicationContext(),
604 "The first time the InstantUpload is running you must be online, so the target folder can successfully created by the upload process",
609 long parentDirId
= parentDir
.getFileId();
610 newFile
.setParentId(parentDirId
);
615 * Creates a status notification to show the upload progress
617 * @param upload Upload operation starting.
619 private void notifyUploadStart(UploadFileOperation upload
) {
620 // / create status notification with a progress bar
622 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
),
623 System
.currentTimeMillis());
624 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
625 mDefaultNotificationContentView
= mNotification
.contentView
;
626 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(),
627 R
.layout
.progressbar_layout
);
628 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
629 mNotification
.contentView
.setTextViewText(R
.id
.status_text
,
630 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
631 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
633 // / includes a pending intent in the notification showing the details
635 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
636 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
637 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
638 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
639 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
640 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
642 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
646 * Callback method to update the progress bar in the status notification
649 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
650 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
651 if (percent
!= mLastPercent
) {
652 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
653 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
654 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
655 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
657 mLastPercent
= percent
;
661 * Callback method to update the progress bar in the status notification
665 public void onTransferProgress(long progressRate
) {
666 // NOTHING TO DO HERE ANYMORE
670 * Updates the status notification with the result of an upload operation.
672 * @param uploadResult Result of the upload operation.
673 * @param upload Finished upload operation
675 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
676 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
677 if (uploadResult
.isCancelled()) {
678 // / cancelled operation -> silent removal of progress notification
679 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
681 } else if (uploadResult
.isSuccess()) {
682 // / success -> silent update of progress notification to success
684 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove
688 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
689 mNotification
.contentView
= mDefaultNotificationContentView
;
691 // / includes a pending intent in the notification showing the
692 // details view of the file
693 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
694 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
695 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
696 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
697 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
698 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
700 mNotification
.setLatestEventInfo(getApplicationContext(),
701 getString(R
.string
.uploader_upload_succeeded_ticker
),
702 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
703 mNotification
.contentIntent
);
705 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
); // NOT
707 DbHandler db
= new DbHandler(this.getBaseContext());
708 db
.removeIUPendingFile(mCurrentUpload
.getFile().getStoragePath());
713 // / fail -> explicit failure notification
714 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
715 Notification finalNotification
= new Notification(R
.drawable
.icon
,
716 getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
717 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
719 Intent detailUploudIntent
= new Intent(this, InstantUploadActivity
.class);
720 detailUploudIntent
.putExtra(FileUploader
.KEY_ACCOUNT
, upload
.getAccount());
721 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
722 (int) System
.currentTimeMillis(), detailUploudIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
723 | PendingIntent
.FLAG_ONE_SHOT
);
725 String content
= null
;
726 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
727 || uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
728 // TODO we need a class to provide error messages for the users
729 // from a RemoteOperationResult and a RemoteOperation
730 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(),
731 getString(R
.string
.app_name
));
734 .format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
736 finalNotification
.setLatestEventInfo(getApplicationContext(),
737 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
739 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
741 DbHandler db
= new DbHandler(this.getBaseContext());
742 if (db
.updateFileState(upload
.getOriginalStoragePath(), DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
) == 0) {
743 db
.putFileForLater(upload
.getOriginalStoragePath(), upload
.getAccount().name
);
752 * Sends a broadcast in order to the interested activities can update their
755 * @param upload Finished upload operation
756 * @param uploadResult Result of the upload operation
758 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
759 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
760 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
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
);