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