Context handling made consistent
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileUploader.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 *
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.
8 *
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.
13 *
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/>.
16 *
17 */
18
19 package com.owncloud.android.files.services;
20
21 import java.io.File;
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;
27
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;
38
39 import eu.alefzero.webdav.OnDatatransferProgressListener;
40
41 import com.owncloud.android.network.OwnCloudClientUtils;
42
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;
60
61 import com.owncloud.android.R;
62 import eu.alefzero.webdav.WebdavClient;
63
64 public class FileUploader extends Service implements OnDatatransferProgressListener {
65
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";
71
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";
80
81 public static final int UPLOAD_SINGLE_FILE = 0;
82 public static final int UPLOAD_MULTIPLE_FILES = 1;
83
84 private static final String TAG = FileUploader.class.getSimpleName();
85
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;
92
93 private ConcurrentMap<String, UploadFileOperation> mPendingUploads = new ConcurrentHashMap<String, UploadFileOperation>();
94 private UploadFileOperation mCurrentUpload = null;
95
96 private NotificationManager mNotificationManager;
97 private Notification mNotification;
98 private int mLastPercent;
99 private RemoteViews mDefaultNotificationContentView;
100
101
102 /**
103 * Builds a key for mPendingUploads from the account and file to upload
104 *
105 * @param account Account where the file to download is stored
106 * @param file File to download
107 */
108 private String buildRemoteName(Account account, OCFile file) {
109 return account.name + file.getRemotePath();
110 }
111
112 private String buildRemoteName(Account account, String remotePath) {
113 return account.name + remotePath;
114 }
115
116
117 /**
118 * Checks if an ownCloud server version should support chunked uploads.
119 *
120 * @param version OwnCloud version instance corresponding to an ownCloud server.
121 * @return 'True' if the ownCloud server with version supports chunked uploads.
122 */
123 private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
124 return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
125 }
126
127
128
129 /**
130 * Service initialization
131 */
132 @Override
133 public void onCreate() {
134 super.onCreate();
135 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
136 HandlerThread thread = new HandlerThread("FileUploaderThread",
137 Process.THREAD_PRIORITY_BACKGROUND);
138 thread.start();
139 mServiceLooper = thread.getLooper();
140 mServiceHandler = new ServiceHandler(mServiceLooper, this);
141 mBinder = new FileUploaderBinder();
142 }
143
144
145 /**
146 * Entry point to add one or several files to the queue of uploads.
147 *
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.
150 */
151 @Override
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;
156 }
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;
161 }
162 Account account = intent.getParcelableExtra(KEY_ACCOUNT);
163
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) };
170
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);
175 }
176
177 if (localPaths == null) {
178 Log.e(TAG, "Incorrect array for local paths provided in upload intent");
179 return Service.START_NOT_STICKY;
180 }
181 if (remotePaths == null) {
182 Log.e(TAG, "Incorrect array for remote paths provided in upload intent");
183 return Service.START_NOT_STICKY;
184 }
185
186 if (localPaths.length != remotePaths.length) {
187 Log.e(TAG, "Different number of remote paths and local paths!");
188 return Service.START_NOT_STICKY;
189 }
190
191 boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
192 boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
193
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;
199 OCFile file = null;
200 FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
201 boolean fixed = false;
202 if (isInstant) {
203 fixed = checkAndFixInstantUploadDirectory(storageManager);
204 }
205 try {
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);
209 if (chunked) {
210 newUpload = new ChunkedUploadFileOperation(account, file, isInstant, forceOverwrite);
211 } else {
212 newUpload = new UploadFileOperation(account, file, isInstant, forceOverwrite);
213 }
214 if (fixed && i==0) {
215 newUpload.setRemoteFolderToBeCreated();
216 }
217 mPendingUploads.putIfAbsent(uploadKey, newUpload);
218 newUpload.addDatatransferProgressListener(this);
219 requestedUploads.add(uploadKey);
220 }
221
222 } catch (IllegalArgumentException e) {
223 Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
224 return START_NOT_STICKY;
225
226 } catch (IllegalStateException e) {
227 Log.e(TAG, "Bad information provided in intent: " + e.getMessage());
228 return START_NOT_STICKY;
229
230 } catch (Exception e) {
231 Log.e(TAG, "Unexpected exception while processing upload intent", e);
232 return START_NOT_STICKY;
233
234 }
235
236 if (requestedUploads.size() > 0) {
237 Message msg = mServiceHandler.obtainMessage();
238 msg.arg1 = startId;
239 msg.obj = requestedUploads;
240 mServiceHandler.sendMessage(msg);
241 }
242
243 return Service.START_NOT_STICKY;
244 }
245
246
247 /**
248 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
249 *
250 * Implemented to perform cancellation, pause and resume of existing uploads.
251 */
252 @Override
253 public IBinder onBind(Intent arg0) {
254 return mBinder;
255 }
256
257 /**
258 * Binder to let client components to perform operations on the queue of uploads.
259 *
260 * It provides by itself the available operations.
261 */
262 public class FileUploaderBinder extends Binder {
263
264 /**
265 * Cancels a pending or current upload of a remote file.
266 *
267 * @param account Owncloud account where the remote file will be stored.
268 * @param file A file in the queue of pending uploads
269 */
270 public void cancel(Account account, OCFile file) {
271 UploadFileOperation upload = null;
272 synchronized (mPendingUploads) {
273 upload = mPendingUploads.remove(buildRemoteName(account, file));
274 }
275 if (upload != null) {
276 upload.cancel();
277 }
278 }
279
280
281 /**
282 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
283 *
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
286 */
287 public boolean isUploading(Account account, OCFile file) {
288 synchronized (mPendingUploads) {
289 return (mPendingUploads.containsKey(buildRemoteName(account, file)));
290 }
291 }
292 }
293
294
295
296
297 /**
298 * Upload worker. Performs the pending uploads in the order they were requested.
299 *
300 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
301 */
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) {
306 super(looper);
307 if (service == null)
308 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
309 mService = service;
310 }
311
312 @Override
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());
320 }
321 }
322 mService.stopSelf(msg.arg1);
323 }
324 }
325
326
327
328
329 /**
330 * Core upload method: sends the file(s) to upload
331 *
332 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
333 */
334 public void uploadFile(String uploadKey) {
335
336 synchronized(mPendingUploads) {
337 mCurrentUpload = mPendingUploads.get(uploadKey);
338 }
339
340 if (mCurrentUpload != null) {
341
342 notifyUploadStart(mCurrentUpload);
343
344
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());
350 }
351
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
355 }
356
357
358 /// perform the upload
359 RemoteOperationResult uploadResult = null;
360 try {
361 uploadResult = mCurrentUpload.execute(mUploadClient);
362 if (uploadResult.isSuccess()) {
363 saveUploadedFile(mCurrentUpload.getFile(), mStorageManager);
364 }
365
366 } finally {
367 synchronized(mPendingUploads) {
368 mPendingUploads.remove(uploadKey);
369 }
370 }
371
372 /// notify result
373 notifyUploadResult(uploadResult, mCurrentUpload);
374
375 sendFinalBroadcast(mCurrentUpload, uploadResult);
376
377 }
378
379 }
380
381 /**
382 * Saves a new OC File after a successful upload.
383 *
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.
387 */
388 private void saveUploadedFile(OCFile file, FileDataStorageManager storageManager) {
389 file.setModificationTimestamp(System.currentTimeMillis());
390 storageManager.saveFile(file);
391 }
392
393
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);
402 return true;
403 }
404 return false;
405 }
406
407
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);
413
414 // size
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
419
420 // MIME type
421 if (mimeType == null || mimeType.length() <= 0) {
422 try {
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);
428 }
429 }
430 if (mimeType == null) {
431 mimeType = "application/octet-stream";
432 }
433 newFile.setMimetype(mimeType);
434
435 // parent dir
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);
441 }
442 long parentDirId = parentDir.getFileId();
443 newFile.setParentId(parentDirId);
444 return newFile;
445 }
446
447
448 /**
449 * Creates a status notification to show the upload progress
450 *
451 * @param upload Upload operation starting.
452 */
453 private void notifyUploadStart(UploadFileOperation upload) {
454 /// create status notification with a progress bar
455 mLastPercent = 0;
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);
463
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);
470
471 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
472 }
473
474
475 /**
476 * Callback method to update the progress bar in the status notification
477 */
478 @Override
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);
486 }
487 mLastPercent = percent;
488 }
489
490
491 /**
492 * Callback method to update the progress bar in the status notification (old version)
493 */
494 @Override
495 public void onTransferProgress(long progressRate) {
496 // NOTHING TO DO HERE ANYMORE
497 }
498
499
500 /**
501 * Updates the status notification with the result of an upload operation.
502 *
503 * @param uploadResult Result of the upload operation.
504 * @param upload Finished upload operation
505 */
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);
510
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;
516
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);
523
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);
528
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
530
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);
536 */
537
538 } else {
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);
549
550 mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
551
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);
557 } */
558 }
559
560 }
561
562
563 /**
564 * Sends a broadcast in order to the interested activities can update their view
565 *
566 * @param upload Finished upload operation
567 * @param uploadResult Result of the upload operation
568 */
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());
576 sendBroadcast(end);
577 }
578
579
580 }