1 package com
.owncloud
.android
.files
.services
;
4 import java
.util
.AbstractList
;
5 import java
.util
.Iterator
;
6 import java
.util
.Vector
;
7 import java
.util
.concurrent
.ConcurrentHashMap
;
8 import java
.util
.concurrent
.ConcurrentMap
;
10 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
11 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
12 import com
.owncloud
.android
.datamodel
.OCFile
;
13 import com
.owncloud
.android
.files
.InstantUploadBroadcastReceiver
;
14 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
15 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
16 import com
.owncloud
.android
.operations
.UploadFileOperation
;
17 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
18 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
19 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
21 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
23 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.app
.Notification
;
28 import android
.app
.NotificationManager
;
29 import android
.app
.PendingIntent
;
30 import android
.app
.Service
;
31 import android
.content
.Intent
;
32 import android
.os
.Binder
;
33 import android
.os
.Handler
;
34 import android
.os
.HandlerThread
;
35 import android
.os
.IBinder
;
36 import android
.os
.Looper
;
37 import android
.os
.Message
;
38 import android
.os
.Process
;
39 import android
.util
.Log
;
40 import android
.webkit
.MimeTypeMap
;
41 import android
.widget
.RemoteViews
;
43 import com
.owncloud
.android
.R
;
44 import eu
.alefzero
.webdav
.WebdavClient
;
46 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
48 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
49 public static final String EXTRA_PARENT_DIR_ID
= "PARENT_DIR_ID";
50 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
51 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
52 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
54 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
55 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
56 public static final String KEY_ACCOUNT
= "ACCOUNT";
57 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
58 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
59 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
60 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
61 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
63 public static final int UPLOAD_SINGLE_FILE
= 0;
64 public static final int UPLOAD_MULTIPLE_FILES
= 1;
66 private static final String TAG
= FileUploader
.class.getSimpleName();
68 private Looper mServiceLooper
;
69 private ServiceHandler mServiceHandler
;
70 private IBinder mBinder
;
71 private WebdavClient mUploadClient
= null
;
72 private Account mLastAccount
= null
, mLastAccountWhereInstantFolderWasCreated
= null
;
73 private FileDataStorageManager mStorageManager
;
75 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
76 private UploadFileOperation mCurrentUpload
= null
;
78 private NotificationManager mNotificationManager
;
79 private Notification mNotification
;
80 private int mLastPercent
;
81 private RemoteViews mDefaultNotificationContentView
;
85 * Builds a key for mPendingUploads from the account and file to upload
87 * @param account Account where the file to download is stored
88 * @param file File to download
90 private String
buildRemoteName(Account account
, OCFile file
) {
91 return account
.name
+ file
.getRemotePath();
94 private String
buildRemoteName(Account account
, String remotePath
) {
95 return account
.name
+ remotePath
;
100 * Checks if an ownCloud server version should support chunked uploads.
102 * @param version OwnCloud version instance corresponding to an ownCloud server.
103 * @return 'True' if the ownCloud server with version supports chunked uploads.
105 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
106 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
112 * Service initialization
115 public void onCreate() {
117 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
118 HandlerThread thread
= new HandlerThread("FileUploaderThread",
119 Process
.THREAD_PRIORITY_BACKGROUND
);
121 mServiceLooper
= thread
.getLooper();
122 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
123 mBinder
= new FileUploaderBinder();
128 * Entry point to add one or several files to the queue of uploads.
130 * New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
131 * although the caller activity goes away.
134 public int onStartCommand(Intent intent
, int flags
, int startId
) {
135 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)) {
136 Log
.e(TAG
, "Not enough information provided in intent");
137 return Service
.START_NOT_STICKY
;
139 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
140 if (uploadType
== -1) {
141 Log
.e(TAG
, "Incorrect upload type provided");
142 return Service
.START_NOT_STICKY
;
144 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
146 String
[] localPaths
, remotePaths
, mimeTypes
;
147 if (uploadType
== UPLOAD_SINGLE_FILE
) {
148 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
149 remotePaths
= new String
[] { intent
150 .getStringExtra(KEY_REMOTE_FILE
) };
151 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
153 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
154 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
155 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
156 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
159 if (localPaths
== null
) {
160 Log
.e(TAG
, "Incorrect array for local paths provided in upload intent");
161 return Service
.START_NOT_STICKY
;
163 if (remotePaths
== null
) {
164 Log
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
165 return Service
.START_NOT_STICKY
;
168 if (localPaths
.length
!= remotePaths
.length
) {
169 Log
.e(TAG
, "Different number of remote paths and local paths!");
170 return Service
.START_NOT_STICKY
;
173 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
174 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
176 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
177 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
178 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
179 String uploadKey
= null
;
180 UploadFileOperation newUpload
= null
;
182 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
184 for (int i
=0; i
< localPaths
.length
; i
++) {
185 uploadKey
= buildRemoteName(account
, remotePaths
[i
]);
186 file
= obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!=null
)?mimeTypes
[i
]:(String
)null
), forceOverwrite
, storageManager
);
188 newUpload
= new ChunkedUploadFileOperation(account
, file
, isInstant
, forceOverwrite
);
190 newUpload
= new UploadFileOperation(account
, file
, isInstant
, forceOverwrite
);
192 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
193 newUpload
.addDatatransferProgressListener(this);
194 requestedUploads
.add(uploadKey
);
197 } catch (IllegalArgumentException e
) {
198 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
199 return START_NOT_STICKY
;
202 if (requestedUploads
.size() > 0) {
203 Message msg
= mServiceHandler
.obtainMessage();
205 msg
.obj
= requestedUploads
;
206 mServiceHandler
.sendMessage(msg
);
209 return Service
.START_NOT_STICKY
;
214 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
216 * Implemented to perform cancellation, pause and resume of existing uploads.
219 public IBinder
onBind(Intent arg0
) {
224 * Binder to let client components to perform operations on the queue of uploads.
226 * It provides by itself the available operations.
228 public class FileUploaderBinder
extends Binder
{
231 * Cancels a pending or current upload of a remote file.
233 * @param account Owncloud account where the remote file will be stored.
234 * @param file A file in the queue of pending uploads
236 public void cancel(Account account
, OCFile file
) {
237 UploadFileOperation upload
= null
;
238 synchronized (mPendingUploads
) {
239 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
241 if (upload
!= null
) {
248 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
250 * @param account Owncloud account where the remote file will be stored.
251 * @param file A file that could be in the queue of pending uploads
253 public boolean isUploading(Account account
, OCFile file
) {
254 synchronized (mPendingUploads
) {
255 return (mPendingUploads
.containsKey(buildRemoteName(account
, file
)));
264 * Upload worker. Performs the pending uploads in the order they were requested.
266 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
268 private static class ServiceHandler
extends Handler
{
269 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
270 FileUploader mService
;
271 public ServiceHandler(Looper looper
, FileUploader service
) {
274 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
279 public void handleMessage(Message msg
) {
280 @SuppressWarnings("unchecked")
281 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
282 if (msg
.obj
!= null
) {
283 Iterator
<String
> it
= requestedUploads
.iterator();
284 while (it
.hasNext()) {
285 mService
.uploadFile(it
.next());
288 mService
.stopSelf(msg
.arg1
);
296 * Core upload method: sends the file(s) to upload
298 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
300 public void uploadFile(String uploadKey
) {
302 synchronized(mPendingUploads
) {
303 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
306 if (mCurrentUpload
!= null
) {
308 notifyUploadStart(mCurrentUpload
);
311 /// prepare client object to send requests to the ownCloud server
312 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
313 mLastAccount
= mCurrentUpload
.getAccount();
314 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
315 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
318 /// create remote folder for instant uploads, "if necessary" (would be great that HEAD to a folder worked as with files, we should check; but it's not WebDAV standard, anyway
319 if (mCurrentUpload
.isInstant() && !mLastAccountWhereInstantFolderWasCreated
.equals(mCurrentUpload
.getAccount())) {
320 mLastAccountWhereInstantFolderWasCreated
= mCurrentUpload
.getAccount();
321 createRemoteFolderForInstantUploads(mUploadClient
, mStorageManager
);
324 /// perform the upload
325 RemoteOperationResult uploadResult
= null
;
327 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
328 if (uploadResult
.isSuccess()) {
329 saveUploadedFile(mCurrentUpload
.getFile(), mStorageManager
);
333 synchronized(mPendingUploads
) {
334 mPendingUploads
.remove(uploadKey
);
339 notifyUploadResult(uploadResult
, mCurrentUpload
);
341 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
348 * Create remote folder for instant uploads if necessary.
350 * @param client WebdavClient to the ownCloud server.
351 * @param storageManager Interface to the local database caching the data in the server.
352 * @return 'True' if the folder exists when the methods finishes.
354 private boolean createRemoteFolderForInstantUploads(WebdavClient client
, FileDataStorageManager storageManager
) {
355 boolean result
= true
;
356 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
357 if (instantUploadDir
== null
) {
358 result
= client
.createDirectory(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
); // fail could just mean that it already exists, but local database is not synchronized; the upload will be started anyway
359 OCFile newDir
= new OCFile(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
360 newDir
.setMimetype("DIR");
361 newDir
.setParentId(storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId());
362 storageManager
.saveFile(newDir
);
368 * Saves a new OC File after a successful upload.
370 * @param file OCFile describing the uploaded file
371 * @param storageManager Interface to the database where the new OCFile has to be stored.
372 * @param parentDirId Id of the parent OCFile.
374 private void saveUploadedFile(OCFile file
, FileDataStorageManager storageManager
) {
375 file
.setModificationTimestamp(System
.currentTimeMillis());
376 storageManager
.saveFile(file
);
380 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
, boolean forceOverwrite
, FileDataStorageManager storageManager
) {
381 OCFile newFile
= new OCFile(remotePath
);
382 newFile
.setStoragePath(localPath
);
383 newFile
.setLastSyncDate(0);
384 newFile
.setKeepInSync(forceOverwrite
);
387 if (localPath
!= null
&& localPath
.length() > 0) {
388 File localFile
= new File(localPath
);
389 newFile
.setFileLength(localFile
.length());
390 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
393 if (mimeType
== null
|| mimeType
.length() <= 0) {
395 mimeType
= MimeTypeMap
.getSingleton()
396 .getMimeTypeFromExtension(
397 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
398 } catch (IndexOutOfBoundsException e
) {
399 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
402 if (mimeType
== null
) {
403 mimeType
= "application/octet-stream";
405 newFile
.setMimetype(mimeType
);
408 String parentPath
= new File(remotePath
).getParent();
409 parentPath
= parentPath
.endsWith("/")?parentPath
:parentPath
+"/" ;
410 long parentDirId
= storageManager
.getFileByPath(parentPath
).getFileId();
411 newFile
.setParentId(parentDirId
);
418 * Creates a status notification to show the upload progress
420 * @param upload Upload operation starting.
422 private void notifyUploadStart(UploadFileOperation upload
) {
423 /// create status notification with a progress bar
425 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
426 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
427 mDefaultNotificationContentView
= mNotification
.contentView
;
428 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
429 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
430 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, new File(upload
.getStoragePath()).getName()));
431 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
433 /// includes a pending intent in the notification showing the details view of the file
434 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
435 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
436 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
437 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
438 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, showDetailsIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
);
440 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
445 * Callback method to update the progress bar in the status notification
448 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
449 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
450 if (percent
!= mLastPercent
) {
451 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
452 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
453 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
454 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
456 mLastPercent
= percent
;
461 * Callback method to update the progress bar in the status notification (old version)
464 public void onTransferProgress(long progressRate
) {
465 // NOTHING TO DO HERE ANYMORE
470 * Updates the status notification with the result of an upload operation.
472 * @param uploadResult Result of the upload operation.
473 * @param upload Finished upload operation
475 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
476 if (uploadResult
.isCancelled()) {
477 /// cancelled operation -> silent removal of progress notification
478 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
480 } else if (uploadResult
.isSuccess()) {
481 /// success -> silent update of progress notification to success message
482 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
483 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
484 mNotification
.contentView
= mDefaultNotificationContentView
;
486 /// includes a pending intent in the notification showing the details view of the file
487 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
488 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
489 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
490 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
491 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, showDetailsIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
);
493 mNotification
.setLatestEventInfo( getApplicationContext(),
494 getString(R
.string
.uploader_upload_succeeded_ticker
),
495 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), (new File(upload
.getStoragePath())).getName()),
496 mNotification
.contentIntent
);
498 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
500 /* Notification about multiple uploads: pending of update
501 mNotification.setLatestEventInfo( getApplicationContext(),
502 getString(R.string.uploader_upload_succeeded_ticker),
503 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
504 mNotification.contentIntent);
508 /// fail -> explicit failure notification
509 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
510 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
511 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
512 // TODO put something smart in the contentIntent below
513 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
514 finalNotification
.setLatestEventInfo( getApplicationContext(),
515 getString(R
.string
.uploader_upload_failed_ticker
),
516 String
.format(getString(R
.string
.uploader_upload_failed_content_single
), (new File(upload
.getStoragePath())).getName()),
517 finalNotification
.contentIntent
);
519 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
521 /* Notification about multiple uploads failure: pending of update
522 finalNotification.setLatestEventInfo( getApplicationContext(),
523 getString(R.string.uploader_upload_failed_ticker),
524 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
525 finalNotification.contentIntent);
533 * Sends a broadcast in order to the interested activities can update their view
535 * @param upload Finished upload operation
536 * @param uploadResult Result of the upload operation
538 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
539 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
540 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote path, after possible automatic renaming
541 end
.putExtra(EXTRA_FILE_PATH
, upload
.getStoragePath());
542 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
543 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
544 end
.putExtra(EXTRA_PARENT_DIR_ID
, upload
.getFile().getParentId());