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