1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
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.
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.
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/>.
19 package com
.owncloud
.android
.files
.services
;
22 import java
.io
.IOException
;
23 import java
.util
.AbstractList
;
24 import java
.util
.HashMap
;
25 import java
.util
.Iterator
;
27 import java
.util
.Vector
;
28 import java
.util
.concurrent
.ConcurrentHashMap
;
29 import java
.util
.concurrent
.ConcurrentMap
;
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
.operations
.common
.RemoteFile
;
38 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperation
;
39 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
;
40 import com
.owncloud
.android
.operations
.UploadFileOperation
;
41 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
.ResultCode
;
42 import com
.owncloud
.android
.lib
.operations
.remote
.ExistenceCheckRemoteOperation
;
43 import com
.owncloud
.android
.lib
.operations
.remote
.ReadRemoteFileOperation
;
44 import com
.owncloud
.android
.lib
.utils
.OwnCloudVersion
;
45 import com
.owncloud
.android
.lib
.network
.OnDatatransferProgressListener
;
46 import com
.owncloud
.android
.lib
.accounts
.OwnCloudAccount
;
47 import com
.owncloud
.android
.lib
.network
.OwnCloudClientFactory
;
48 import com
.owncloud
.android
.lib
.network
.OwnCloudClient
;
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
;
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
;
78 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
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";
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";
92 public static final String KEY_ACCOUNT
= "ACCOUNT";
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";
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;
103 public static final int UPLOAD_SINGLE_FILE
= 0;
104 public static final int UPLOAD_MULTIPLE_FILES
= 1;
106 private static final String TAG
= FileUploader
.class.getSimpleName();
108 private Looper mServiceLooper
;
109 private ServiceHandler mServiceHandler
;
110 private IBinder mBinder
;
111 private OwnCloudClient mUploadClient
= null
;
112 private Account mLastAccount
= null
;
113 private FileDataStorageManager mStorageManager
;
115 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
116 private UploadFileOperation mCurrentUpload
= null
;
118 private NotificationManager mNotificationManager
;
119 private Notification mNotification
;
120 private int mLastPercent
;
121 private RemoteViews mDefaultNotificationContentView
;
124 public static String
getUploadFinishMessage() {
125 return FileUploader
.class.getName().toString() + UPLOAD_FINISH_MESSAGE
;
129 * Builds a key for mPendingUploads from the account and file to upload
131 * @param account Account where the file to upload is stored
132 * @param file File to upload
134 private String
buildRemoteName(Account account
, OCFile file
) {
135 return account
.name
+ file
.getRemotePath();
138 private String
buildRemoteName(Account account
, String remotePath
) {
139 return account
.name
+ remotePath
;
143 * Checks if an ownCloud server version should support chunked uploads.
145 * @param version OwnCloud version instance corresponding to an ownCloud
147 * @return 'True' if the ownCloud server with version supports chunked
150 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
151 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
155 * Service initialization
158 public void 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
);
164 mServiceLooper
= thread
.getLooper();
165 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
166 mBinder
= new FileUploaderBinder();
170 * Entry point to add one or several files to the queue of uploads.
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.
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
;
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
;
188 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
190 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
191 OCFile
[] files
= null
;
192 if (uploadType
== UPLOAD_SINGLE_FILE
) {
194 if (intent
.hasExtra(KEY_FILE
)) {
195 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
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
) };
203 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
205 if (intent
.hasExtra(KEY_FILE
)) {
206 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
214 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
215 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
216 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
220 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
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
);
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
;
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
;
235 if (remotePaths
== null
) {
236 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
237 return Service
.START_NOT_STICKY
;
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
;
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
;
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
;
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());
266 newUpload
.setRemoteFolderToBeCreated();
268 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
); // Grants that the file only upload once time
270 newUpload
.addDatatransferProgressListener(this);
271 newUpload
.addDatatransferProgressListener((FileUploaderBinder
)mBinder
);
272 requestedUploads
.add(uploadKey
);
275 } catch (IllegalArgumentException e
) {
276 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
277 return START_NOT_STICKY
;
279 } catch (IllegalStateException e
) {
280 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
281 return START_NOT_STICKY
;
283 } catch (Exception e
) {
284 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
285 return START_NOT_STICKY
;
289 if (requestedUploads
.size() > 0) {
290 Message msg
= mServiceHandler
.obtainMessage();
292 msg
.obj
= requestedUploads
;
293 mServiceHandler
.sendMessage(msg
);
295 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
296 return Service
.START_NOT_STICKY
;
300 * Provides a binder object that clients can use to perform operations on
301 * the queue of uploads, excepting the addition of new files.
303 * Implemented to perform cancellation, pause and resume of existing
307 public IBinder
onBind(Intent arg0
) {
312 * Called when ALL the bound clients were onbound.
315 public boolean onUnbind(Intent intent
) {
316 ((FileUploaderBinder
)mBinder
).clearListeners();
317 return false
; // not accepting rebinding (default behaviour)
322 * Binder to let client components to perform operations on the queue of
325 * It provides by itself the available operations.
327 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
330 * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
332 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
335 * Cancels a pending or current upload of a remote file.
337 * @param account Owncloud account where the remote file will be stored.
338 * @param file A file in the queue of pending uploads
340 public void cancel(Account account
, OCFile file
) {
341 UploadFileOperation upload
= null
;
342 synchronized (mPendingUploads
) {
343 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
345 if (upload
!= null
) {
352 public void clearListeners() {
353 mBoundListeners
.clear();
360 * Returns True when the file described by 'file' is being uploaded to
361 * the ownCloud account 'account' or waiting for it
363 * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
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
368 public boolean isUploading(Account account
, OCFile file
) {
369 if (account
== null
|| file
== null
)
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
);
382 return (mPendingUploads
.containsKey(targetKey
));
389 * Adds a listener interested in the progress of the upload for a concrete file.
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.
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
);
404 * Removes a listener interested in the progress of the upload for a concrete file.
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.
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
);
420 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
422 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
423 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
424 if (boundListener
!= null
) {
425 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
432 * Upload worker. Performs the pending uploads in the order they were
435 * Created with the Looper of a new thread, started in
436 * {@link FileUploader#onCreate()}.
438 private static class ServiceHandler
extends Handler
{
439 // don't make it a final class, and don't remove the static ; lint will
440 // warn about a possible memory leak
441 FileUploader mService
;
443 public ServiceHandler(Looper looper
, FileUploader service
) {
446 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
451 public void handleMessage(Message msg
) {
452 @SuppressWarnings("unchecked")
453 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
454 if (msg
.obj
!= null
) {
455 Iterator
<String
> it
= requestedUploads
.iterator();
456 while (it
.hasNext()) {
457 mService
.uploadFile(it
.next());
460 mService
.stopSelf(msg
.arg1
);
465 * Core upload method: sends the file(s) to upload
467 * @param uploadKey Key to access the upload to perform, contained in
470 public void uploadFile(String uploadKey
) {
472 synchronized (mPendingUploads
) {
473 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
476 if (mCurrentUpload
!= null
) {
478 notifyUploadStart(mCurrentUpload
);
480 RemoteOperationResult uploadResult
= null
, grantResult
= null
;
483 /// prepare client object to send requests to the ownCloud server
484 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
485 mLastAccount
= mCurrentUpload
.getAccount();
486 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
487 mUploadClient
= OwnCloudClientFactory
.createOwnCloudClient(mLastAccount
, getApplicationContext());
490 /// check the existence of the parent folder for the file to upload
491 String remoteParentPath
= new File(mCurrentUpload
.getRemotePath()).getParent();
492 remoteParentPath
= remoteParentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? remoteParentPath
: remoteParentPath
+ OCFile
.PATH_SEPARATOR
;
493 grantResult
= grantFolderExistence(remoteParentPath
);
495 /// perform the upload
496 if (grantResult
.isSuccess()) {
497 OCFile parent
= mStorageManager
.getFileByPath(remoteParentPath
);
498 mCurrentUpload
.getFile().setParentId(parent
.getFileId());
499 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
500 if (uploadResult
.isSuccess()) {
504 uploadResult
= grantResult
;
507 } catch (AccountsException e
) {
508 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
509 uploadResult
= new RemoteOperationResult(e
);
511 } catch (IOException e
) {
512 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
513 uploadResult
= new RemoteOperationResult(e
);
516 synchronized (mPendingUploads
) {
517 mPendingUploads
.remove(uploadKey
);
518 Log_OC
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
520 if (uploadResult
.isException()) {
521 // enforce the creation of a new client object for next uploads; this grant that a new socket will
522 // be created in the future if the current exception is due to an abrupt lose of network connection
523 mUploadClient
= null
;
529 notifyUploadResult(uploadResult
, mCurrentUpload
);
530 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
537 * Checks the existence of the folder where the current file will be uploaded both in the remote server
538 * and in the local database.
540 * If the upload is set to enforce the creation of the folder, the method tries to create it both remote
543 * @param pathToGrant Full remote path whose existence will be granted.
544 * @return An {@link OCFile} instance corresponding to the folder where the file will be uploaded.
546 private RemoteOperationResult
grantFolderExistence(String pathToGrant
) {
547 RemoteOperation operation
= new ExistenceCheckRemoteOperation(pathToGrant
, this, false
);
548 RemoteOperationResult result
= operation
.execute(mUploadClient
);
549 if (!result
.isSuccess() && result
.getCode() == ResultCode
.FILE_NOT_FOUND
&& mCurrentUpload
.isRemoteFolderToBeCreated()) {
550 operation
= new CreateFolderOperation( pathToGrant
,
553 result
= operation
.execute(mUploadClient
);
555 if (result
.isSuccess()) {
556 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
557 if (parentDir
== null
) {
558 parentDir
= createLocalFolder(pathToGrant
);
560 if (parentDir
!= null
) {
561 result
= new RemoteOperationResult(ResultCode
.OK
);
563 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
570 private OCFile
createLocalFolder(String remotePath
) {
571 String parentPath
= new File(remotePath
).getParent();
572 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
573 OCFile parent
= mStorageManager
.getFileByPath(parentPath
);
574 if (parent
== null
) {
575 parent
= createLocalFolder(parentPath
);
577 if (parent
!= null
) {
578 OCFile createdFolder
= new OCFile(remotePath
);
579 createdFolder
.setMimetype("DIR");
580 createdFolder
.setParentId(parent
.getFileId());
581 mStorageManager
.saveFile(createdFolder
);
582 return createdFolder
;
589 * Saves a OC File after a successful upload.
591 * A PROPFIND is necessary to keep the props in the local database
592 * synchronized with the server, specially the modification time and Etag
595 * TODO refactor this ugly thing
597 private void saveUploadedFile() {
598 OCFile file
= mCurrentUpload
.getFile();
599 long syncDate
= System
.currentTimeMillis();
600 file
.setLastSyncDateForData(syncDate
);
602 // new PROPFIND to keep data consistent with server
603 // in theory, should return the same we already have
604 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(mCurrentUpload
.getRemotePath());
605 RemoteOperationResult result
= operation
.execute(mUploadClient
);
606 if (result
.isSuccess()) {
607 updateOCFile(file
, result
.getData().get(0));
608 file
.setLastSyncDateForProperties(syncDate
);
611 // / maybe this would be better as part of UploadFileOperation... or
612 // maybe all this method
613 if (mCurrentUpload
.wasRenamed()) {
614 OCFile oldFile
= mCurrentUpload
.getOldFile();
615 if (oldFile
.fileExists()) {
616 oldFile
.setStoragePath(null
);
617 mStorageManager
.saveFile(oldFile
);
619 } // else: it was just an automatic renaming due to a name
620 // coincidence; nothing else is needed, the storagePath is right
621 // in the instance returned by mCurrentUpload.getFile()
624 mStorageManager
.saveFile(file
);
627 private void updateOCFile(OCFile file
, RemoteFile remoteFile
) {
628 file
.setCreationTimestamp(remoteFile
.getCreationTimestamp());
629 file
.setFileLength(remoteFile
.getLength());
630 file
.setMimetype(remoteFile
.getMimeType());
631 file
.setModificationTimestamp(remoteFile
.getModifiedTimestamp());
632 file
.setModificationTimestampAtLastSyncForData(remoteFile
.getModifiedTimestamp());
633 // file.setEtag(remoteFile.getEtag()); // TODO Etag, where available
636 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
,
637 FileDataStorageManager storageManager
) {
638 OCFile newFile
= new OCFile(remotePath
);
639 newFile
.setStoragePath(localPath
);
640 newFile
.setLastSyncDateForProperties(0);
641 newFile
.setLastSyncDateForData(0);
644 if (localPath
!= null
&& localPath
.length() > 0) {
645 File localFile
= new File(localPath
);
646 newFile
.setFileLength(localFile
.length());
647 newFile
.setLastSyncDateForData(localFile
.lastModified());
648 } // don't worry about not assigning size, the problems with localPath
649 // are checked when the UploadFileOperation instance is created
652 if (mimeType
== null
|| mimeType
.length() <= 0) {
654 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
655 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
656 } catch (IndexOutOfBoundsException e
) {
657 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
660 if (mimeType
== null
) {
661 mimeType
= "application/octet-stream";
663 newFile
.setMimetype(mimeType
);
669 * Creates a status notification to show the upload progress
671 * @param upload Upload operation starting.
673 @SuppressWarnings("deprecation")
674 private void notifyUploadStart(UploadFileOperation upload
) {
675 // / create status notification with a progress bar
677 mNotification
= new Notification(DisplayUtils
.getSeasonalIconId(), getString(R
.string
.uploader_upload_in_progress_ticker
),
678 System
.currentTimeMillis());
679 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
680 mDefaultNotificationContentView
= mNotification
.contentView
;
681 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(),
682 R
.layout
.progressbar_layout
);
683 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
684 mNotification
.contentView
.setTextViewText(R
.id
.status_text
,
685 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
686 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, DisplayUtils
.getSeasonalIconId());
688 /// includes a pending intent in the notification showing the details view of the file
689 Intent showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
690 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
691 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
692 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
693 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
694 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
696 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
700 * Callback method to update the progress bar in the status notification
703 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
704 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
705 if (percent
!= mLastPercent
) {
706 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
707 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
708 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
709 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
711 mLastPercent
= percent
;
715 * Updates the status notification with the result of an upload operation.
717 * @param uploadResult Result of the upload operation.
718 * @param upload Finished upload operation
720 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
721 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
722 if (uploadResult
.isCancelled()) {
723 // / cancelled operation -> silent removal of progress notification
724 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
726 } else if (uploadResult
.isSuccess()) {
727 // / success -> silent update of progress notification to success
729 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove
733 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
734 mNotification
.contentView
= mDefaultNotificationContentView
;
736 /// includes a pending intent in the notification showing the details view of the file
737 Intent showDetailsIntent
= null
;
738 if (PreviewImageFragment
.canBePreviewed(upload
.getFile())) {
739 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
741 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
743 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
744 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
745 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, true
);
746 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
747 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
748 (int) System
.currentTimeMillis(), showDetailsIntent
, 0);
750 mNotification
.setLatestEventInfo(getApplicationContext(),
751 getString(R
.string
.uploader_upload_succeeded_ticker
),
752 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
753 mNotification
.contentIntent
);
755 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
); // NOT
757 DbHandler db
= new DbHandler(this.getBaseContext());
758 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
763 // / fail -> explicit failure notification
764 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
765 Notification finalNotification
= new Notification(DisplayUtils
.getSeasonalIconId(),
766 getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
767 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
768 String content
= null
;
770 boolean needsToUpdateCredentials
= (uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
771 //(uploadResult.isTemporalRedirection() && uploadResult.isIdPRedirection() &&
772 (uploadResult
.isIdPRedirection() &&
773 mUploadClient
.getCredentials() == null
));
774 //MainApp.getAuthTokenTypeSamlSessionCookie().equals(mUploadClient.getAuthTokenType())));
775 if (needsToUpdateCredentials
) {
776 // let the user update credentials with one click
777 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
778 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
779 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
780 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
781 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
782 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
783 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
784 finalNotification
.contentIntent
= PendingIntent
.getActivity(this, (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
785 content
= String
.format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
786 finalNotification
.setLatestEventInfo(getApplicationContext(),
787 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
788 mUploadClient
= null
; // grant that future retries on the same account will get the fresh credentials
790 // TODO put something smart in the contentIntent below
791 // finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
794 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
795 || uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
796 // TODO we need a class to provide error messages for the users
797 // from a RemoteOperationResult and a RemoteOperation
798 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(),
799 getString(R
.string
.app_name
));
800 } else if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
801 content
= getString(R
.string
.failed_upload_quota_exceeded_text
);
804 .format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
807 // we add only for instant-uploads the InstantUploadActivity and the
809 Intent detailUploadIntent
= null
;
810 if (upload
.isInstant() && InstantUploadActivity
.IS_ENABLED
) {
811 detailUploadIntent
= new Intent(this, InstantUploadActivity
.class);
812 detailUploadIntent
.putExtra(FileUploader
.KEY_ACCOUNT
, upload
.getAccount());
814 detailUploadIntent
= new Intent(this, FailedUploadActivity
.class);
815 detailUploadIntent
.putExtra(FailedUploadActivity
.MESSAGE
, content
);
817 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(),
818 (int) System
.currentTimeMillis(), detailUploadIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
819 | PendingIntent
.FLAG_ONE_SHOT
);
821 if (upload
.isInstant()) {
824 db
= new DbHandler(this.getBaseContext());
825 String message
= uploadResult
.getLogMessage() + " errorCode: " + uploadResult
.getCode();
826 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
827 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
828 message
= getString(R
.string
.failed_upload_quota_exceeded_text
);
829 if (db
.updateFileState(upload
.getOriginalStoragePath(), DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
831 db
.putFileForLater(upload
.getOriginalStoragePath(), upload
.getAccount().name
, message
);
841 finalNotification
.setLatestEventInfo(getApplicationContext(),
842 getString(R
.string
.uploader_upload_failed_ticker
), content
, finalNotification
.contentIntent
);
844 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
850 * Sends a broadcast in order to the interested activities can update their
853 * @param upload Finished upload operation
854 * @param uploadResult Result of the upload operation
856 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
857 Intent end
= new Intent(getUploadFinishMessage());
858 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
863 if (upload
.wasRenamed()) {
864 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
866 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
867 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
868 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
869 sendStickyBroadcast(end
);