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