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