1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.files
.services
;
22 import java
.util
.AbstractList
;
23 import java
.util
.Iterator
;
24 import java
.util
.Vector
;
25 import java
.util
.concurrent
.ConcurrentHashMap
;
26 import java
.util
.concurrent
.ConcurrentMap
;
28 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
29 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
30 import com
.owncloud
.android
.datamodel
.OCFile
;
31 import com
.owncloud
.android
.files
.InstantUploadBroadcastReceiver
;
32 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
33 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
34 import com
.owncloud
.android
.operations
.UploadFileOperation
;
35 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
36 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
37 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
39 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
41 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
43 import android
.accounts
.Account
;
44 import android
.accounts
.AccountManager
;
45 import android
.app
.Notification
;
46 import android
.app
.NotificationManager
;
47 import android
.app
.PendingIntent
;
48 import android
.app
.Service
;
49 import android
.content
.Intent
;
50 import android
.os
.Binder
;
51 import android
.os
.Handler
;
52 import android
.os
.HandlerThread
;
53 import android
.os
.IBinder
;
54 import android
.os
.Looper
;
55 import android
.os
.Message
;
56 import android
.os
.Process
;
57 import android
.util
.Log
;
58 import android
.webkit
.MimeTypeMap
;
59 import android
.widget
.RemoteViews
;
61 import com
.owncloud
.android
.R
;
62 import eu
.alefzero
.webdav
.WebdavClient
;
64 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
66 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
67 public static final String EXTRA_PARENT_DIR_ID
= "PARENT_DIR_ID";
68 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
69 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
70 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
72 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
73 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
74 public static final String KEY_ACCOUNT
= "ACCOUNT";
75 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
76 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
77 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
78 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
79 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
81 public static final int UPLOAD_SINGLE_FILE
= 0;
82 public static final int UPLOAD_MULTIPLE_FILES
= 1;
84 private static final String TAG
= FileUploader
.class.getSimpleName();
86 private Looper mServiceLooper
;
87 private ServiceHandler mServiceHandler
;
88 private IBinder mBinder
;
89 private WebdavClient mUploadClient
= null
;
90 private Account mLastAccount
= null
;
91 private FileDataStorageManager mStorageManager
;
93 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
94 private UploadFileOperation mCurrentUpload
= null
;
96 private NotificationManager mNotificationManager
;
97 private Notification mNotification
;
98 private int mLastPercent
;
99 private RemoteViews mDefaultNotificationContentView
;
103 * Builds a key for mPendingUploads from the account and file to upload
105 * @param account Account where the file to download is stored
106 * @param file File to download
108 private String
buildRemoteName(Account account
, OCFile file
) {
109 return account
.name
+ file
.getRemotePath();
112 private String
buildRemoteName(Account account
, String remotePath
) {
113 return account
.name
+ remotePath
;
118 * Checks if an ownCloud server version should support chunked uploads.
120 * @param version OwnCloud version instance corresponding to an ownCloud server.
121 * @return 'True' if the ownCloud server with version supports chunked uploads.
123 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
124 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
130 * Service initialization
133 public void onCreate() {
135 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
136 HandlerThread thread
= new HandlerThread("FileUploaderThread",
137 Process
.THREAD_PRIORITY_BACKGROUND
);
139 mServiceLooper
= thread
.getLooper();
140 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
141 mBinder
= new FileUploaderBinder();
146 * Entry point to add one or several files to the queue of uploads.
148 * New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
149 * although the caller activity goes away.
152 public int onStartCommand(Intent intent
, int flags
, int startId
) {
153 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)) {
154 Log
.e(TAG
, "Not enough information provided in intent");
155 return Service
.START_NOT_STICKY
;
157 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
158 if (uploadType
== -1) {
159 Log
.e(TAG
, "Incorrect upload type provided");
160 return Service
.START_NOT_STICKY
;
162 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
164 String
[] localPaths
, remotePaths
, mimeTypes
;
165 if (uploadType
== UPLOAD_SINGLE_FILE
) {
166 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
167 remotePaths
= new String
[] { intent
168 .getStringExtra(KEY_REMOTE_FILE
) };
169 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
171 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
172 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
173 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
174 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
177 if (localPaths
== null
) {
178 Log
.e(TAG
, "Incorrect array for local paths provided in upload intent");
179 return Service
.START_NOT_STICKY
;
181 if (remotePaths
== null
) {
182 Log
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
183 return Service
.START_NOT_STICKY
;
186 if (localPaths
.length
!= remotePaths
.length
) {
187 Log
.e(TAG
, "Different number of remote paths and local paths!");
188 return Service
.START_NOT_STICKY
;
191 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
192 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
194 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
195 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
196 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
197 String uploadKey
= null
;
198 UploadFileOperation newUpload
= null
;
200 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
201 boolean fixed
= false
;
203 fixed
= checkAndFixInstantUploadDirectory(storageManager
);
206 for (int i
=0; i
< localPaths
.length
; i
++) {
207 uploadKey
= buildRemoteName(account
, remotePaths
[i
]);
208 file
= obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!=null
)?mimeTypes
[i
]:(String
)null
), isInstant
, forceOverwrite
, storageManager
);
210 newUpload
= new ChunkedUploadFileOperation(account
, file
, isInstant
, forceOverwrite
);
212 newUpload
= new UploadFileOperation(account
, file
, isInstant
, forceOverwrite
);
215 newUpload
.setRemoteFolderToBeCreated();
217 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
218 newUpload
.addDatatransferProgressListener(this);
219 requestedUploads
.add(uploadKey
);
222 } catch (IllegalArgumentException e
) {
223 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
224 return START_NOT_STICKY
;
226 } catch (IllegalStateException e
) {
227 Log
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
228 return START_NOT_STICKY
;
230 } catch (Exception e
) {
231 Log
.e(TAG
, "Unexpected exception while processing upload intent", e
);
232 return START_NOT_STICKY
;
236 if (requestedUploads
.size() > 0) {
237 Message msg
= mServiceHandler
.obtainMessage();
239 msg
.obj
= requestedUploads
;
240 mServiceHandler
.sendMessage(msg
);
243 return Service
.START_NOT_STICKY
;
248 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
250 * Implemented to perform cancellation, pause and resume of existing uploads.
253 public IBinder
onBind(Intent arg0
) {
258 * Binder to let client components to perform operations on the queue of uploads.
260 * It provides by itself the available operations.
262 public class FileUploaderBinder
extends Binder
{
265 * Cancels a pending or current upload of a remote file.
267 * @param account Owncloud account where the remote file will be stored.
268 * @param file A file in the queue of pending uploads
270 public void cancel(Account account
, OCFile file
) {
271 UploadFileOperation upload
= null
;
272 synchronized (mPendingUploads
) {
273 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
275 if (upload
!= null
) {
282 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
284 * @param account Owncloud account where the remote file will be stored.
285 * @param file A file that could be in the queue of pending uploads
287 public boolean isUploading(Account account
, OCFile file
) {
288 synchronized (mPendingUploads
) {
289 return (mPendingUploads
.containsKey(buildRemoteName(account
, file
)));
298 * Upload worker. Performs the pending uploads in the order they were requested.
300 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
302 private static class ServiceHandler
extends Handler
{
303 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
304 FileUploader mService
;
305 public ServiceHandler(Looper looper
, FileUploader service
) {
308 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
313 public void handleMessage(Message msg
) {
314 @SuppressWarnings("unchecked")
315 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
316 if (msg
.obj
!= null
) {
317 Iterator
<String
> it
= requestedUploads
.iterator();
318 while (it
.hasNext()) {
319 mService
.uploadFile(it
.next());
322 mService
.stopSelf(msg
.arg1
);
330 * Core upload method: sends the file(s) to upload
332 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
334 public void uploadFile(String uploadKey
) {
336 synchronized(mPendingUploads
) {
337 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
340 if (mCurrentUpload
!= null
) {
342 notifyUploadStart(mCurrentUpload
);
345 /// prepare client object to send requests to the ownCloud server
346 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
347 mLastAccount
= mCurrentUpload
.getAccount();
348 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
349 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
352 /// create remote folder for instant uploads
353 if (mCurrentUpload
.isRemoteFolderToBeCreated()) {
354 mUploadClient
.createDirectory(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
); // ignoring result; fail could just mean that it already exists, but local database is not synchronized; the upload will be tried anyway
358 /// perform the upload
359 RemoteOperationResult uploadResult
= null
;
361 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
362 if (uploadResult
.isSuccess()) {
363 saveUploadedFile(mCurrentUpload
.getFile(), mStorageManager
);
367 synchronized(mPendingUploads
) {
368 mPendingUploads
.remove(uploadKey
);
373 notifyUploadResult(uploadResult
, mCurrentUpload
);
375 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
382 * Saves a new OC File after a successful upload.
384 * @param file OCFile describing the uploaded file
385 * @param storageManager Interface to the database where the new OCFile has to be stored.
386 * @param parentDirId Id of the parent OCFile.
388 private void saveUploadedFile(OCFile file
, FileDataStorageManager storageManager
) {
389 file
.setModificationTimestamp(System
.currentTimeMillis());
390 storageManager
.saveFile(file
);
394 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
395 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
396 if (instantUploadDir
== null
) {
397 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
398 OCFile newDir
= new OCFile(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
399 newDir
.setMimetype("DIR");
400 newDir
.setParentId(storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId());
401 storageManager
.saveFile(newDir
);
408 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
, boolean isInstant
, boolean forceOverwrite
, FileDataStorageManager storageManager
) {
409 OCFile newFile
= new OCFile(remotePath
);
410 newFile
.setStoragePath(localPath
);
411 newFile
.setLastSyncDate(0);
412 newFile
.setKeepInSync(forceOverwrite
);
415 if (localPath
!= null
&& localPath
.length() > 0) {
416 File localFile
= new File(localPath
);
417 newFile
.setFileLength(localFile
.length());
418 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
421 if (mimeType
== null
|| mimeType
.length() <= 0) {
423 mimeType
= MimeTypeMap
.getSingleton()
424 .getMimeTypeFromExtension(
425 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
426 } catch (IndexOutOfBoundsException e
) {
427 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
430 if (mimeType
== null
) {
431 mimeType
= "application/octet-stream";
433 newFile
.setMimetype(mimeType
);
436 String parentPath
= new File(remotePath
).getParent();
437 parentPath
= parentPath
.endsWith("/")?parentPath
:parentPath
+"/" ;
438 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
439 if (parentDir
== null
) {
440 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath
);
442 long parentDirId
= parentDir
.getFileId();
443 newFile
.setParentId(parentDirId
);
449 * Creates a status notification to show the upload progress
451 * @param upload Upload operation starting.
453 private void notifyUploadStart(UploadFileOperation upload
) {
454 /// create status notification with a progress bar
456 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
457 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
458 mDefaultNotificationContentView
= mNotification
.contentView
;
459 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
460 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
461 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, new File(upload
.getStoragePath()).getName()));
462 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
464 /// includes a pending intent in the notification showing the details view of the file
465 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
466 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
467 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
468 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
469 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
471 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
476 * Callback method to update the progress bar in the status notification
479 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
480 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
481 if (percent
!= mLastPercent
) {
482 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
483 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
484 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
485 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
487 mLastPercent
= percent
;
492 * Callback method to update the progress bar in the status notification (old version)
495 public void onTransferProgress(long progressRate
) {
496 // NOTHING TO DO HERE ANYMORE
501 * Updates the status notification with the result of an upload operation.
503 * @param uploadResult Result of the upload operation.
504 * @param upload Finished upload operation
506 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
507 if (uploadResult
.isCancelled()) {
508 /// cancelled operation -> silent removal of progress notification
509 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
511 } else if (uploadResult
.isSuccess()) {
512 /// success -> silent update of progress notification to success message
513 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
514 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
515 mNotification
.contentView
= mDefaultNotificationContentView
;
517 /// includes a pending intent in the notification showing the details view of the file
518 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
519 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
520 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
521 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
522 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
524 mNotification
.setLatestEventInfo( getApplicationContext(),
525 getString(R
.string
.uploader_upload_succeeded_ticker
),
526 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), (new File(upload
.getStoragePath())).getName()),
527 mNotification
.contentIntent
);
529 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
); // NOT AN ERROR; uploader_upload_in_progress_ticker is the target, not a new notification
531 /* Notification about multiple uploads: pending of update
532 mNotification.setLatestEventInfo( getApplicationContext(),
533 getString(R.string.uploader_upload_succeeded_ticker),
534 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
535 mNotification.contentIntent);
539 /// fail -> explicit failure notification
540 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
541 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
542 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
543 // TODO put something smart in the contentIntent below
544 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
545 finalNotification
.setLatestEventInfo( getApplicationContext(),
546 getString(R
.string
.uploader_upload_failed_ticker
),
547 String
.format(getString(R
.string
.uploader_upload_failed_content_single
), (new File(upload
.getStoragePath())).getName()),
548 finalNotification
.contentIntent
);
550 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
552 /* Notification about multiple uploads failure: pending of update
553 finalNotification.setLatestEventInfo( getApplicationContext(),
554 getString(R.string.uploader_upload_failed_ticker),
555 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
556 finalNotification.contentIntent);
564 * Sends a broadcast in order to the interested activities can update their view
566 * @param upload Finished upload operation
567 * @param uploadResult Result of the upload operation
569 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
570 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
571 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote path, after possible automatic renaming
572 end
.putExtra(EXTRA_FILE_PATH
, upload
.getStoragePath());
573 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
574 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
575 end
.putExtra(EXTRA_PARENT_DIR_ID
, upload
.getFile().getParentId());