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