Fixed undesired restart of finished audio previews when the device orientation changes
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileUploader.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.files.services;
20
21 import java.io.File;
22 import java.util.AbstractList;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.Map;
26 import java.util.Vector;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
29
30 import org.apache.http.HttpStatus;
31 import org.apache.jackrabbit.webdav.MultiStatus;
32 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
33
34 import com.owncloud.android.authenticator.AccountAuthenticator;
35 import com.owncloud.android.datamodel.FileDataStorageManager;
36 import com.owncloud.android.datamodel.OCFile;
37 import com.owncloud.android.files.InstantUploadBroadcastReceiver;
38 import com.owncloud.android.operations.ChunkedUploadFileOperation;
39 import com.owncloud.android.operations.RemoteOperationResult;
40 import com.owncloud.android.operations.UploadFileOperation;
41 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
42 import com.owncloud.android.ui.activity.FileDetailActivity;
43 import com.owncloud.android.ui.fragment.FileDetailFragment;
44 import com.owncloud.android.ui.preview.PreviewImageActivity;
45 import com.owncloud.android.ui.preview.PreviewImageFragment;
46 import com.owncloud.android.utils.OwnCloudVersion;
47
48 import eu.alefzero.webdav.OnDatatransferProgressListener;
49 import eu.alefzero.webdav.WebdavEntry;
50 import eu.alefzero.webdav.WebdavUtils;
51
52 import com.owncloud.android.network.OwnCloudClientUtils;
53
54 import android.accounts.Account;
55 import android.accounts.AccountManager;
56 import android.app.Notification;
57 import android.app.NotificationManager;
58 import android.app.PendingIntent;
59 import android.app.Service;
60 import android.content.Intent;
61 import android.os.Binder;
62 import android.os.Handler;
63 import android.os.HandlerThread;
64 import android.os.IBinder;
65 import android.os.Looper;
66 import android.os.Message;
67 import android.os.Process;
68 import android.util.Log;
69 import android.webkit.MimeTypeMap;
70 import android.widget.RemoteViews;
71
72 import com.owncloud.android.R;
73 import eu.alefzero.webdav.WebdavClient;
74
75 public class FileUploader extends Service implements OnDatatransferProgressListener {
76
77 public static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
78 public static final String EXTRA_UPLOAD_RESULT = "RESULT";
79 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
80 public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
81 public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
82 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
83
84 public static final String KEY_FILE = "FILE";
85 public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
86 public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
87 public static final String KEY_MIME_TYPE = "MIME_TYPE";
88
89 public static final String KEY_ACCOUNT = "ACCOUNT";
90
91 public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
92 public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
93 public static final String KEY_INSTANT_UPLOAD = "INSTANT_UPLOAD";
94 public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
95
96 public static final int LOCAL_BEHAVIOUR_COPY = 0;
97 public static final int LOCAL_BEHAVIOUR_MOVE = 1;
98 public static final int LOCAL_BEHAVIOUR_FORGET = 2;
99
100 public static final int UPLOAD_SINGLE_FILE = 0;
101 public static final int UPLOAD_MULTIPLE_FILES = 1;
102
103 private static final String TAG = FileUploader.class.getSimpleName();
104
105 private Looper mServiceLooper;
106 private ServiceHandler mServiceHandler;
107 private IBinder mBinder;
108 private WebdavClient mUploadClient = null;
109 private Account mLastAccount = null;
110 private FileDataStorageManager mStorageManager;
111
112 private ConcurrentMap<String, UploadFileOperation> mPendingUploads = new ConcurrentHashMap<String, UploadFileOperation>();
113 private UploadFileOperation mCurrentUpload = null;
114
115 private NotificationManager mNotificationManager;
116 private Notification mNotification;
117 private int mLastPercent;
118 private RemoteViews mDefaultNotificationContentView;
119
120
121 /**
122 * Builds a key for mPendingUploads from the account and file to upload
123 *
124 * @param account Account where the file to upload is stored
125 * @param file File to upload
126 */
127 private String buildRemoteName(Account account, OCFile file) {
128 return account.name + file.getRemotePath();
129 }
130
131 private String buildRemoteName(Account account, String remotePath) {
132 return account.name + remotePath;
133 }
134
135
136 /**
137 * Checks if an ownCloud server version should support chunked uploads.
138 *
139 * @param version OwnCloud version instance corresponding to an ownCloud server.
140 * @return 'True' if the ownCloud server with version supports chunked uploads.
141 */
142 private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
143 return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
144 }
145
146
147
148 /**
149 * Service initialization
150 */
151 @Override
152 public void onCreate() {
153 super.onCreate();
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
163
164 /**
165 * Entry point to add one or several files to the queue of uploads.
166 *
167 * New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
168 * although the caller activity goes away.
169 */
170 @Override
171 public int onStartCommand(Intent intent, int flags, int startId) {
172 if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE) || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
173 Log.e(TAG, "Not enough information provided in intent");
174 return Service.START_NOT_STICKY;
175 }
176 int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
177 if (uploadType == -1) {
178 Log.e(TAG, "Incorrect upload type provided");
179 return Service.START_NOT_STICKY;
180 }
181 Account account = intent.getParcelableExtra(KEY_ACCOUNT);
182
183 String[] localPaths = null, remotePaths = null, mimeTypes = null;
184 OCFile[] files = null;
185 if (uploadType == UPLOAD_SINGLE_FILE) {
186
187 if (intent.hasExtra(KEY_FILE)) {
188 files = new OCFile[] {intent.getParcelableExtra(KEY_FILE) };
189
190 } else {
191 localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
192 remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
193 mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
194 }
195
196 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
197
198 if (intent.hasExtra(KEY_FILE)) {
199 files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO will this casting work fine?
200
201 } else {
202 localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
203 remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
204 mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
205 }
206 }
207
208 FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
209
210 boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
211 boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
212 int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_COPY);
213 boolean fixed = false;
214 if (isInstant) {
215 fixed = checkAndFixInstantUploadDirectory(storageManager); // MUST be done BEFORE calling obtainNewOCFileToUpload
216 }
217
218 if (intent.hasExtra(KEY_FILE) && files == null) {
219 Log.e(TAG, "Incorrect array for OCFiles provided in upload intent");
220 return Service.START_NOT_STICKY;
221
222 } else if (!intent.hasExtra(KEY_FILE)) {
223 if (localPaths == null) {
224 Log.e(TAG, "Incorrect array for local paths provided in upload intent");
225 return Service.START_NOT_STICKY;
226 }
227 if (remotePaths == null) {
228 Log.e(TAG, "Incorrect array for remote paths provided in upload intent");
229 return Service.START_NOT_STICKY;
230 }
231 if (localPaths.length != remotePaths.length) {
232 Log.e(TAG, "Different number of remote paths and local paths!");
233 return Service.START_NOT_STICKY;
234 }
235
236 files = new OCFile[localPaths.length];
237 for (int i=0; i < localPaths.length; i++) {
238 files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes!=null)?mimeTypes[i]:(String)null), storageManager);
239 }
240 }
241
242 OwnCloudVersion ocv = new OwnCloudVersion(AccountManager.get(this).getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
243 boolean chunked = FileUploader.chunkedUploadIsSupported(ocv);
244 AbstractList<String> requestedUploads = new Vector<String>();
245 String uploadKey = null;
246 UploadFileOperation newUpload = null;
247 try {
248 for (int i=0; i < files.length; i++) {
249 uploadKey = buildRemoteName(account, files[i].getRemotePath());
250 if (chunked) {
251 newUpload = new ChunkedUploadFileOperation(account, files[i], isInstant, forceOverwrite, localAction);
252 } else {
253 newUpload = new UploadFileOperation(account, files[i], isInstant, forceOverwrite, localAction);
254 }
255 if (fixed && i==0) {
256 newUpload.setRemoteFolderToBeCreated();
257 }
258 mPendingUploads.putIfAbsent(uploadKey, newUpload);
259 newUpload.addDatatransferProgressListener(this);
260 newUpload.addDatatransferProgressListener((FileUploaderBinder)mBinder);
261 requestedUploads.add(uploadKey);
262 }
263
264 } catch (IllegalArgumentException e) {
265 Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
266 return START_NOT_STICKY;
267
268 } catch (IllegalStateException e) {
269 Log.e(TAG, "Bad information provided in intent: " + e.getMessage());
270 return START_NOT_STICKY;
271
272 } catch (Exception e) {
273 Log.e(TAG, "Unexpected exception while processing upload intent", e);
274 return START_NOT_STICKY;
275
276 }
277
278 if (requestedUploads.size() > 0) {
279 Message msg = mServiceHandler.obtainMessage();
280 msg.arg1 = startId;
281 msg.obj = requestedUploads;
282 mServiceHandler.sendMessage(msg);
283 }
284
285 return Service.START_NOT_STICKY;
286 }
287
288
289 /**
290 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
291 *
292 * Implemented to perform cancellation, pause and resume of existing uploads.
293 */
294 @Override
295 public IBinder onBind(Intent arg0) {
296 return mBinder;
297 }
298
299 /**
300 * Called when ALL the bound clients were onbound.
301 */
302 @Override
303 public boolean onUnbind(Intent intent) {
304 ((FileUploaderBinder)mBinder).clearListeners();
305 return false; // not accepting rebinding (default behaviour)
306 }
307
308
309 /**
310 * Binder to let client components to perform operations on the queue of uploads.
311 *
312 * It provides by itself the available operations.
313 */
314 public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
315
316 /**
317 * Map of listeners that will be reported about progress of uploads from a {@link FileUploaderBinder} instance
318 */
319 private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
320
321 /**
322 * Cancels a pending or current upload of a remote file.
323 *
324 * @param account Owncloud account where the remote file will be stored.
325 * @param file A file in the queue of pending uploads
326 */
327 public void cancel(Account account, OCFile file) {
328 UploadFileOperation upload = null;
329 synchronized (mPendingUploads) {
330 upload = mPendingUploads.remove(buildRemoteName(account, file));
331 }
332 if (upload != null) {
333 upload.cancel();
334 }
335 }
336
337
338
339 public void clearListeners() {
340 mBoundListeners.clear();
341 }
342
343
344
345
346 /**
347 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
348 *
349 * If 'file' is a directory, returns 'true' if some of its descendant files is uploading or waiting to upload.
350 *
351 * @param account Owncloud account where the remote file will be stored.
352 * @param file A file that could be in the queue of pending uploads
353 */
354 public boolean isUploading(Account account, OCFile file) {
355 if (account == null || file == null) return false;
356 String targetKey = buildRemoteName(account, file);
357 synchronized (mPendingUploads) {
358 if (file.isDirectory()) {
359 // this can be slow if there are many uploads :(
360 Iterator<String> it = mPendingUploads.keySet().iterator();
361 boolean found = false;
362 while (it.hasNext() && !found) {
363 found = it.next().startsWith(targetKey);
364 }
365 return found;
366 } else {
367 return (mPendingUploads.containsKey(targetKey));
368 }
369 }
370 }
371
372
373 /**
374 * Adds a listener interested in the progress of the upload for a concrete file.
375 *
376 * @param listener Object to notify about progress of transfer.
377 * @param account ownCloud account holding the file of interest.
378 * @param file {@link OCfile} of interest for listener.
379 */
380 public void addDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
381 if (account == null || file == null || listener == null) return;
382 String targetKey = buildRemoteName(account, file);
383 mBoundListeners.put(targetKey, listener);
384 }
385
386
387
388 /**
389 * Removes a listener interested in the progress of the upload for a concrete file.
390 *
391 * @param listener Object to notify about progress of transfer.
392 * @param account ownCloud account holding the file of interest.
393 * @param file {@link OCfile} of interest for listener.
394 */
395 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener, Account account, OCFile file) {
396 if (account == null || file == null || listener == null) return;
397 String targetKey = buildRemoteName(account, file);
398 if (mBoundListeners.get(targetKey) == listener) {
399 mBoundListeners.remove(targetKey);
400 }
401 }
402
403
404 @Override
405 public void onTransferProgress(long progressRate) {
406 // old way, should not be in use any more
407 }
408
409
410 @Override
411 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
412 String fileName) {
413 String key = buildRemoteName(mCurrentUpload.getAccount(), mCurrentUpload.getFile());
414 OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
415 if (boundListener != null) {
416 boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, fileName);
417 }
418 }
419
420 }
421
422
423
424
425 /**
426 * Upload worker. Performs the pending uploads in the order they were requested.
427 *
428 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
429 */
430 private static class ServiceHandler extends Handler {
431 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
432 FileUploader mService;
433 public ServiceHandler(Looper looper, FileUploader service) {
434 super(looper);
435 if (service == null)
436 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
437 mService = service;
438 }
439
440 @Override
441 public void handleMessage(Message msg) {
442 @SuppressWarnings("unchecked")
443 AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
444 if (msg.obj != null) {
445 Iterator<String> it = requestedUploads.iterator();
446 while (it.hasNext()) {
447 mService.uploadFile(it.next());
448 }
449 }
450 mService.stopSelf(msg.arg1);
451 }
452 }
453
454
455
456
457 /**
458 * Core upload method: sends the file(s) to upload
459 *
460 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
461 */
462 public void uploadFile(String uploadKey) {
463
464 synchronized(mPendingUploads) {
465 mCurrentUpload = mPendingUploads.get(uploadKey);
466 }
467
468 if (mCurrentUpload != null) {
469
470 notifyUploadStart(mCurrentUpload);
471
472
473 /// prepare client object to send requests to the ownCloud server
474 if (mUploadClient == null || !mLastAccount.equals(mCurrentUpload.getAccount())) {
475 mLastAccount = mCurrentUpload.getAccount();
476 mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
477 mUploadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
478 }
479
480 /// create remote folder for instant uploads
481 if (mCurrentUpload.isRemoteFolderToBeCreated()) {
482 mUploadClient.createDirectory(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR); // ignoring result; fail could just mean that it already exists, but local database is not synchronized; the upload will be tried anyway
483 }
484
485
486 /// perform the upload
487 RemoteOperationResult uploadResult = null;
488 try {
489 uploadResult = mCurrentUpload.execute(mUploadClient);
490 if (uploadResult.isSuccess()) {
491 saveUploadedFile();
492 }
493
494 } finally {
495 synchronized(mPendingUploads) {
496 mPendingUploads.remove(uploadKey);
497 }
498 }
499
500 /// notify result
501 notifyUploadResult(uploadResult, mCurrentUpload);
502
503 sendFinalBroadcast(mCurrentUpload, uploadResult);
504
505 }
506
507 }
508
509 /**
510 * Saves a OC File after a successful upload.
511 *
512 * A PROPFIND is necessary to keep the props in the local database synchronized with the server,
513 * specially the modification time and Etag (where available)
514 *
515 * TODO refactor this ugly thing
516 */
517 private void saveUploadedFile() {
518 OCFile file = mCurrentUpload.getFile();
519 long syncDate = System.currentTimeMillis();
520 file.setLastSyncDateForData(syncDate);
521
522 /// new PROPFIND to keep data consistent with server in theory, should return the same we already have
523 PropFindMethod propfind = null;
524 RemoteOperationResult result = null;
525 try {
526 propfind = new PropFindMethod(mUploadClient.getBaseUri() + WebdavUtils.encodePath(mCurrentUpload.getRemotePath()));
527 int status = mUploadClient.executeMethod(propfind);
528 boolean isMultiStatus = (status == HttpStatus.SC_MULTI_STATUS);
529 if (isMultiStatus) {
530 MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
531 WebdavEntry we = new WebdavEntry(resp.getResponses()[0],
532 mUploadClient.getBaseUri().getPath());
533 updateOCFile(file, we);
534 file.setLastSyncDateForProperties(syncDate);
535
536 } else {
537 mUploadClient.exhaustResponse(propfind.getResponseBodyAsStream());
538 }
539
540 result = new RemoteOperationResult(isMultiStatus, status);
541 Log.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": " + result.getLogMessage());
542
543 } catch (Exception e) {
544 result = new RemoteOperationResult(e);
545 Log.e(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": " + result.getLogMessage(), e);
546
547 } finally {
548 if (propfind != null)
549 propfind.releaseConnection();
550 }
551
552 /// maybe this would be better as part of UploadFileOperation... or maybe all this method
553 if (mCurrentUpload.wasRenamed()) {
554 OCFile oldFile = mCurrentUpload.getOldFile();
555 if (oldFile.fileExists()) {
556 oldFile.setStoragePath(null);
557 mStorageManager.saveFile(oldFile);
558
559 } // else: it was just an automatic renaming due to a name coincidence; nothing else is needed, the storagePath is right in the instance returned by mCurrentUpload.getFile()
560 }
561
562 mStorageManager.saveFile(file);
563 }
564
565
566 private void updateOCFile(OCFile file, WebdavEntry we) {
567 file.setCreationTimestamp(we.createTimestamp());
568 file.setFileLength(we.contentLength());
569 file.setMimetype(we.contentType());
570 file.setModificationTimestamp(we.modifiedTimestamp());
571 file.setModificationTimestampAtLastSyncForData(we.modifiedTimestamp());
572 // file.setEtag(mCurrentUpload.getEtag()); // TODO Etag, where available
573 }
574
575
576 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager) {
577 OCFile instantUploadDir = storageManager.getFileByPath(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
578 if (instantUploadDir == null) {
579 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
580 OCFile newDir = new OCFile(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
581 newDir.setMimetype("DIR");
582 newDir.setParentId(storageManager.getFileByPath(OCFile.PATH_SEPARATOR).getFileId());
583 storageManager.saveFile(newDir);
584 return true;
585 }
586 return false;
587 }
588
589
590 private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType, FileDataStorageManager storageManager) {
591 OCFile newFile = new OCFile(remotePath);
592 newFile.setStoragePath(localPath);
593 newFile.setLastSyncDateForProperties(0);
594 newFile.setLastSyncDateForData(0);
595
596 // size
597 if (localPath != null && localPath.length() > 0) {
598 File localFile = new File(localPath);
599 newFile.setFileLength(localFile.length());
600 newFile.setLastSyncDateForData(localFile.lastModified());
601 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
602
603 // MIME type
604 if (mimeType == null || mimeType.length() <= 0) {
605 try {
606 mimeType = MimeTypeMap.getSingleton()
607 .getMimeTypeFromExtension(
608 remotePath.substring(remotePath.lastIndexOf('.') + 1));
609 } catch (IndexOutOfBoundsException e) {
610 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
611 }
612 }
613 if (mimeType == null) {
614 mimeType = "application/octet-stream";
615 }
616 newFile.setMimetype(mimeType);
617
618 // parent dir
619 String parentPath = new File(remotePath).getParent();
620 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR ;
621 OCFile parentDir = storageManager.getFileByPath(parentPath);
622 if (parentDir == null) {
623 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath);
624 }
625 long parentDirId = parentDir.getFileId();
626 newFile.setParentId(parentDirId);
627 return newFile;
628 }
629
630
631 /**
632 * Creates a status notification to show the upload progress
633 *
634 * @param upload Upload operation starting.
635 */
636 @SuppressWarnings("deprecation")
637 private void notifyUploadStart(UploadFileOperation upload) {
638 /// create status notification with a progress bar
639 mLastPercent = 0;
640 mNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_in_progress_ticker), System.currentTimeMillis());
641 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
642 mDefaultNotificationContentView = mNotification.contentView;
643 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
644 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
645 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
646 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
647
648 /// includes a pending intent in the notification showing the details view of the file
649 Intent showDetailsIntent = null;
650 if (PreviewImageFragment.canBePreviewed(upload.getFile())) {
651 showDetailsIntent = new Intent(this, PreviewImageActivity.class);
652 } else {
653 showDetailsIntent = new Intent(this, FileDetailActivity.class);
654 showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
655 }
656 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
657 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
658 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
659 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
660
661 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
662 }
663
664
665 /**
666 * Callback method to update the progress bar in the status notification
667 */
668 @Override
669 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
670 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
671 if (percent != mLastPercent) {
672 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
673 String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
674 mNotification.contentView.setTextViewText(R.id.status_text, text);
675 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
676 }
677 mLastPercent = percent;
678 }
679
680
681 /**
682 * Callback method to update the progress bar in the status notification (old version)
683 */
684 @Override
685 public void onTransferProgress(long progressRate) {
686 // NOTHING TO DO HERE ANYMORE
687 }
688
689
690 /**
691 * Updates the status notification with the result of an upload operation.
692 *
693 * @param uploadResult Result of the upload operation.
694 * @param upload Finished upload operation
695 */
696 private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
697 if (uploadResult.isCancelled()) {
698 /// cancelled operation -> silent removal of progress notification
699 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
700
701 } else if (uploadResult.isSuccess()) {
702 /// success -> silent update of progress notification to success message
703 mNotification.flags ^= Notification.FLAG_ONGOING_EVENT; // remove the ongoing flag
704 mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
705 mNotification.contentView = mDefaultNotificationContentView;
706
707 /// includes a pending intent in the notification showing the details view of the file
708 Intent showDetailsIntent = null;
709 if (PreviewImageFragment.canBePreviewed(upload.getFile())) {
710 showDetailsIntent = new Intent(this, PreviewImageActivity.class);
711 } else {
712 showDetailsIntent = new Intent(this, FileDetailActivity.class);
713 showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
714 }
715 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
716 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
717 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
718 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
719
720 mNotification.setLatestEventInfo( getApplicationContext(),
721 getString(R.string.uploader_upload_succeeded_ticker),
722 String.format(getString(R.string.uploader_upload_succeeded_content_single), upload.getFileName()),
723 mNotification.contentIntent);
724
725 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification); // NOT AN ERROR; uploader_upload_in_progress_ticker is the target, not a new notification
726
727 /* Notification about multiple uploads: pending of update
728 mNotification.setLatestEventInfo( getApplicationContext(),
729 getString(R.string.uploader_upload_succeeded_ticker),
730 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
731 mNotification.contentIntent);
732 */
733
734 } else {
735 /// fail -> explicit failure notification
736 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
737 Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
738 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
739 // TODO put something smart in the contentIntent below
740 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
741
742 String content = null;
743 if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL ||
744 uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
745 // TODO we need a class to provide error messages for the users from a RemoteOperationResult and a RemoteOperation
746 content = String.format(getString(R.string.error__upload__local_file_not_copied), upload.getFileName(), getString(R.string.app_name));
747 } else {
748 content = String.format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
749 }
750 finalNotification.setLatestEventInfo( getApplicationContext(),
751 getString(R.string.uploader_upload_failed_ticker),
752 content,
753 finalNotification.contentIntent);
754
755 mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
756
757 /* Notification about multiple uploads failure: pending of update
758 finalNotification.setLatestEventInfo( getApplicationContext(),
759 getString(R.string.uploader_upload_failed_ticker),
760 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
761 finalNotification.contentIntent);
762 } */
763 }
764
765 }
766
767
768 /**
769 * Sends a broadcast in order to the interested activities can update their view
770 *
771 * @param upload Finished upload operation
772 * @param uploadResult Result of the upload operation
773 */
774 private void sendFinalBroadcast(UploadFileOperation upload, RemoteOperationResult uploadResult) {
775 Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
776 end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote path, after possible automatic renaming
777 if (upload.wasRenamed()) {
778 end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
779 }
780 end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
781 end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
782 end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
783 sendStickyBroadcast(end);
784 }
785
786
787 }