Notification improvements:
[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.lib.resources.files.RemoteFile;
38 import com.owncloud.android.lib.common.operations.RemoteOperation;
39 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
40 import com.owncloud.android.operations.UploadFileOperation;
41 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
42 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
43 import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
44 import com.owncloud.android.lib.resources.files.FileUtils;
45 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
46 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
47 import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
48 import com.owncloud.android.lib.common.OwnCloudClientFactory;
49 import com.owncloud.android.lib.common.OwnCloudClient;
50 import com.owncloud.android.ui.activity.FailedUploadActivity;
51 import com.owncloud.android.ui.activity.FileActivity;
52 import com.owncloud.android.ui.activity.FileDisplayActivity;
53 import com.owncloud.android.ui.activity.InstantUploadActivity;
54 import com.owncloud.android.ui.preview.PreviewImageActivity;
55 import com.owncloud.android.ui.preview.PreviewImageFragment;
56 import com.owncloud.android.utils.DisplayUtils;
57 import com.owncloud.android.utils.Log_OC;
58
59 import android.accounts.Account;
60 import android.accounts.AccountManager;
61 import android.accounts.AccountsException;
62 import android.app.Notification;
63 import android.app.NotificationManager;
64 import android.app.PendingIntent;
65 import android.app.Service;
66 import android.content.Intent;
67 import android.os.Binder;
68 import android.os.Handler;
69 import android.os.HandlerThread;
70 import android.os.IBinder;
71 import android.os.Looper;
72 import android.os.Message;
73 import android.os.Process;
74 import android.support.v4.app.NotificationCompat;
75 import android.webkit.MimeTypeMap;
76 import android.widget.RemoteViews;
77
78
79
80 public class FileUploader extends Service implements OnDatatransferProgressListener {
81
82 private static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
83 public static final String EXTRA_UPLOAD_RESULT = "RESULT";
84 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
85 public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
86 public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
87 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
88
89 public static final String KEY_FILE = "FILE";
90 public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
91 public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
92 public static final String KEY_MIME_TYPE = "MIME_TYPE";
93
94 public static final String KEY_ACCOUNT = "ACCOUNT";
95
96 public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
97 public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
98 public static final String KEY_INSTANT_UPLOAD = "INSTANT_UPLOAD";
99 public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
100
101 public static final int LOCAL_BEHAVIOUR_COPY = 0;
102 public static final int LOCAL_BEHAVIOUR_MOVE = 1;
103 public static final int LOCAL_BEHAVIOUR_FORGET = 2;
104
105 public static final int UPLOAD_SINGLE_FILE = 0;
106 public static final int UPLOAD_MULTIPLE_FILES = 1;
107
108 private static final String TAG = FileUploader.class.getSimpleName();
109
110 private Looper mServiceLooper;
111 private ServiceHandler mServiceHandler;
112 private IBinder mBinder;
113 private OwnCloudClient mUploadClient = null;
114 private Account mLastAccount = null;
115 private FileDataStorageManager mStorageManager;
116
117 private ConcurrentMap<String, UploadFileOperation> mPendingUploads = new ConcurrentHashMap<String, UploadFileOperation>();
118 private UploadFileOperation mCurrentUpload = null;
119
120 private NotificationManager mNotificationManager;
121 private NotificationCompat.Builder mNotificationBuilder;
122 private int mLastPercent;
123 private RemoteViews mDefaultNotificationContentView;
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 String versionString = aMgr.getUserData(account, Constants.KEY_OC_VERSION_STRING);
260 OwnCloudVersion ocv = new OwnCloudVersion(version, versionString);
261
262 boolean chunked = FileUploader.chunkedUploadIsSupported(ocv);
263 AbstractList<String> requestedUploads = new Vector<String>();
264 String uploadKey = null;
265 UploadFileOperation newUpload = null;
266 try {
267 for (int i = 0; i < files.length; i++) {
268 uploadKey = buildRemoteName(account, files[i].getRemotePath());
269 newUpload = new UploadFileOperation(account, files[i], chunked, isInstant, forceOverwrite, localAction,
270 getApplicationContext());
271 if (isInstant) {
272 newUpload.setRemoteFolderToBeCreated();
273 }
274 mPendingUploads.putIfAbsent(uploadKey, newUpload); // Grants that the file only upload once time
275
276 newUpload.addDatatransferProgressListener(this);
277 newUpload.addDatatransferProgressListener((FileUploaderBinder)mBinder);
278 requestedUploads.add(uploadKey);
279 }
280
281 } catch (IllegalArgumentException e) {
282 Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
283 return START_NOT_STICKY;
284
285 } catch (IllegalStateException e) {
286 Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
287 return START_NOT_STICKY;
288
289 } catch (Exception e) {
290 Log_OC.e(TAG, "Unexpected exception while processing upload intent", e);
291 return START_NOT_STICKY;
292
293 }
294
295 if (requestedUploads.size() > 0) {
296 Message msg = mServiceHandler.obtainMessage();
297 msg.arg1 = startId;
298 msg.obj = requestedUploads;
299 mServiceHandler.sendMessage(msg);
300 }
301 Log_OC.i(TAG, "mPendingUploads size:" + mPendingUploads.size());
302 return Service.START_NOT_STICKY;
303 }
304
305 /**
306 * Provides a binder object that clients can use to perform operations on
307 * the queue of uploads, excepting the addition of new files.
308 *
309 * Implemented to perform cancellation, pause and resume of existing
310 * uploads.
311 */
312 @Override
313 public IBinder onBind(Intent arg0) {
314 return mBinder;
315 }
316
317 /**
318 * Called when ALL the bound clients were onbound.
319 */
320 @Override
321 public boolean onUnbind(Intent intent) {
322 ((FileUploaderBinder)mBinder).clearListeners();
323 return false; // not accepting rebinding (default behaviour)
324 }
325
326
327 /**
328 * Binder to let client components to perform operations on the queue of
329 * uploads.
330 *
331 * It provides by itself the available operations.
332 */
333 public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
334
335 /**
336 * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
337 */
338 private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
339
340 /**
341 * Cancels a pending or current upload of a remote file.
342 *
343 * @param account Owncloud account where the remote file will be stored.
344 * @param file A file in the queue of pending uploads
345 */
346 public void cancel(Account account, OCFile file) {
347 UploadFileOperation upload = null;
348 synchronized (mPendingUploads) {
349 upload = mPendingUploads.remove(buildRemoteName(account, file));
350 }
351 if (upload != null) {
352 upload.cancel();
353 }
354 }
355
356
357
358 public void clearListeners() {
359 mBoundListeners.clear();
360 }
361
362
363
364
365 /**
366 * Returns True when the file described by 'file' is being uploaded to
367 * the ownCloud account 'account' or waiting for it
368 *
369 * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
370 *
371 * @param account Owncloud account where the remote file will be stored.
372 * @param file A file that could be in the queue of pending uploads
373 */
374 public boolean isUploading(Account account, OCFile file) {
375 if (account == null || file == null)
376 return false;
377 String targetKey = buildRemoteName(account, file);
378 synchronized (mPendingUploads) {
379 if (file.isFolder()) {
380 // this can be slow if there are many uploads :(
381 Iterator<String> it = mPendingUploads.keySet().iterator();
382 boolean found = false;
383 while (it.hasNext() && !found) {
384 found = it.next().startsWith(targetKey);
385 }
386 return found;
387 } else {
388 return (mPendingUploads.containsKey(targetKey));
389 }
390 }
391 }
392
393
394 /**
395 * Adds a listener interested in the progress of the upload for a concrete file.
396 *
397 * @param listener Object to notify about progress of transfer.
398 * @param account ownCloud account holding the file of interest.
399 * @param file {@link OCfile} of interest for listener.
400 */
401 public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
402 if (account == null || file == null || listener == null) return;
403 String targetKey = buildRemoteName(account, file);
404 mBoundListeners.put(targetKey, listener);
405 }
406
407
408
409 /**
410 * Removes a listener interested in the progress of the upload for a concrete file.
411 *
412 * @param listener Object to notify about progress of transfer.
413 * @param account ownCloud account holding the file of interest.
414 * @param file {@link OCfile} of interest for listener.
415 */
416 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
417 if (account == null || file == null || listener == null) return;
418 String targetKey = buildRemoteName(account, file);
419 if (mBoundListeners.get(targetKey) == listener) {
420 mBoundListeners.remove(targetKey);
421 }
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 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 @SuppressWarnings("deprecation")
683 private void notifyUploadStart(UploadFileOperation upload) {
684 // / create status notification with a progress bar
685 mLastPercent = 0;
686 mNotificationBuilder = new NotificationCompat.Builder(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 if (uploadResult.isCancelled()) {
733 // / cancelled operation -> silent removal of progress notification
734 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
735
736 } else if (uploadResult.isSuccess()) {
737 // / success -> silent update of progress notification to success
738 // message
739 mNotificationBuilder.setOngoing(false).setAutoCancel(true);
740
741 /// includes a pending intent in the notification showing the details view of the file
742 Intent showDetailsIntent = null;
743 if (PreviewImageFragment.canBePreviewed(upload.getFile())) {
744 showDetailsIntent = new Intent(this, PreviewImageActivity.class);
745 } else {
746 showDetailsIntent = new Intent(this, FileDisplayActivity.class);
747 }
748 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
749 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
750 showDetailsIntent.putExtra(FileActivity.EXTRA_FROM_NOTIFICATION, true);;
751 mNotificationBuilder
752 .setContentIntent(PendingIntent.getActivity(
753 this, (int) System.currentTimeMillis(), showDetailsIntent, 0
754 ))
755 .setTicker(getString(R.string.uploader_upload_succeeded_ticker))
756 .setContentTitle(getString(R.string.uploader_upload_succeeded_ticker))
757 .setContentText(
758 String.format(getString(R.string.uploader_upload_succeeded_content_single),
759 upload.getFileName())
760 );
761
762 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build()); // NOT
763 // AN
764 DbHandler db = new DbHandler(this.getBaseContext());
765 db.removeIUPendingFile(mCurrentUpload.getOriginalStoragePath());
766 db.close();
767
768 } else {
769
770 // / fail -> explicit failure notification
771 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
772 NotificationCompat.Builder errorBuilder = new NotificationCompat.Builder(this);
773 errorBuilder
774 .setSmallIcon(R.drawable.notification_icon)
775 .setTicker(getString(R.string.uploader_upload_failed_ticker))
776 .setContentTitle(getString(R.string.uploader_upload_failed_ticker))
777 .setAutoCancel(true);
778 String content = null;
779
780 boolean needsToUpdateCredentials = (uploadResult.getCode() == ResultCode.UNAUTHORIZED ||
781 //(uploadResult.isTemporalRedirection() && uploadResult.isIdPRedirection() &&
782 (uploadResult.isIdPRedirection() &&
783 mUploadClient.getCredentials() == null));
784 //MainApp.getAuthTokenTypeSamlSessionCookie().equals(mUploadClient.getAuthTokenType())));
785 if (needsToUpdateCredentials) {
786 // let the user update credentials with one click
787 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
788 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount());
789 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
790 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
791 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
792 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
793 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
794 errorBuilder.setContentIntent(PendingIntent.getActivity(
795 this, (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT
796 ));
797 content = String.format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
798 mUploadClient = null; // grant that future retries on the same account will get the fresh credentials
799 } else {
800 // TODO put something smart in the contentIntent below
801
802 if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL
803 || uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
804 // TODO we need a class to provide error messages for the users
805 // from a RemoteOperationResult and a RemoteOperation
806 content = String.format(getString(R.string.error__upload__local_file_not_copied), upload.getFileName(),
807 getString(R.string.app_name));
808 } else if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
809 content = getString(R.string.failed_upload_quota_exceeded_text);
810 } else {
811 content = String
812 .format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
813 }
814
815 // we add only for instant-uploads the InstantUploadActivity and the
816 // db entry
817 Intent detailUploadIntent = null;
818 if (upload.isInstant() && InstantUploadActivity.IS_ENABLED) {
819 detailUploadIntent = new Intent(this, InstantUploadActivity.class);
820 detailUploadIntent.putExtra(FileUploader.KEY_ACCOUNT, upload.getAccount());
821 } else {
822 detailUploadIntent = new Intent(this, FailedUploadActivity.class);
823 detailUploadIntent.putExtra(FailedUploadActivity.MESSAGE, content);
824 }
825 errorBuilder
826 .setContentIntent(PendingIntent.getActivity(
827 this, (int) System.currentTimeMillis(), detailUploadIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT
828 ))
829 .setContentText(content);
830
831 if (upload.isInstant()) {
832 DbHandler db = null;
833 try {
834 db = new DbHandler(this.getBaseContext());
835 String message = uploadResult.getLogMessage() + " errorCode: " + uploadResult.getCode();
836 Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
837 if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
838 message = getString(R.string.failed_upload_quota_exceeded_text);
839 if (db.updateFileState(upload.getOriginalStoragePath(), DbHandler.UPLOAD_STATUS_UPLOAD_FAILED,
840 message) == 0) {
841 db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name, message);
842 }
843 }
844 } finally {
845 if (db != null) {
846 db.close();
847 }
848 }
849 }
850 }
851
852 mNotificationManager.notify(R.string.uploader_upload_failed_ticker, errorBuilder.build());
853 }
854
855 }
856
857 /**
858 * Sends a broadcast in order to the interested activities can update their
859 * view
860 *
861 * @param upload Finished upload operation
862 * @param uploadResult Result of the upload operation
863 */
864 private void sendFinalBroadcast(UploadFileOperation upload, RemoteOperationResult uploadResult) {
865 Intent end = new Intent(getUploadFinishMessage());
866 end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
867 // path, after
868 // possible
869 // automatic
870 // renaming
871 if (upload.wasRenamed()) {
872 end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
873 }
874 end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
875 end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
876 end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
877 sendStickyBroadcast(end);
878 }
879
880 }