check available beta version
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileUploader.java
1 /**
2 * ownCloud Android client application
3 *
4 * Copyright (C) 2012 Bartek Przybylski
5 * Copyright (C) 2012-2015 ownCloud Inc.
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2,
9 * as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 */
20
21 package com.owncloud.android.files.services;
22
23 import java.io.File;
24 import java.util.AbstractList;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.Map;
28 import java.util.Vector;
29
30 import android.accounts.Account;
31 import android.accounts.AccountManager;
32 import android.accounts.OnAccountsUpdateListener;
33 import android.app.NotificationManager;
34 import android.app.PendingIntent;
35 import android.app.Service;
36 import android.content.Intent;
37 import android.os.Binder;
38 import android.os.Handler;
39 import android.os.HandlerThread;
40 import android.os.IBinder;
41 import android.os.Looper;
42 import android.os.Message;
43 import android.os.Process;
44 import android.support.v4.app.NotificationCompat;
45 import android.util.Pair;
46 import android.webkit.MimeTypeMap;
47
48 import com.owncloud.android.R;
49 import com.owncloud.android.authentication.AccountUtils;
50 import com.owncloud.android.authentication.AuthenticatorActivity;
51 import com.owncloud.android.datamodel.FileDataStorageManager;
52 import com.owncloud.android.datamodel.OCFile;
53 import com.owncloud.android.db.DbHandler;
54 import com.owncloud.android.lib.common.OwnCloudAccount;
55 import com.owncloud.android.lib.common.OwnCloudClient;
56 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
57 import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
58 import com.owncloud.android.lib.common.operations.RemoteOperation;
59 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
60 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
61 import com.owncloud.android.lib.common.utils.Log_OC;
62 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
63 import com.owncloud.android.lib.resources.files.FileUtils;
64 import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
65 import com.owncloud.android.lib.resources.files.RemoteFile;
66 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
67 import com.owncloud.android.notifications.NotificationBuilderWithProgressBar;
68 import com.owncloud.android.notifications.NotificationDelayer;
69 import com.owncloud.android.operations.CreateFolderOperation;
70 import com.owncloud.android.operations.UploadFileOperation;
71 import com.owncloud.android.operations.common.SyncOperation;
72 import com.owncloud.android.ui.activity.FileActivity;
73 import com.owncloud.android.ui.activity.FileDisplayActivity;
74 import com.owncloud.android.utils.ErrorMessageAdapter;
75 import com.owncloud.android.utils.UriUtils;
76
77
78 public class FileUploader extends Service
79 implements OnDatatransferProgressListener, OnAccountsUpdateListener {
80
81 private static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
82 public static final String EXTRA_UPLOAD_RESULT = "RESULT";
83 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
84 public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
85 public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
86 public static final String EXTRA_LINKED_TO_PATH = "LINKED_TO";
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 public static final int LOCAL_BEHAVIOUR_REMOVE = 3;
105
106 public static final int UPLOAD_SINGLE_FILE = 0;
107 public static final int UPLOAD_MULTIPLE_FILES = 1;
108
109 private static final String TAG = FileUploader.class.getSimpleName();
110
111 private Looper mServiceLooper;
112 private ServiceHandler mServiceHandler;
113 private IBinder mBinder;
114 private OwnCloudClient mUploadClient = null;
115 private Account mCurrentAccount = null;
116 private FileDataStorageManager mStorageManager;
117
118 private IndexedForest<UploadFileOperation> mPendingUploads = new IndexedForest<UploadFileOperation>();
119 private UploadFileOperation mCurrentUpload = null;
120
121 private NotificationManager mNotificationManager;
122 private NotificationCompat.Builder mNotificationBuilder;
123 private int mLastPercent;
124
125 private static final String MIME_TYPE_PDF = "application/pdf";
126 private static final String FILE_EXTENSION_PDF = ".pdf";
127
128
129 public static String getUploadFinishMessage() {
130 return FileUploader.class.getName() + UPLOAD_FINISH_MESSAGE;
131 }
132
133 /**
134 * Checks if an ownCloud server version should support chunked uploads.
135 *
136 * @param version OwnCloud version instance corresponding to an ownCloud
137 * server.
138 * @return 'True' if the ownCloud server with version supports chunked
139 * uploads.
140 *
141 * TODO - move to OCClient
142 */
143 private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
144 return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
145 }
146
147 /**
148 * Service initialization
149 */
150 @Override
151 public void onCreate() {
152 super.onCreate();
153 Log_OC.d(TAG, "Creating service");
154 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
155 HandlerThread thread = new HandlerThread("FileUploaderThread",
156 Process.THREAD_PRIORITY_BACKGROUND);
157 thread.start();
158 mServiceLooper = thread.getLooper();
159 mServiceHandler = new ServiceHandler(mServiceLooper, this);
160 mBinder = new FileUploaderBinder();
161
162 // add AccountsUpdatedListener
163 AccountManager am = AccountManager.get(getApplicationContext());
164 am.addOnAccountsUpdatedListener(this, null, false);
165 }
166
167 /**
168 * Service clean up
169 */
170 @Override
171 public void onDestroy() {
172 Log_OC.v(TAG, "Destroying service" );
173 mBinder = null;
174 mServiceHandler = null;
175 mServiceLooper.quit();
176 mServiceLooper = null;
177 mNotificationManager = null;
178
179 // remove AccountsUpdatedListener
180 AccountManager am = AccountManager.get(getApplicationContext());
181 am.removeOnAccountsUpdatedListener(this);
182
183 super.onDestroy();
184 }
185
186
187 /**
188 * Entry point to add one or several files to the queue of uploads.
189 *
190 * New uploads are added calling to startService(), resulting in a call to
191 * this method. This ensures the service will keep on working although the
192 * caller activity goes away.
193 */
194 @Override
195 public int onStartCommand(Intent intent, int flags, int startId) {
196 Log_OC.d(TAG, "Starting command with id " + startId);
197
198 if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE)
199 || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
200 Log_OC.e(TAG, "Not enough information provided in intent");
201 return Service.START_NOT_STICKY;
202 }
203 int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
204 if (uploadType == -1) {
205 Log_OC.e(TAG, "Incorrect upload type provided");
206 return Service.START_NOT_STICKY;
207 }
208 Account account = intent.getParcelableExtra(KEY_ACCOUNT);
209 if (!AccountUtils.exists(account, getApplicationContext())) {
210 return Service.START_NOT_STICKY;
211 }
212
213 String[] localPaths = null, remotePaths = null, mimeTypes = null;
214 OCFile[] files = null;
215 if (uploadType == UPLOAD_SINGLE_FILE) {
216
217 if (intent.hasExtra(KEY_FILE)) {
218 files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) };
219
220 } else {
221 localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
222 remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
223 mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
224 }
225
226 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
227
228 if (intent.hasExtra(KEY_FILE)) {
229 files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO
230 // will
231 // this
232 // casting
233 // work
234 // fine?
235
236 } else {
237 localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
238 remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
239 mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
240 }
241 }
242
243 FileDataStorageManager storageManager = new FileDataStorageManager(account,
244 getContentResolver());
245
246 boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
247 boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
248 int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_COPY);
249
250 if (intent.hasExtra(KEY_FILE) && files == null) {
251 Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
252 return Service.START_NOT_STICKY;
253
254 } else if (!intent.hasExtra(KEY_FILE)) {
255 if (localPaths == null) {
256 Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent");
257 return Service.START_NOT_STICKY;
258 }
259 if (remotePaths == null) {
260 Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent");
261 return Service.START_NOT_STICKY;
262 }
263 if (localPaths.length != remotePaths.length) {
264 Log_OC.e(TAG, "Different number of remote paths and local paths!");
265 return Service.START_NOT_STICKY;
266 }
267
268 files = new OCFile[localPaths.length];
269 for (int i = 0; i < localPaths.length; i++) {
270 files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i],
271 ((mimeTypes != null) ? mimeTypes[i] : null));
272 if (files[i] == null) {
273 // TODO @andomaex add failure Notification
274 return Service.START_NOT_STICKY;
275 }
276 }
277 }
278
279 OwnCloudVersion ocv = AccountUtils.getServerVersion(account);
280
281 boolean chunked = FileUploader.chunkedUploadIsSupported(ocv);
282 AbstractList<String> requestedUploads = new Vector<String>();
283 String uploadKey = null;
284 UploadFileOperation newUpload = null;
285 try {
286 for (int i = 0; i < files.length; i++) {
287 newUpload = new UploadFileOperation(
288 account,
289 files[i],
290 chunked,
291 isInstant,
292 forceOverwrite, localAction,
293 getApplicationContext()
294 );
295 if (isInstant) {
296 newUpload.setRemoteFolderToBeCreated();
297 }
298 newUpload.addDatatransferProgressListener(this);
299 newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
300 Pair<String, String> putResult = mPendingUploads.putIfAbsent(
301 account, files[i].getRemotePath(), newUpload
302 );
303 uploadKey = putResult.first;
304 requestedUploads.add(uploadKey);
305 }
306
307 } catch (IllegalArgumentException e) {
308 Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
309 return START_NOT_STICKY;
310
311 } catch (IllegalStateException e) {
312 Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
313 return START_NOT_STICKY;
314
315 } catch (Exception e) {
316 Log_OC.e(TAG, "Unexpected exception while processing upload intent", e);
317 return START_NOT_STICKY;
318
319 }
320
321 if (requestedUploads.size() > 0) {
322 Message msg = mServiceHandler.obtainMessage();
323 msg.arg1 = startId;
324 msg.obj = requestedUploads;
325 mServiceHandler.sendMessage(msg);
326 }
327 return Service.START_NOT_STICKY;
328 }
329
330 /**
331 * Provides a binder object that clients can use to perform operations on
332 * the queue of uploads, excepting the addition of new files.
333 *
334 * Implemented to perform cancellation, pause and resume of existing
335 * uploads.
336 */
337 @Override
338 public IBinder onBind(Intent arg0) {
339 return mBinder;
340 }
341
342 /**
343 * Called when ALL the bound clients were onbound.
344 */
345 @Override
346 public boolean onUnbind(Intent intent) {
347 ((FileUploaderBinder)mBinder).clearListeners();
348 return false; // not accepting rebinding (default behaviour)
349 }
350
351 @Override
352 public void onAccountsUpdated(Account[] accounts) {
353 // Review current upload, and cancel it if its account doen't exist
354 if (mCurrentUpload != null &&
355 !AccountUtils.exists(mCurrentUpload.getAccount(), getApplicationContext())) {
356 mCurrentUpload.cancel();
357 }
358 // The rest of uploads are cancelled when they try to start
359 }
360
361 /**
362 * Binder to let client components to perform operations on the queue of
363 * uploads.
364 *
365 * It provides by itself the available operations.
366 */
367 public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
368
369 /**
370 * Map of listeners that will be reported about progress of uploads from a
371 * {@link FileUploaderBinder} instance
372 */
373 private Map<String, OnDatatransferProgressListener> mBoundListeners =
374 new HashMap<String, OnDatatransferProgressListener>();
375
376 /**
377 * Cancels a pending or current upload of a remote file.
378 *
379 * @param account ownCloud account where the remote file will be stored.
380 * @param file A file in the queue of pending uploads
381 */
382 public void cancel(Account account, OCFile file) {
383 Pair<UploadFileOperation, String> removeResult = mPendingUploads.remove(account, file.getRemotePath());
384 UploadFileOperation upload = removeResult.first;
385 if (upload != null) {
386 upload.cancel();
387 } else {
388 if (mCurrentUpload != null && mCurrentAccount != null &&
389 mCurrentUpload.getRemotePath().startsWith(file.getRemotePath()) &&
390 account.name.equals(mCurrentAccount.name)) {
391 mCurrentUpload.cancel();
392 }
393 }
394 }
395
396 /**
397 * Cancels all the uploads for an account
398 *
399 * @param account ownCloud account.
400 */
401 public void cancel(Account account) {
402 Log_OC.d(TAG, "Account= " + account.name);
403
404 if (mCurrentUpload != null) {
405 Log_OC.d(TAG, "Current Upload Account= " + mCurrentUpload.getAccount().name);
406 if (mCurrentUpload.getAccount().name.equals(account.name)) {
407 mCurrentUpload.cancel();
408 }
409 }
410 // Cancel pending uploads
411 cancelUploadsForAccount(account);
412 }
413
414 public void clearListeners() {
415 mBoundListeners.clear();
416 }
417
418
419 /**
420 * Returns True when the file described by 'file' is being uploaded to
421 * the ownCloud account 'account' or waiting for it
422 *
423 * If 'file' is a directory, returns 'true' if some of its descendant files
424 * is uploading or waiting to upload.
425 *
426 * @param account ownCloud account where the remote file will be stored.
427 * @param file A file that could be in the queue of pending uploads
428 */
429 public boolean isUploading(Account account, OCFile file) {
430 if (account == null || file == null) return false;
431 return (mPendingUploads.contains(account, file.getRemotePath()));
432 }
433
434
435 /**
436 * Adds a listener interested in the progress of the upload for a concrete file.
437 *
438 * @param listener Object to notify about progress of transfer.
439 * @param account ownCloud account holding the file of interest.
440 * @param file {@link OCFile} of interest for listener.
441 */
442 public void addDatatransferProgressListener (OnDatatransferProgressListener listener,
443 Account account, OCFile file) {
444 if (account == null || file == null || listener == null) return;
445 String targetKey = buildRemoteName(account, file);
446 mBoundListeners.put(targetKey, listener);
447 }
448
449
450
451 /**
452 * Removes a listener interested in the progress of the upload for a concrete file.
453 *
454 * @param listener Object to notify about progress of transfer.
455 * @param account ownCloud account holding the file of interest.
456 * @param file {@link OCFile} of interest for listener.
457 */
458 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener,
459 Account account, OCFile file) {
460 if (account == null || file == null || listener == null) return;
461 String targetKey = buildRemoteName(account, file);
462 if (mBoundListeners.get(targetKey) == listener) {
463 mBoundListeners.remove(targetKey);
464 }
465 }
466
467
468 @Override
469 public void onTransferProgress(long progressRate, long totalTransferredSoFar,
470 long totalToTransfer, String fileName) {
471 String key = buildRemoteName(mCurrentUpload.getAccount(), mCurrentUpload.getFile());
472 OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
473 if (boundListener != null) {
474 boundListener.onTransferProgress(progressRate, totalTransferredSoFar,
475 totalToTransfer, fileName);
476 }
477 }
478
479 /**
480 * Builds a key for the map of listeners.
481 *
482 * TODO remove and replace key with file.getFileId() after changing current policy (upload file, then
483 * add to local database) to better policy (add to local database, then upload)
484 *
485 * @param account ownCloud account where the file to upload belongs.
486 * @param file File to upload
487 * @return Key
488 */
489 private String buildRemoteName(Account account, OCFile file) {
490 return account.name + file.getRemotePath();
491 }
492
493 }
494
495 /**
496 * Upload worker. Performs the pending uploads in the order they were
497 * requested.
498 *
499 * Created with the Looper of a new thread, started in
500 * {@link FileUploader#onCreate()}.
501 */
502 private static class ServiceHandler extends Handler {
503 // don't make it a final class, and don't remove the static ; lint will
504 // warn about a possible memory leak
505 FileUploader mService;
506
507 public ServiceHandler(Looper looper, FileUploader service) {
508 super(looper);
509 if (service == null)
510 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
511 mService = service;
512 }
513
514 @Override
515 public void handleMessage(Message msg) {
516 @SuppressWarnings("unchecked")
517 AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
518 if (msg.obj != null) {
519 Iterator<String> it = requestedUploads.iterator();
520 while (it.hasNext()) {
521 mService.uploadFile(it.next());
522 }
523 }
524 Log_OC.d(TAG, "Stopping command after id " + msg.arg1);
525 mService.stopSelf(msg.arg1);
526 }
527 }
528
529 /**
530 * Core upload method: sends the file(s) to upload
531 *
532 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
533 */
534 public void uploadFile(String uploadKey) {
535
536 mCurrentUpload = mPendingUploads.get(uploadKey);
537
538 if (mCurrentUpload != null) {
539 // Detect if the account exists
540 if (AccountUtils.exists(mCurrentUpload.getAccount(), getApplicationContext())) {
541 Log_OC.d(TAG, "Account " + mCurrentUpload.getAccount().name + " exists");
542
543 notifyUploadStart(mCurrentUpload);
544
545 RemoteOperationResult uploadResult = null, grantResult;
546
547 try {
548 /// prepare client object to send the request to the ownCloud server
549 if (mCurrentAccount == null || !mCurrentAccount.equals(mCurrentUpload.getAccount())) {
550 mCurrentAccount = mCurrentUpload.getAccount();
551 mStorageManager = new FileDataStorageManager(
552 mCurrentAccount,
553 getContentResolver()
554 );
555 } // else, reuse storage manager from previous operation
556
557 // always get client from client manager, to get fresh credentials in case of update
558 OwnCloudAccount ocAccount = new OwnCloudAccount(mCurrentAccount, this);
559 mUploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().
560 getClientFor(ocAccount, this);
561
562
563 /// check the existence of the parent folder for the file to upload
564 String remoteParentPath = new File(mCurrentUpload.getRemotePath()).getParent();
565 remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ?
566 remoteParentPath : remoteParentPath + OCFile.PATH_SEPARATOR;
567 grantResult = grantFolderExistence(remoteParentPath);
568
569 /// perform the upload
570 if (grantResult.isSuccess()) {
571 OCFile parent = mStorageManager.getFileByPath(remoteParentPath);
572 mCurrentUpload.getFile().setParentId(parent.getFileId());
573 uploadResult = mCurrentUpload.execute(mUploadClient);
574 if (uploadResult.isSuccess()) {
575 saveUploadedFile();
576
577 } else if (uploadResult.getCode() == ResultCode.SYNC_CONFLICT) {
578 mStorageManager.saveConflict(mCurrentUpload.getFile(),
579 mCurrentUpload.getFile().getEtagInConflict());
580 }
581 } else {
582 uploadResult = grantResult;
583 }
584
585 } catch (Exception e) {
586 Log_OC.e(TAG, "Error uploading", e);
587 uploadResult = new RemoteOperationResult(e);
588
589 } finally {
590 Pair<UploadFileOperation, String> removeResult;
591 if (mCurrentUpload.wasRenamed()) {
592 removeResult = mPendingUploads.removePayload(
593 mCurrentAccount,
594 mCurrentUpload.getOldFile().getRemotePath()
595 );
596 } else {
597 removeResult = mPendingUploads.removePayload(
598 mCurrentAccount,
599 mCurrentUpload.getRemotePath()
600 );
601 }
602
603 /// notify result
604 notifyUploadResult(mCurrentUpload, uploadResult);
605
606 sendBroadcastUploadFinished(mCurrentUpload, uploadResult, removeResult.second);
607 }
608
609 } else {
610 // Cancel the transfer
611 Log_OC.d(TAG, "Account " + mCurrentUpload.getAccount().toString() +
612 " doesn't exist");
613 cancelUploadsForAccount(mCurrentUpload.getAccount());
614
615 }
616 }
617
618 }
619
620 /**
621 * Checks the existence of the folder where the current file will be uploaded both
622 * in the remote server and in the local database.
623 *
624 * If the upload is set to enforce the creation of the folder, the method tries to
625 * create it both remote and locally.
626 *
627 * @param pathToGrant Full remote path whose existence will be granted.
628 * @return An {@link OCFile} instance corresponding to the folder where the file
629 * will be uploaded.
630 */
631 private RemoteOperationResult grantFolderExistence(String pathToGrant) {
632 RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, this, false);
633 RemoteOperationResult result = operation.execute(mUploadClient);
634 if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND &&
635 mCurrentUpload.isRemoteFolderToBeCreated()) {
636 SyncOperation syncOp = new CreateFolderOperation( pathToGrant, true);
637 result = syncOp.execute(mUploadClient, mStorageManager);
638 }
639 if (result.isSuccess()) {
640 OCFile parentDir = mStorageManager.getFileByPath(pathToGrant);
641 if (parentDir == null) {
642 parentDir = createLocalFolder(pathToGrant);
643 }
644 if (parentDir != null) {
645 result = new RemoteOperationResult(ResultCode.OK);
646 } else {
647 result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
648 }
649 }
650 return result;
651 }
652
653
654 private OCFile createLocalFolder(String remotePath) {
655 String parentPath = new File(remotePath).getParent();
656 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ?
657 parentPath : parentPath + OCFile.PATH_SEPARATOR;
658 OCFile parent = mStorageManager.getFileByPath(parentPath);
659 if (parent == null) {
660 parent = createLocalFolder(parentPath);
661 }
662 if (parent != null) {
663 OCFile createdFolder = new OCFile(remotePath);
664 createdFolder.setMimetype("DIR");
665 createdFolder.setParentId(parent.getFileId());
666 mStorageManager.saveFile(createdFolder);
667 return createdFolder;
668 }
669 return null;
670 }
671
672
673 /**
674 * Saves a OC File after a successful upload.
675 *
676 * A PROPFIND is necessary to keep the props in the local database
677 * synchronized with the server, specially the modification time and Etag
678 * (where available)
679 *
680 * TODO move into UploadFileOperation
681 */
682 private void saveUploadedFile() {
683 OCFile file = mCurrentUpload.getFile();
684 if (file.fileExists()) {
685 file = mStorageManager.getFileById(file.getFileId());
686 }
687 long syncDate = System.currentTimeMillis();
688 file.setLastSyncDateForData(syncDate);
689
690 // new PROPFIND to keep data consistent with server
691 // in theory, should return the same we already have
692 ReadRemoteFileOperation operation =
693 new ReadRemoteFileOperation(mCurrentUpload.getRemotePath());
694 RemoteOperationResult result = operation.execute(mUploadClient);
695 if (result.isSuccess()) {
696 updateOCFile(file, (RemoteFile) result.getData().get(0));
697 file.setLastSyncDateForProperties(syncDate);
698 } else {
699 Log_OC.e(TAG, "Error reading properties of file after successful upload; this is gonna hurt...");
700 }
701
702 // / maybe this would be better as part of UploadFileOperation... or
703 // maybe all this method
704 if (mCurrentUpload.wasRenamed()) {
705 OCFile oldFile = mCurrentUpload.getOldFile();
706 if (oldFile.fileExists()) {
707 oldFile.setStoragePath(null);
708 mStorageManager.saveFile(oldFile);
709 mStorageManager.saveConflict(oldFile, null);
710
711 } // else: it was just an automatic renaming due to a name
712 // coincidence; nothing else is needed, the storagePath is right
713 // in the instance returned by mCurrentUpload.getFile()
714 }
715 file.setNeedsUpdateThumbnail(true);
716 mStorageManager.saveFile(file);
717 mStorageManager.saveConflict(file, null);
718
719 mStorageManager.triggerMediaScan(file.getStoragePath());
720
721 }
722
723 private void updateOCFile(OCFile file, RemoteFile remoteFile) {
724 file.setCreationTimestamp(remoteFile.getCreationTimestamp());
725 file.setFileLength(remoteFile.getLength());
726 file.setMimetype(remoteFile.getMimeType());
727 file.setModificationTimestamp(remoteFile.getModifiedTimestamp());
728 file.setModificationTimestampAtLastSyncForData(remoteFile.getModifiedTimestamp());
729 file.setEtag(remoteFile.getEtag());
730 file.setRemoteId(remoteFile.getRemoteId());
731 }
732
733 private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType) {
734
735 // MIME type
736 if (mimeType == null || mimeType.length() <= 0) {
737 try {
738 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
739 remotePath.substring(remotePath.lastIndexOf('.') + 1));
740 } catch (IndexOutOfBoundsException e) {
741 Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " +
742 remotePath);
743 }
744 }
745 if (mimeType == null) {
746 mimeType = "application/octet-stream";
747 }
748
749 if (isPdfFileFromContentProviderWithoutExtension(localPath, mimeType)){
750 remotePath += FILE_EXTENSION_PDF;
751 }
752
753 OCFile newFile = new OCFile(remotePath);
754 newFile.setStoragePath(localPath);
755 newFile.setLastSyncDateForProperties(0);
756 newFile.setLastSyncDateForData(0);
757
758 // size
759 if (localPath != null && localPath.length() > 0) {
760 File localFile = new File(localPath);
761 newFile.setFileLength(localFile.length());
762 newFile.setLastSyncDateForData(localFile.lastModified());
763 } // don't worry about not assigning size, the problems with localPath
764 // are checked when the UploadFileOperation instance is created
765
766
767 newFile.setMimetype(mimeType);
768
769 return newFile;
770 }
771
772 /**
773 * Creates a status notification to show the upload progress
774 *
775 * @param upload Upload operation starting.
776 */
777 private void notifyUploadStart(UploadFileOperation upload) {
778 // / create status notification with a progress bar
779 mLastPercent = 0;
780 mNotificationBuilder =
781 NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
782 mNotificationBuilder
783 .setOngoing(true)
784 .setSmallIcon(R.drawable.notification_icon)
785 .setTicker(getString(R.string.uploader_upload_in_progress_ticker))
786 .setContentTitle(getString(R.string.uploader_upload_in_progress_ticker))
787 .setProgress(100, 0, false)
788 .setContentText(
789 String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
790
791 /// includes a pending intent in the notification showing the details view of the file
792 Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
793 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
794 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
795 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
796 mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
797 this, (int) System.currentTimeMillis(), showDetailsIntent, 0
798 ));
799
800 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
801 }
802
803 /**
804 * Callback method to update the progress bar in the status notification
805 */
806 @Override
807 public void onTransferProgress(long progressRate, long totalTransferredSoFar,
808 long totalToTransfer, String filePath) {
809 int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
810 if (percent != mLastPercent) {
811 mNotificationBuilder.setProgress(100, percent, false);
812 String fileName = filePath.substring(
813 filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
814 String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
815 mNotificationBuilder.setContentText(text);
816 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
817 }
818 mLastPercent = percent;
819 }
820
821 /**
822 * Updates the status notification with the result of an upload operation.
823 *
824 * @param uploadResult Result of the upload operation.
825 * @param upload Finished upload operation
826 */
827 private void notifyUploadResult(UploadFileOperation upload,
828 RemoteOperationResult uploadResult) {
829 Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
830 // / cancelled operation or success -> silent removal of progress notification
831 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
832
833 // Show the result: success or fail notification
834 if (!uploadResult.isCancelled()) {
835 int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker :
836 R.string.uploader_upload_failed_ticker;
837
838 String content;
839
840 // check credentials error
841 boolean needsToUpdateCredentials = (
842 uploadResult.getCode() == ResultCode.UNAUTHORIZED ||
843 uploadResult.isIdPRedirection()
844 );
845 tickerId = (needsToUpdateCredentials) ?
846 R.string.uploader_upload_failed_credentials_error : tickerId;
847
848 mNotificationBuilder
849 .setTicker(getString(tickerId))
850 .setContentTitle(getString(tickerId))
851 .setAutoCancel(true)
852 .setOngoing(false)
853 .setProgress(0, 0, false);
854
855 content = ErrorMessageAdapter.getErrorCauseMessage(
856 uploadResult, upload, getResources()
857 );
858
859 if (needsToUpdateCredentials) {
860 // let the user update credentials with one click
861 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
862 updateAccountCredentials.putExtra(
863 AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount()
864 );
865 updateAccountCredentials.putExtra(
866 AuthenticatorActivity.EXTRA_ACTION,
867 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN
868 );
869 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
870 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
871 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
872 mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
873 this,
874 (int) System.currentTimeMillis(),
875 updateAccountCredentials,
876 PendingIntent.FLAG_ONE_SHOT
877 ));
878
879 mUploadClient = null;
880 // grant that future retries on the same account will get the fresh credentials
881 } else {
882 mNotificationBuilder.setContentText(content);
883
884 if (upload.isInstant()) {
885 DbHandler db = null;
886 try {
887 db = new DbHandler(this.getBaseContext());
888 String message = uploadResult.getLogMessage() + " errorCode: " +
889 uploadResult.getCode();
890 Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
891 if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
892 //message = getString(R.string.failed_upload_quota_exceeded_text);
893 if (db.updateFileState(
894 upload.getOriginalStoragePath(),
895 DbHandler.UPLOAD_STATUS_UPLOAD_FAILED,
896 message) == 0) {
897 db.putFileForLater(
898 upload.getOriginalStoragePath(),
899 upload.getAccount().name,
900 message
901 );
902 }
903 }
904 } finally {
905 if (db != null) {
906 db.close();
907 }
908 }
909 }
910 }
911
912 mNotificationBuilder.setContentText(content);
913 mNotificationManager.notify(tickerId, mNotificationBuilder.build());
914
915 if (uploadResult.isSuccess()) {
916
917 DbHandler db = new DbHandler(this.getBaseContext());
918 db.removeIUPendingFile(mCurrentUpload.getOriginalStoragePath());
919 db.close();
920
921 // remove success notification, with a delay of 2 seconds
922 NotificationDelayer.cancelWithDelay(
923 mNotificationManager,
924 R.string.uploader_upload_succeeded_ticker,
925 2000);
926
927 }
928 }
929 }
930
931 /**
932 * Sends a broadcast in order to the interested activities can update their
933 * view
934 *
935 * @param upload Finished upload operation
936 * @param uploadResult Result of the upload operation
937 * @param unlinkedFromRemotePath Path in the uploads tree where the upload was unlinked from
938 */
939 private void sendBroadcastUploadFinished(
940 UploadFileOperation upload,
941 RemoteOperationResult uploadResult,
942 String unlinkedFromRemotePath) {
943
944 Intent end = new Intent(getUploadFinishMessage());
945 end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
946 // path, after
947 // possible
948 // automatic
949 // renaming
950 if (upload.wasRenamed()) {
951 end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
952 }
953 end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
954 end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
955 end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
956 if (unlinkedFromRemotePath != null) {
957 end.putExtra(EXTRA_LINKED_TO_PATH, unlinkedFromRemotePath);
958 }
959
960 sendStickyBroadcast(end);
961 }
962
963 /**
964 * Checks if content provider, using the content:// scheme, returns a file with mime-type
965 * 'application/pdf' but file has not extension
966 * @param localPath Full path to a file in the local file system.
967 * @param mimeType MIME type of the file.
968 * @return true if is needed to add the pdf file extension to the file
969 *
970 * TODO - move to OCFile or Utils class
971 */
972 private boolean isPdfFileFromContentProviderWithoutExtension(String localPath,
973 String mimeType) {
974 return localPath.startsWith(UriUtils.URI_CONTENT_SCHEME) &&
975 mimeType.equals(MIME_TYPE_PDF) &&
976 !localPath.endsWith(FILE_EXTENSION_PDF);
977 }
978
979 /**
980 * Remove uploads of an account
981 *
982 * @param account Downloads account to remove
983 */
984 private void cancelUploadsForAccount(Account account){
985 // Cancel pending uploads
986 mPendingUploads.remove(account);
987 }
988 }