Cancellation in uploads and access to details view pressing the status notification
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileUploader.java
1 package com.owncloud.android.files.services;
2
3 import java.io.File;
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;
9
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;
20
21 import eu.alefzero.webdav.OnDatatransferProgressListener;
22
23 import com.owncloud.android.network.OwnCloudClientUtils;
24
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;
42
43 import com.owncloud.android.R;
44 import eu.alefzero.webdav.WebdavClient;
45
46 public class FileUploader extends Service implements OnDatatransferProgressListener {
47
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";
53
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";
62
63 public static final int UPLOAD_SINGLE_FILE = 0;
64 public static final int UPLOAD_MULTIPLE_FILES = 1;
65
66 private static final String TAG = FileUploader.class.getSimpleName();
67
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;
74
75 private ConcurrentMap<String, UploadFileOperation> mPendingUploads = new ConcurrentHashMap<String, UploadFileOperation>();
76 private UploadFileOperation mCurrentUpload = null;
77
78 private NotificationManager mNotificationManager;
79 private Notification mNotification;
80 private int mLastPercent;
81 private RemoteViews mDefaultNotificationContentView;
82
83
84 /**
85 * Builds a key for mPendingUploads from the account and file to upload
86 *
87 * @param account Account where the file to download is stored
88 * @param file File to download
89 */
90 private String buildRemoteName(Account account, OCFile file) {
91 return account.name + file.getRemotePath();
92 }
93
94 private String buildRemoteName(Account account, String remotePath) {
95 return account.name + remotePath;
96 }
97
98
99 /**
100 * Checks if an ownCloud server version should support chunked uploads.
101 *
102 * @param version OwnCloud version instance corresponding to an ownCloud server.
103 * @return 'True' if the ownCloud server with version supports chunked uploads.
104 */
105 private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
106 return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
107 }
108
109
110
111 /**
112 * Service initialization
113 */
114 @Override
115 public void onCreate() {
116 super.onCreate();
117 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
118 HandlerThread thread = new HandlerThread("FileUploaderThread",
119 Process.THREAD_PRIORITY_BACKGROUND);
120 thread.start();
121 mServiceLooper = thread.getLooper();
122 mServiceHandler = new ServiceHandler(mServiceLooper, this);
123 mBinder = new FileUploaderBinder();
124 }
125
126
127 /**
128 * Entry point to add one or several files to the queue of uploads.
129 *
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.
132 */
133 @Override
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;
138 }
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;
143 }
144 Account account = intent.getParcelableExtra(KEY_ACCOUNT);
145
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) };
152
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);
157 }
158
159 if (localPaths == null) {
160 Log.e(TAG, "Incorrect array for local paths provided in upload intent");
161 return Service.START_NOT_STICKY;
162 }
163 if (remotePaths == null) {
164 Log.e(TAG, "Incorrect array for remote paths provided in upload intent");
165 return Service.START_NOT_STICKY;
166 }
167
168 if (localPaths.length != remotePaths.length) {
169 Log.e(TAG, "Different number of remote paths and local paths!");
170 return Service.START_NOT_STICKY;
171 }
172
173 boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
174 boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
175
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;
181 OCFile file = null;
182 FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
183 try {
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);
187 if (chunked) {
188 newUpload = new ChunkedUploadFileOperation(account, file, isInstant, forceOverwrite);
189 } else {
190 newUpload = new UploadFileOperation(account, file, isInstant, forceOverwrite);
191 }
192 mPendingUploads.putIfAbsent(uploadKey, newUpload);
193 newUpload.addDatatransferProgressListener(this);
194 requestedUploads.add(uploadKey);
195 }
196
197 } catch (IllegalArgumentException e) {
198 Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
199 return START_NOT_STICKY;
200 }
201
202 if (requestedUploads.size() > 0) {
203 Message msg = mServiceHandler.obtainMessage();
204 msg.arg1 = startId;
205 msg.obj = requestedUploads;
206 mServiceHandler.sendMessage(msg);
207 }
208
209 return Service.START_NOT_STICKY;
210 }
211
212
213 /**
214 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
215 *
216 * Implemented to perform cancellation, pause and resume of existing uploads.
217 */
218 @Override
219 public IBinder onBind(Intent arg0) {
220 return mBinder;
221 }
222
223 /**
224 * Binder to let client components to perform operations on the queue of uploads.
225 *
226 * It provides by itself the available operations.
227 */
228 public class FileUploaderBinder extends Binder {
229
230 /**
231 * Cancels a pending or current upload of a remote file.
232 *
233 * @param account Owncloud account where the remote file will be stored.
234 * @param file A file in the queue of pending uploads
235 */
236 public void cancel(Account account, OCFile file) {
237 UploadFileOperation upload = null;
238 synchronized (mPendingUploads) {
239 upload = mPendingUploads.remove(buildRemoteName(account, file));
240 }
241 if (upload != null) {
242 upload.cancel();
243 }
244 }
245
246
247 /**
248 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
249 *
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
252 */
253 public boolean isUploading(Account account, OCFile file) {
254 synchronized (mPendingUploads) {
255 return (mPendingUploads.containsKey(buildRemoteName(account, file)));
256 }
257 }
258 }
259
260
261
262
263 /**
264 * Upload worker. Performs the pending uploads in the order they were requested.
265 *
266 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
267 */
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) {
272 super(looper);
273 if (service == null)
274 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
275 mService = service;
276 }
277
278 @Override
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());
286 }
287 }
288 mService.stopSelf(msg.arg1);
289 }
290 }
291
292
293
294
295 /**
296 * Core upload method: sends the file(s) to upload
297 *
298 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
299 */
300 public void uploadFile(String uploadKey) {
301
302 synchronized(mPendingUploads) {
303 mCurrentUpload = mPendingUploads.get(uploadKey);
304 }
305
306 if (mCurrentUpload != null) {
307
308 notifyUploadStart(mCurrentUpload);
309
310
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());
316 }
317
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);
322 }
323
324 /// perform the upload
325 RemoteOperationResult uploadResult = null;
326 try {
327 uploadResult = mCurrentUpload.execute(mUploadClient);
328 if (uploadResult.isSuccess()) {
329 saveUploadedFile(mCurrentUpload.getFile(), mStorageManager);
330 }
331
332 } finally {
333 synchronized(mPendingUploads) {
334 mPendingUploads.remove(uploadKey);
335 }
336 }
337
338 /// notify result
339 notifyUploadResult(uploadResult, mCurrentUpload);
340
341 sendFinalBroadcast(mCurrentUpload, uploadResult);
342
343 }
344
345 }
346
347 /**
348 * Create remote folder for instant uploads if necessary.
349 *
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.
353 */
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);
363 }
364 return result;
365 }
366
367 /**
368 * Saves a new OC File after a successful upload.
369 *
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.
373 */
374 private void saveUploadedFile(OCFile file, FileDataStorageManager storageManager) {
375 file.setModificationTimestamp(System.currentTimeMillis());
376 storageManager.saveFile(file);
377 }
378
379
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);
385
386 // size
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
391
392 // MIME type
393 if (mimeType == null || mimeType.length() <= 0) {
394 try {
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);
400 }
401 }
402 if (mimeType == null) {
403 mimeType = "application/octet-stream";
404 }
405 newFile.setMimetype(mimeType);
406
407 // parent dir
408 String parentPath = new File(remotePath).getParent();
409 parentPath = parentPath.endsWith("/")?parentPath:parentPath+"/" ;
410 long parentDirId = storageManager.getFileByPath(parentPath).getFileId();
411 newFile.setParentId(parentDirId);
412
413 return newFile;
414 }
415
416
417 /**
418 * Creates a status notification to show the upload progress
419 *
420 * @param upload Upload operation starting.
421 */
422 private void notifyUploadStart(UploadFileOperation upload) {
423 /// create status notification with a progress bar
424 mLastPercent = 0;
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);
432
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);
439
440 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
441 }
442
443
444 /**
445 * Callback method to update the progress bar in the status notification
446 */
447 @Override
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);
455 }
456 mLastPercent = percent;
457 }
458
459
460 /**
461 * Callback method to update the progress bar in the status notification (old version)
462 */
463 @Override
464 public void onTransferProgress(long progressRate) {
465 // NOTHING TO DO HERE ANYMORE
466 }
467
468
469 /**
470 * Updates the status notification with the result of an upload operation.
471 *
472 * @param uploadResult Result of the upload operation.
473 * @param upload Finished upload operation
474 */
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);
479
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;
485
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);
492
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);
497
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
499
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);
505 */
506
507 } else {
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);
518
519 mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
520
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);
526 } */
527 }
528
529 }
530
531
532 /**
533 * Sends a broadcast in order to the interested activities can update their view
534 *
535 * @param upload Finished upload operation
536 * @param uploadResult Result of the upload operation
537 */
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());
545 sendBroadcast(end);
546 }
547
548
549 }