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
.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
;
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
;
80 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
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";
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";
94 public static final String KEY_ACCOUNT
= "ACCOUNT";
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";
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;
105 public static final int UPLOAD_SINGLE_FILE
= 0;
106 public static final int UPLOAD_MULTIPLE_FILES
= 1;
108 private static final String TAG
= FileUploader
.class.getSimpleName();
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
;
117 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
118 private UploadFileOperation mCurrentUpload
= null
;
120 private NotificationManager mNotificationManager
;
121 private NotificationCompat
.Builder mNotificationBuilder
;
122 private int mLastPercent
;
123 private RemoteViews mDefaultNotificationContentView
;
126 public static String
getUploadFinishMessage() {
127 return FileUploader
.class.getName().toString() + UPLOAD_FINISH_MESSAGE
;
131 * Builds a key for mPendingUploads from the account and file to upload
133 * @param account Account where the file to upload is stored
134 * @param file File to upload
136 private String
buildRemoteName(Account account
, OCFile file
) {
137 return account
.name
+ file
.getRemotePath();
140 private String
buildRemoteName(Account account
, String remotePath
) {
141 return account
.name
+ remotePath
;
145 * Checks if an ownCloud server version should support chunked uploads.
147 * @param version OwnCloud version instance corresponding to an ownCloud
149 * @return 'True' if the ownCloud server with version supports chunked
152 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
153 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
157 * Service initialization
160 public void 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
);
166 mServiceLooper
= thread
.getLooper();
167 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
168 mBinder
= new FileUploaderBinder();
172 * Entry point to add one or several files to the queue of uploads.
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.
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
;
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
;
190 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
192 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
193 OCFile
[] files
= null
;
194 if (uploadType
== UPLOAD_SINGLE_FILE
) {
196 if (intent
.hasExtra(KEY_FILE
)) {
197 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
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
) };
205 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
207 if (intent
.hasExtra(KEY_FILE
)) {
208 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
216 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
217 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
218 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
222 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
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
);
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
;
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
;
237 if (remotePaths
== null
) {
238 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
239 return Service
.START_NOT_STICKY
;
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
;
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
;
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
);
262 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
263 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
264 String uploadKey
= null
;
265 UploadFileOperation newUpload
= null
;
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());
272 newUpload
.setRemoteFolderToBeCreated();
274 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
); // Grants that the file only upload once time
276 newUpload
.addDatatransferProgressListener(this);
277 newUpload
.addDatatransferProgressListener((FileUploaderBinder
)mBinder
);
278 requestedUploads
.add(uploadKey
);
281 } catch (IllegalArgumentException e
) {
282 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
283 return START_NOT_STICKY
;
285 } catch (IllegalStateException e
) {
286 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
287 return START_NOT_STICKY
;
289 } catch (Exception e
) {
290 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
291 return START_NOT_STICKY
;
295 if (requestedUploads
.size() > 0) {
296 Message msg
= mServiceHandler
.obtainMessage();
298 msg
.obj
= requestedUploads
;
299 mServiceHandler
.sendMessage(msg
);
301 Log_OC
.i(TAG
, "mPendingUploads size:" + mPendingUploads
.size());
302 return Service
.START_NOT_STICKY
;
306 * Provides a binder object that clients can use to perform operations on
307 * the queue of uploads, excepting the addition of new files.
309 * Implemented to perform cancellation, pause and resume of existing
313 public IBinder
onBind(Intent arg0
) {
318 * Called when ALL the bound clients were onbound.
321 public boolean onUnbind(Intent intent
) {
322 ((FileUploaderBinder
)mBinder
).clearListeners();
323 return false
; // not accepting rebinding (default behaviour)
328 * Binder to let client components to perform operations on the queue of
331 * It provides by itself the available operations.
333 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
336 * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
338 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
= new HashMap
<String
, OnDatatransferProgressListener
>();
341 * Cancels a pending or current upload of a remote file.
343 * @param account Owncloud account where the remote file will be stored.
344 * @param file A file in the queue of pending uploads
346 public void cancel(Account account
, OCFile file
) {
347 UploadFileOperation upload
= null
;
348 synchronized (mPendingUploads
) {
349 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
351 if (upload
!= null
) {
358 public void clearListeners() {
359 mBoundListeners
.clear();
366 * Returns True when the file described by 'file' is being uploaded to
367 * the ownCloud account 'account' or waiting for it
369 * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
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
374 public boolean isUploading(Account account
, OCFile file
) {
375 if (account
== null
|| file
== null
)
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
);
388 return (mPendingUploads
.containsKey(targetKey
));
395 * Adds a listener interested in the progress of the upload for a concrete file.
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.
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
);
410 * Removes a listener interested in the progress of the upload for a concrete file.
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.
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
);
426 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
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
);
438 * Upload worker. Performs the pending uploads in the order they were
441 * Created with the Looper of a new thread, started in
442 * {@link FileUploader#onCreate()}.
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
;
449 public ServiceHandler(Looper looper
, FileUploader service
) {
452 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
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());
466 mService
.stopSelf(msg
.arg1
);
471 * Core upload method: sends the file(s) to upload
473 * @param uploadKey Key to access the upload to perform, contained in
476 public void uploadFile(String uploadKey
) {
478 synchronized (mPendingUploads
) {
479 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
482 if (mCurrentUpload
!= null
) {
484 notifyUploadStart(mCurrentUpload
);
486 RemoteOperationResult uploadResult
= null
, grantResult
= null
;
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());
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
);
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()) {
510 uploadResult
= grantResult
;
513 } catch (AccountsException e
) {
514 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
515 uploadResult
= new RemoteOperationResult(e
);
517 } catch (IOException e
) {
518 Log_OC
.e(TAG
, "Error while trying to get autorization for " + mLastAccount
.name
, e
);
519 uploadResult
= new RemoteOperationResult(e
);
522 synchronized (mPendingUploads
) {
523 mPendingUploads
.remove(uploadKey
);
524 Log_OC
.i(TAG
, "Remove CurrentUploadItem from pending upload Item Map.");
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
;
535 notifyUploadResult(uploadResult
, mCurrentUpload
);
536 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
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.
546 * If the upload is set to enforce the creation of the folder, the method tries to create it both remote
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.
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
,
559 result
= operation
.execute(mUploadClient
);
561 if (result
.isSuccess()) {
562 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
563 if (parentDir
== null
) {
564 parentDir
= createLocalFolder(pathToGrant
);
566 if (parentDir
!= null
) {
567 result
= new RemoteOperationResult(ResultCode
.OK
);
569 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
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
);
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
;
595 * Saves a OC File after a successful upload.
597 * A PROPFIND is necessary to keep the props in the local database
598 * synchronized with the server, specially the modification time and Etag
601 * TODO refactor this ugly thing
603 private void saveUploadedFile() {
604 OCFile file
= mCurrentUpload
.getFile();
605 if (file
.fileExists()) {
606 file
= mStorageManager
.getFileById(file
.getFileId());
608 long syncDate
= System
.currentTimeMillis();
609 file
.setLastSyncDateForData(syncDate
);
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
);
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
);
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()
633 mStorageManager
.saveFile(file
);
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
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);
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
661 if (mimeType
== null
|| mimeType
.length() <= 0) {
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
);
669 if (mimeType
== null
) {
670 mimeType
= "application/octet-stream";
672 newFile
.setMimetype(mimeType
);
678 * Creates a status notification to show the upload progress
680 * @param upload Upload operation starting.
682 @SuppressWarnings("deprecation")
683 private void notifyUploadStart(UploadFileOperation upload
) {
684 // / create status notification with a progress bar
686 mNotificationBuilder
= new NotificationCompat
.Builder(this);
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
)
694 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
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
705 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
709 * Callback method to update the progress bar in the status notification
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());
721 mLastPercent
= percent
;
725 * Updates the status notification with the result of an upload operation.
727 * @param uploadResult Result of the upload operation.
728 * @param upload Finished upload operation
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
);
736 } else if (uploadResult
.isSuccess()) {
737 // / success -> silent update of progress notification to success
739 mNotificationBuilder
.setOngoing(false
).setAutoCancel(true
);
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);
746 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
748 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
749 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
750 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FROM_NOTIFICATION
, true
);;
752 .setContentIntent(PendingIntent
.getActivity(
753 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
755 .setTicker(getString(R
.string
.uploader_upload_succeeded_ticker
))
756 .setContentTitle(getString(R
.string
.uploader_upload_succeeded_ticker
))
758 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
),
759 upload
.getFileName())
762 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build()); // NOT
764 DbHandler db
= new DbHandler(this.getBaseContext());
765 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
770 // / fail -> explicit failure notification
771 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
772 NotificationCompat
.Builder errorBuilder
= new NotificationCompat
.Builder(this);
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
;
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
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
800 // TODO put something smart in the contentIntent below
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
);
812 .format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
815 // we add only for instant-uploads the InstantUploadActivity and the
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());
822 detailUploadIntent
= new Intent(this, FailedUploadActivity
.class);
823 detailUploadIntent
.putExtra(FailedUploadActivity
.MESSAGE
, content
);
826 .setContentIntent(PendingIntent
.getActivity(
827 this, (int) System
.currentTimeMillis(), detailUploadIntent
, PendingIntent
.FLAG_UPDATE_CURRENT
| PendingIntent
.FLAG_ONE_SHOT
829 .setContentText(content
);
831 if (upload
.isInstant()) {
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
,
841 db
.putFileForLater(upload
.getOriginalStoragePath(), upload
.getAccount().name
, message
);
852 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, errorBuilder
.build());
858 * Sends a broadcast in order to the interested activities can update their
861 * @param upload Finished upload operation
862 * @param uploadResult Result of the upload operation
864 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
865 Intent end
= new Intent(getUploadFinishMessage());
866 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
871 if (upload
.wasRenamed()) {
872 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
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
);