8107eb5810d845916502a2e3e5a9948487349ebe
[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.HashMap;
24 import java.util.Iterator;
25 import java.util.Map;
26 import java.util.Vector;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
29
30 import org.apache.http.HttpStatus;
31 import org.apache.jackrabbit.webdav.MultiStatus;
32 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
33
34 import com.owncloud.android.authenticator.AccountAuthenticator;
35 import com.owncloud.android.datamodel.FileDataStorageManager;
36 import com.owncloud.android.datamodel.OCFile;
37 import com.owncloud.android.files.InstantUploadBroadcastReceiver;
38 import com.owncloud.android.operations.ChunkedUploadFileOperation;
39 import com.owncloud.android.operations.RemoteOperationResult;
40 import com.owncloud.android.operations.UploadFileOperation;
41 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
42 import com.owncloud.android.ui.activity.FileDetailActivity;
43 import com.owncloud.android.ui.fragment.FileDetailFragment;
44 import com.owncloud.android.utils.OwnCloudVersion;
45
46 import eu.alefzero.webdav.OnDatatransferProgressListener;
47 import eu.alefzero.webdav.WebdavEntry;
48 import eu.alefzero.webdav.WebdavUtils;
49
50 import com.owncloud.android.network.OwnCloudClientUtils;
51
52 import android.accounts.Account;
53 import android.accounts.AccountManager;
54 import android.app.Notification;
55 import android.app.NotificationManager;
56 import android.app.PendingIntent;
57 import android.app.Service;
58 import android.content.Intent;
59 import android.os.Binder;
60 import android.os.Handler;
61 import android.os.HandlerThread;
62 import android.os.IBinder;
63 import android.os.Looper;
64 import android.os.Message;
65 import android.os.Process;
66 import android.util.Log;
67 import android.webkit.MimeTypeMap;
68 import android.widget.RemoteViews;
69
70 import com.owncloud.android.R;
71 import eu.alefzero.webdav.WebdavClient;
72
73 public class FileUploader extends Service implements OnDatatransferProgressListener {
74
75 public static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
76 public static final String EXTRA_UPLOAD_RESULT = "RESULT";
77 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
78 public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
79 public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
80 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
81
82 public static final String KEY_FILE = "FILE";
83 public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
84 public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
85 public static final String KEY_MIME_TYPE = "MIME_TYPE";
86
87 public static final String KEY_ACCOUNT = "ACCOUNT";
88
89 public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
90 public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
91 public static final String KEY_INSTANT_UPLOAD = "INSTANT_UPLOAD";
92 public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
93
94 public static final int LOCAL_BEHAVIOUR_COPY = 0;
95 public static final int LOCAL_BEHAVIOUR_MOVE = 1;
96 public static final int LOCAL_BEHAVIOUR_FORGET = 2;
97
98 public static final int UPLOAD_SINGLE_FILE = 0;
99 public static final int UPLOAD_MULTIPLE_FILES = 1;
100
101 private static final String TAG = FileUploader.class.getSimpleName();
102
103 private Looper mServiceLooper;
104 private ServiceHandler mServiceHandler;
105 private IBinder mBinder;
106 private WebdavClient mUploadClient = null;
107 private Account mLastAccount = null;
108 private FileDataStorageManager mStorageManager;
109
110 private ConcurrentMap<String, UploadFileOperation> mPendingUploads = new ConcurrentHashMap<String, UploadFileOperation>();
111 private UploadFileOperation mCurrentUpload = null;
112
113 private NotificationManager mNotificationManager;
114 private Notification mNotification;
115 private int mLastPercent;
116 private RemoteViews mDefaultNotificationContentView;
117
118
119 /**
120 * Builds a key for mPendingUploads from the account and file to upload
121 *
122 * @param account Account where the file to upload is stored
123 * @param file File to upload
124 */
125 private String buildRemoteName(Account account, OCFile file) {
126 return account.name + file.getRemotePath();
127 }
128
129 private String buildRemoteName(Account account, String remotePath) {
130 return account.name + remotePath;
131 }
132
133
134 /**
135 * Checks if an ownCloud server version should support chunked uploads.
136 *
137 * @param version OwnCloud version instance corresponding to an ownCloud server.
138 * @return 'True' if the ownCloud server with version supports chunked uploads.
139 */
140 private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
141 return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
142 }
143
144
145
146 /**
147 * Service initialization
148 */
149 @Override
150 public void onCreate() {
151 super.onCreate();
152 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
153 HandlerThread thread = new HandlerThread("FileUploaderThread",
154 Process.THREAD_PRIORITY_BACKGROUND);
155 thread.start();
156 mServiceLooper = thread.getLooper();
157 mServiceHandler = new ServiceHandler(mServiceLooper, this);
158 mBinder = new FileUploaderBinder();
159 }
160
161
162 /**
163 * Entry point to add one or several files to the queue of uploads.
164 *
165 * New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
166 * although the caller activity goes away.
167 */
168 @Override
169 public int onStartCommand(Intent intent, int flags, int startId) {
170 if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE) || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
171 Log.e(TAG, "Not enough information provided in intent");
172 return Service.START_NOT_STICKY;
173 }
174 int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
175 if (uploadType == -1) {
176 Log.e(TAG, "Incorrect upload type provided");
177 return Service.START_NOT_STICKY;
178 }
179 Account account = intent.getParcelableExtra(KEY_ACCOUNT);
180
181 String[] localPaths = null, remotePaths = null, mimeTypes = null;
182 OCFile[] files = null;
183 if (uploadType == UPLOAD_SINGLE_FILE) {
184
185 if (intent.hasExtra(KEY_FILE)) {
186 files = new OCFile[] {intent.getParcelableExtra(KEY_FILE) };
187
188 } else {
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) };
192 }
193
194 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
195
196 if (intent.hasExtra(KEY_FILE)) {
197 files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO will this casting work fine?
198
199 } else {
200 localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
201 remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
202 mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
203 }
204 }
205
206 FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
207
208 boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
209 boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
210 int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_COPY);
211 boolean fixed = false;
212 if (isInstant) {
213 fixed = checkAndFixInstantUploadDirectory(storageManager); // MUST be done BEFORE calling obtainNewOCFileToUpload
214 }
215
216 if (intent.hasExtra(KEY_FILE) && files == null) {
217 Log.e(TAG, "Incorrect array for OCFiles provided in upload intent");
218 return Service.START_NOT_STICKY;
219
220 } else if (!intent.hasExtra(KEY_FILE)) {
221 if (localPaths == null) {
222 Log.e(TAG, "Incorrect array for local paths provided in upload intent");
223 return Service.START_NOT_STICKY;
224 }
225 if (remotePaths == null) {
226 Log.e(TAG, "Incorrect array for remote paths provided in upload intent");
227 return Service.START_NOT_STICKY;
228 }
229 if (localPaths.length != remotePaths.length) {
230 Log.e(TAG, "Different number of remote paths and local paths!");
231 return Service.START_NOT_STICKY;
232 }
233
234 files = new OCFile[localPaths.length];
235 for (int i=0; i < localPaths.length; i++) {
236 files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes!=null)?mimeTypes[i]:(String)null), storageManager);
237 }
238 }
239
240 OwnCloudVersion ocv = new OwnCloudVersion(AccountManager.get(this).getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
241 boolean chunked = FileUploader.chunkedUploadIsSupported(ocv);
242 AbstractList<String> requestedUploads = new Vector<String>();
243 String uploadKey = null;
244 UploadFileOperation newUpload = null;
245 try {
246 for (int i=0; i < files.length; i++) {
247 uploadKey = buildRemoteName(account, files[i].getRemotePath());
248 if (chunked) {
249 newUpload = new ChunkedUploadFileOperation(account, files[i], isInstant, forceOverwrite, localAction);
250 } else {
251 newUpload = new UploadFileOperation(account, files[i], isInstant, forceOverwrite, localAction);
252 }
253 if (fixed && i==0) {
254 newUpload.setRemoteFolderToBeCreated();
255 }
256 mPendingUploads.putIfAbsent(uploadKey, newUpload);
257 newUpload.addDatatransferProgressListener(this);
258 newUpload.addDatatransferProgressListener((FileUploaderBinder)mBinder);
259 requestedUploads.add(uploadKey);
260 }
261
262 } catch (IllegalArgumentException e) {
263 Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
264 return START_NOT_STICKY;
265
266 } catch (IllegalStateException e) {
267 Log.e(TAG, "Bad information provided in intent: " + e.getMessage());
268 return START_NOT_STICKY;
269
270 } catch (Exception e) {
271 Log.e(TAG, "Unexpected exception while processing upload intent", e);
272 return START_NOT_STICKY;
273
274 }
275
276 if (requestedUploads.size() > 0) {
277 Message msg = mServiceHandler.obtainMessage();
278 msg.arg1 = startId;
279 msg.obj = requestedUploads;
280 mServiceHandler.sendMessage(msg);
281 }
282
283 return Service.START_NOT_STICKY;
284 }
285
286
287 /**
288 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
289 *
290 * Implemented to perform cancellation, pause and resume of existing uploads.
291 */
292 @Override
293 public IBinder onBind(Intent arg0) {
294 return mBinder;
295 }
296
297 /**
298 * Called when ALL the bound clients were onbound.
299 */
300 @Override
301 public boolean onUnbind(Intent intent) {
302 ((FileUploaderBinder)mBinder).clearListeners();
303 return false; // not accepting rebinding (default behaviour)
304 }
305
306
307 /**
308 * Binder to let client components to perform operations on the queue of uploads.
309 *
310 * It provides by itself the available operations.
311 */
312 public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
313
314 /**
315 * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
316 */
317 private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
318
319 /**
320 * Cancels a pending or current upload of a remote file.
321 *
322 * @param account Owncloud account where the remote file will be stored.
323 * @param file A file in the queue of pending uploads
324 */
325 public void cancel(Account account, OCFile file) {
326 UploadFileOperation upload = null;
327 synchronized (mPendingUploads) {
328 upload = mPendingUploads.remove(buildRemoteName(account, file));
329 }
330 if (upload != null) {
331 upload.cancel();
332 }
333 }
334
335
336
337 public void clearListeners() {
338 mBoundListeners.clear();
339 }
340
341
342
343
344 /**
345 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
346 *
347 * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
348 *
349 * @param account Owncloud account where the remote file will be stored.
350 * @param file A file that could be in the queue of pending uploads
351 */
352 public boolean isUploading(Account account, OCFile file) {
353 if (account == null || file == null) return false;
354 String targetKey = buildRemoteName(account, file);
355 synchronized (mPendingUploads) {
356 if (file.isDirectory()) {
357 // this can be slow if there are many uploads :(
358 Iterator<String> it = mPendingUploads.keySet().iterator();
359 boolean found = false;
360 while (it.hasNext() && !found) {
361 found = it.next().startsWith(targetKey);
362 }
363 return found;
364 } else {
365 return (mPendingUploads.containsKey(targetKey));
366 }
367 }
368 }
369
370
371 /**
372 * Adds a listener interested in the progress of the upload for a concrete file.
373 *
374 * @param listener Object to notify about progress of transfer.
375 * @param account ownCloud account holding the file of interest.
376 * @param file {@link OCfile} of interest for listener.
377 */
378 public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
379 if (account == null || file == null || listener == null) return;
380 String targetKey = buildRemoteName(account, file);
381 mBoundListeners.put(targetKey, listener);
382 }
383
384
385
386 /**
387 * Removes a listener interested in the progress of the upload for a concrete file.
388 *
389 * @param listener Object to notify about progress of transfer.
390 * @param account ownCloud account holding the file of interest.
391 * @param file {@link OCfile} of interest for listener.
392 */
393 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
394 if (account == null || file == null || listener == null) return;
395 String targetKey = buildRemoteName(account, file);
396 if (mBoundListeners.get(targetKey) == listener) {
397 mBoundListeners.remove(targetKey);
398 }
399 }
400
401
402 @Override
403 public void onTransferProgress(long progressRate) {
404 // old way, should not be in use any more
405 }
406
407
408 @Override
409 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
410 String fileName) {
411 String key = buildRemoteName(mCurrentUpload.getAccount(), mCurrentUpload.getFile());
412 OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
413 if (boundListener != null) {
414 boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
415 }
416 }
417
418 }
419
420
421
422
423 /**
424 * Upload worker. Performs the pending uploads in the order they were requested.
425 *
426 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
427 */
428 private static class ServiceHandler extends Handler {
429 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
430 FileUploader mService;
431 public ServiceHandler(Looper looper, FileUploader service) {
432 super(looper);
433 if (service == null)
434 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
435 mService = service;
436 }
437
438 @Override
439 public void handleMessage(Message msg) {
440 @SuppressWarnings("unchecked")
441 AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
442 if (msg.obj != null) {
443 Iterator<String> it = requestedUploads.iterator();
444 while (it.hasNext()) {
445 mService.uploadFile(it.next());
446 }
447 }
448 mService.stopSelf(msg.arg1);
449 }
450 }
451
452
453
454
455 /**
456 * Core upload method: sends the file(s) to upload
457 *
458 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
459 */
460 public void uploadFile(String uploadKey) {
461
462 synchronized(mPendingUploads) {
463 mCurrentUpload = mPendingUploads.get(uploadKey);
464 }
465
466 if (mCurrentUpload != null) {
467
468 notifyUploadStart(mCurrentUpload);
469
470
471 /// prepare client object to send requests to the ownCloud server
472 if (mUploadClient == null || !mLastAccount.equals(mCurrentUpload.getAccount())) {
473 mLastAccount = mCurrentUpload.getAccount();
474 mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
475 mUploadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
476 }
477
478 /// create remote folder for instant uploads
479 if (mCurrentUpload.isRemoteFolderToBeCreated()) {
480 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
481 }
482
483
484 /// perform the upload
485 RemoteOperationResult uploadResult = null;
486 try {
487 uploadResult = mCurrentUpload.execute(mUploadClient);
488 if (uploadResult.isSuccess()) {
489 saveUploadedFile();
490 }
491
492 } finally {
493 synchronized(mPendingUploads) {
494 mPendingUploads.remove(uploadKey);
495 }
496 }
497
498 /// notify result
499 notifyUploadResult(uploadResult, mCurrentUpload);
500
501 sendFinalBroadcast(mCurrentUpload, uploadResult);
502
503 }
504
505 }
506
507 /**
508 * Saves a OC File after a successful upload.
509 *
510 * A PROPFIND is necessary to keep the props in the local database synchronized with the server,
511 * specially the modification time and Etag (where available)
512 *
513 * TODO refactor this ugly thing
514 */
515 private void saveUploadedFile() {
516 OCFile file = mCurrentUpload.getFile();
517 long syncDate = System.currentTimeMillis();
518 file.setLastSyncDateForData(syncDate);
519
520 /// new PROPFIND to keep data consistent with server in theory, should return the same we already have
521 PropFindMethod propfind = null;
522 RemoteOperationResult result = null;
523 try {
524 propfind = new PropFindMethod(mUploadClient.getBaseUri() + WebdavUtils.encodePath(mCurrentUpload.getRemotePath()));
525 int status = mUploadClient.executeMethod(propfind);
526 boolean isMultiStatus = (status == HttpStatus.SC_MULTI_STATUS);
527 if (isMultiStatus) {
528 MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
529 WebdavEntry we = new WebdavEntry(resp.getResponses()[0],
530 mUploadClient.getBaseUri().getPath());
531 updateOCFile(file, we);
532 file.setLastSyncDateForProperties(syncDate);
533
534 } else {
535 mUploadClient.exhaustResponse(propfind.getResponseBodyAsStream());
536 }
537
538 result = new RemoteOperationResult(isMultiStatus, status);
539 Log.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": " + result.getLogMessage());
540
541 } catch (Exception e) {
542 result = new RemoteOperationResult(e);
543 Log.e(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": " + result.getLogMessage(), e);
544
545 } finally {
546 if (propfind != null)
547 propfind.releaseConnection();
548 }
549
550 /// maybe this would be better as part of UploadFileOperation... or maybe all this method
551 if (mCurrentUpload.wasRenamed()) {
552 OCFile oldFile = mCurrentUpload.getOldFile();
553 if (oldFile.fileExists()) {
554 oldFile.setStoragePath(null);
555 mStorageManager.saveFile(oldFile);
556
557 } // else: it was just an automatic renaming due to a name coincidence; nothing else is needed, the storagePath is right in the instance returned by mCurrentUpload.getFile()
558 }
559
560 mStorageManager.saveFile(file);
561 }
562
563
564 private void updateOCFile(OCFile file, WebdavEntry we) {
565 file.setCreationTimestamp(we.createTimestamp());
566 file.setFileLength(we.contentLength());
567 file.setMimetype(we.contentType());
568 file.setModificationTimestamp(we.modifiedTimestamp());
569 file.setModificationTimestampAtLastSyncForData(we.modifiedTimestamp());
570 // file.setEtag(mCurrentUpload.getEtag()); // TODO Etag, where available
571 }
572
573
574 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager) {
575 OCFile instantUploadDir = storageManager.getFileByPath(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
576 if (instantUploadDir == null) {
577 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
578 OCFile newDir = new OCFile(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
579 newDir.setMimetype("DIR");
580 newDir.setParentId(storageManager.getFileByPath(OCFile.PATH_SEPARATOR).getFileId());
581 storageManager.saveFile(newDir);
582 return true;
583 }
584 return false;
585 }
586
587
588 private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType, FileDataStorageManager storageManager) {
589 OCFile newFile = new OCFile(remotePath);
590 newFile.setStoragePath(localPath);
591 newFile.setLastSyncDateForProperties(0);
592 newFile.setLastSyncDateForData(0);
593
594 // size
595 if (localPath != null && localPath.length() > 0) {
596 File localFile = new File(localPath);
597 newFile.setFileLength(localFile.length());
598 newFile.setLastSyncDateForData(localFile.lastModified());
599 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
600
601 // MIME type
602 if (mimeType == null || mimeType.length() <= 0) {
603 try {
604 mimeType = MimeTypeMap.getSingleton()
605 .getMimeTypeFromExtension(
606 remotePath.substring(remotePath.lastIndexOf('.') + 1));
607 } catch (IndexOutOfBoundsException e) {
608 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
609 }
610 }
611 if (mimeType == null) {
612 mimeType = "application/octet-stream";
613 }
614 newFile.setMimetype(mimeType);
615
616 // parent dir
617 String parentPath = new File(remotePath).getParent();
618 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR ;
619 OCFile parentDir = storageManager.getFileByPath(parentPath);
620 if (parentDir == null) {
621 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath);
622 }
623 long parentDirId = parentDir.getFileId();
624 newFile.setParentId(parentDirId);
625 return newFile;
626 }
627
628
629 /**
630 * Creates a status notification to show the upload progress
631 *
632 * @param upload Upload operation starting.
633 */
634 @SuppressWarnings("deprecation")
635 private void notifyUploadStart(UploadFileOperation upload) {
636 /// create status notification with a progress bar
637 mLastPercent = 0;
638 mNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_in_progress_ticker), System.currentTimeMillis());
639 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
640 mDefaultNotificationContentView = mNotification.contentView;
641 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
642 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
643 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
644 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
645
646 /// includes a pending intent in the notification showing the details view of the file
647 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
648 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
649 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
650 showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
651 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
652 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
653
654 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
655 }
656
657
658 /**
659 * Callback method to update the progress bar in the status notification
660 */
661 @Override
662 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
663 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
664 if (percent != mLastPercent) {
665 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
666 String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
667 mNotification.contentView.setTextViewText(R.id.status_text, text);
668 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
669 }
670 mLastPercent = percent;
671 }
672
673
674 /**
675 * Callback method to update the progress bar in the status notification (old version)
676 */
677 @Override
678 public void onTransferProgress(long progressRate) {
679 // NOTHING TO DO HERE ANYMORE
680 }
681
682
683 /**
684 * Updates the status notification with the result of an upload operation.
685 *
686 * @param uploadResult Result of the upload operation.
687 * @param upload Finished upload operation
688 */
689 private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
690 if (uploadResult.isCancelled()) {
691 /// cancelled operation -> silent removal of progress notification
692 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
693
694 } else if (uploadResult.isSuccess()) {
695 /// success -> silent update of progress notification to success message
696 mNotification.flags ^= Notification.FLAG_ONGOING_EVENT; // remove the ongoing flag
697 mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
698 mNotification.contentView = mDefaultNotificationContentView;
699
700 /// includes a pending intent in the notification showing the details view of the file
701 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
702 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
703 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
704 showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
705 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
706 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
707
708 mNotification.setLatestEventInfo( getApplicationContext(),
709 getString(R.string.uploader_upload_succeeded_ticker),
710 String.format(getString(R.string.uploader_upload_succeeded_content_single), upload.getFileName()),
711 mNotification.contentIntent);
712
713 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
714
715 /* Notification about multiple uploads: pending of update
716 mNotification.setLatestEventInfo( getApplicationContext(),
717 getString(R.string.uploader_upload_succeeded_ticker),
718 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
719 mNotification.contentIntent);
720 */
721
722 } else {
723 /// fail -> explicit failure notification
724 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
725 Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
726 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
727 // TODO put something smart in the contentIntent below
728 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
729
730 String content = null;
731 if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL ||
732 uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
733 // TODO we need a class to provide error messages for the users from a RemoteOperationResult and a RemoteOperation
734 content = String.format(getString(R.string.error__upload__local_file_not_copied), upload.getFileName(), getString(R.string.app_name));
735 } else {
736 content = String.format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
737 }
738 finalNotification.setLatestEventInfo( getApplicationContext(),
739 getString(R.string.uploader_upload_failed_ticker),
740 content,
741 finalNotification.contentIntent);
742
743 mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
744
745 /* Notification about multiple uploads failure: pending of update
746 finalNotification.setLatestEventInfo( getApplicationContext(),
747 getString(R.string.uploader_upload_failed_ticker),
748 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
749 finalNotification.contentIntent);
750 } */
751 }
752
753 }
754
755
756 /**
757 * Sends a broadcast in order to the interested activities can update their view
758 *
759 * @param upload Finished upload operation
760 * @param uploadResult Result of the upload operation
761 */
762 private void sendFinalBroadcast(UploadFileOperation upload, RemoteOperationResult uploadResult) {
763 Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
764 end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote path, after possible automatic renaming
765 if (upload.wasRenamed()) {
766 end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
767 }
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);
772 }
773
774
775 }