Fixed update of list of files when downloads finish
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / fragment / FileDetailFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 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 package com.owncloud.android.ui.fragment;
19
20 import java.io.File;
21 import java.lang.ref.WeakReference;
22 import java.util.ArrayList;
23 import java.util.List;
24
25 import org.apache.commons.httpclient.methods.GetMethod;
26 import org.apache.commons.httpclient.methods.PostMethod;
27 import org.apache.commons.httpclient.methods.StringRequestEntity;
28 import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
29 import org.apache.http.HttpStatus;
30 import org.apache.http.NameValuePair;
31 import org.apache.http.client.utils.URLEncodedUtils;
32 import org.apache.http.message.BasicNameValuePair;
33 import org.apache.http.protocol.HTTP;
34 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
35 import org.json.JSONObject;
36
37 import android.accounts.Account;
38 import android.accounts.AccountManager;
39 import android.app.Activity;
40 import android.content.ActivityNotFoundException;
41 import android.content.BroadcastReceiver;
42 import android.content.ComponentName;
43 import android.content.Context;
44 import android.content.Intent;
45 import android.content.IntentFilter;
46 import android.content.ServiceConnection;
47 import android.net.Uri;
48 import android.os.Bundle;
49 import android.os.Handler;
50 import android.os.IBinder;
51 import android.support.v4.app.FragmentTransaction;
52 import android.util.Log;
53 import android.view.LayoutInflater;
54 import android.view.View;
55 import android.view.View.OnClickListener;
56 import android.view.ViewGroup;
57 import android.webkit.MimeTypeMap;
58 import android.widget.Button;
59 import android.widget.CheckBox;
60 import android.widget.ImageView;
61 import android.widget.MediaController;
62 import android.widget.ProgressBar;
63 import android.widget.TextView;
64 import android.widget.Toast;
65
66 import com.actionbarsherlock.app.SherlockFragment;
67 import com.owncloud.android.AccountUtils;
68 import com.owncloud.android.DisplayUtils;
69 import com.owncloud.android.authenticator.AccountAuthenticator;
70 import com.owncloud.android.datamodel.FileDataStorageManager;
71 import com.owncloud.android.datamodel.OCFile;
72 import com.owncloud.android.files.services.FileDownloader;
73 import com.owncloud.android.files.services.FileObserverService;
74 import com.owncloud.android.files.services.FileUploader;
75 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
76 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
77 import com.owncloud.android.media.MediaService;
78 import com.owncloud.android.media.MediaServiceBinder;
79 import com.owncloud.android.network.OwnCloudClientUtils;
80 import com.owncloud.android.operations.OnRemoteOperationListener;
81 import com.owncloud.android.operations.RemoteOperation;
82 import com.owncloud.android.operations.RemoteOperationResult;
83 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
84 import com.owncloud.android.operations.RemoveFileOperation;
85 import com.owncloud.android.operations.RenameFileOperation;
86 import com.owncloud.android.operations.SynchronizeFileOperation;
87 import com.owncloud.android.ui.activity.ConflictsResolveActivity;
88 import com.owncloud.android.ui.activity.FileDetailActivity;
89 import com.owncloud.android.ui.activity.FileDisplayActivity;
90 import com.owncloud.android.ui.activity.PreviewVideoActivity;
91 import com.owncloud.android.ui.dialog.EditNameDialog;
92 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
93 import com.owncloud.android.utils.OwnCloudVersion;
94
95 import com.owncloud.android.R;
96
97 import eu.alefzero.webdav.OnDatatransferProgressListener;
98 import eu.alefzero.webdav.WebdavClient;
99 import eu.alefzero.webdav.WebdavUtils;
100
101 /**
102 * This Fragment is used to display the details about a file.
103 *
104 * @author Bartek Przybylski
105 * @author David A. Velasco
106 */
107 public class FileDetailFragment extends SherlockFragment implements
108 OnClickListener,
109 ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener, EditNameDialogListener,
110 FileFragment {
111
112 public static final String EXTRA_FILE = "FILE";
113 public static final String EXTRA_ACCOUNT = "ACCOUNT";
114
115 private FileFragment.ContainerActivity mContainerActivity;
116
117 private int mLayout;
118 private View mView;
119 private OCFile mFile;
120 private Account mAccount;
121 private FileDataStorageManager mStorageManager;
122
123 //private DownloadFinishReceiver mDownloadFinishReceiver;
124 private UploadFinishReceiver mUploadFinishReceiver;
125 public ProgressListener mProgressListener;
126
127 private Handler mHandler;
128 private RemoteOperation mLastRemoteOperation;
129
130 private MediaServiceBinder mMediaServiceBinder = null;
131 private MediaController mMediaController = null;
132 private MediaServiceConnection mMediaServiceConnection = null;
133
134 private static final String TAG = FileDetailFragment.class.getSimpleName();
135 public static final String FTAG = "FileDetails";
136 public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
137
138
139 /**
140 * Creates an empty details fragment.
141 *
142 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
143 */
144 public FileDetailFragment() {
145 mFile = null;
146 mAccount = null;
147 mStorageManager = null;
148 mLayout = R.layout.file_details_empty;
149 mProgressListener = null;
150 }
151
152
153 /**
154 * Creates a details fragment.
155 *
156 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
157 *
158 * @param fileToDetail An {@link OCFile} to show in the fragment
159 * @param ocAccount An ownCloud account; needed to start downloads
160 */
161 public FileDetailFragment(OCFile fileToDetail, Account ocAccount) {
162 mFile = fileToDetail;
163 mAccount = ocAccount;
164 mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
165 mLayout = R.layout.file_details_empty;
166 mProgressListener = null;
167 }
168
169
170 @Override
171 public void onCreate(Bundle savedInstanceState) {
172 super.onCreate(savedInstanceState);
173 mHandler = new Handler();
174 }
175
176
177 @Override
178 public View onCreateView(LayoutInflater inflater, ViewGroup container,
179 Bundle savedInstanceState) {
180 super.onCreateView(inflater, container, savedInstanceState);
181
182 if (savedInstanceState != null) {
183 mFile = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
184 mAccount = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_ACCOUNT);
185 }
186
187 if(mFile != null && mAccount != null) {
188 mLayout = R.layout.file_details_fragment;
189 }
190
191 View view = null;
192 view = inflater.inflate(mLayout, container, false);
193 mView = view;
194
195 if (mLayout == R.layout.file_details_fragment) {
196 mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
197 mView.findViewById(R.id.fdRenameBtn).setOnClickListener(this);
198 mView.findViewById(R.id.fdDownloadBtn).setOnClickListener(this);
199 mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);
200 mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);
201 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
202 ProgressBar progressBar = (ProgressBar)mView.findViewById(R.id.fdProgressBar);
203 mProgressListener = new ProgressListener(progressBar);
204 }
205
206 updateFileDetails(false, false);
207 return view;
208 }
209
210
211 /**
212 * {@inheritDoc}
213 */
214 @Override
215 public void onAttach(Activity activity) {
216 super.onAttach(activity);
217 try {
218 mContainerActivity = (ContainerActivity) activity;
219
220 } catch (ClassCastException e) {
221 throw new ClassCastException(activity.toString() + " must implement " + FileDetailFragment.ContainerActivity.class.getSimpleName());
222 }
223 }
224
225
226 /**
227 * {@inheritDoc}
228 */
229 @Override
230 public void onActivityCreated(Bundle savedInstanceState) {
231 super.onActivityCreated(savedInstanceState);
232 if (mAccount != null) {
233 mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());;
234 }
235 }
236
237
238 @Override
239 public void onSaveInstanceState(Bundle outState) {
240 super.onSaveInstanceState(outState);
241 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mFile);
242 outState.putParcelable(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
243 }
244
245 @Override
246 public void onStart() {
247 super.onStart();
248 if (mFile != null && mFile.isAudio()) {
249 bindMediaService();
250 }
251 listenForTransferProgress();
252 }
253
254 @Override
255 public void onResume() {
256 super.onResume();
257
258 /*
259 mDownloadFinishReceiver = new DownloadFinishReceiver();
260 IntentFilter filter = new IntentFilter(
261 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
262 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
263 */
264
265 mUploadFinishReceiver = new UploadFinishReceiver();
266 IntentFilter filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
267 getActivity().registerReceiver(mUploadFinishReceiver, filter);
268
269 }
270
271
272 @Override
273 public void onPause() {
274 super.onPause();
275
276 /*
277 if (mDownloadFinishReceiver != null) {
278 getActivity().unregisterReceiver(mDownloadFinishReceiver);
279 mDownloadFinishReceiver = null;
280 }
281 */
282
283 if (mUploadFinishReceiver != null) {
284 getActivity().unregisterReceiver(mUploadFinishReceiver);
285 mUploadFinishReceiver = null;
286 }
287 }
288
289
290 @Override
291 public void onStop() {
292 super.onStop();
293 if (mMediaServiceConnection != null) {
294 Log.d(TAG, "Unbinding from MediaService ...");
295 if (mMediaServiceBinder != null && mMediaController != null) {
296 mMediaServiceBinder.unregisterMediaController(mMediaController);
297 }
298 getActivity().unbindService(mMediaServiceConnection);
299 mMediaServiceBinder = null;
300 if (mMediaController != null) {
301 mMediaController.hide();
302 mMediaController = null;
303 }
304 }
305 leaveTransferProgress();
306 }
307
308
309 @Override
310 public View getView() {
311 return super.getView() == null ? mView : super.getView();
312 }
313
314
315 @Override
316 public void onClick(View v) {
317 switch (v.getId()) {
318 case R.id.fdDownloadBtn: {
319 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
320 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
321 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
322 downloaderBinder.cancel(mAccount, mFile);
323 if (mFile.isDown()) {
324 setButtonsForDown();
325 } else {
326 setButtonsForRemote();
327 }
328
329 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
330 uploaderBinder.cancel(mAccount, mFile);
331 if (!mFile.fileExists()) {
332 // TODO make something better
333 if (getActivity() instanceof FileDisplayActivity) {
334 // double pane
335 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
336 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FTAG); // empty FileDetailFragment
337 transaction.commit();
338 mContainerActivity.onFileStateChanged();
339 } else {
340 getActivity().finish();
341 }
342
343 } else if (mFile.isDown()) {
344 setButtonsForDown();
345 } else {
346 setButtonsForRemote();
347 }
348
349 } else {
350 mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());
351 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
352 mLastRemoteOperation.execute(wc, this, mHandler);
353
354 // update ui
355 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
356 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
357
358 }
359 break;
360 }
361 case R.id.fdKeepInSync: {
362 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
363 mFile.setKeepInSync(cb.isChecked());
364 mStorageManager.saveFile(mFile);
365
366 /// register the OCFile instance in the observer service to monitor local updates;
367 /// if necessary, the file is download
368 Intent intent = new Intent(getActivity().getApplicationContext(),
369 FileObserverService.class);
370 intent.putExtra(FileObserverService.KEY_FILE_CMD,
371 (cb.isChecked()?
372 FileObserverService.CMD_ADD_OBSERVED_FILE:
373 FileObserverService.CMD_DEL_OBSERVED_FILE));
374 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
375 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
376 getActivity().startService(intent);
377
378 if (mFile.keepInSync()) {
379 onClick(getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
380 }
381 break;
382 }
383 case R.id.fdRenameBtn: {
384 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), mFile.getFileName(), this);
385 dialog.show(getFragmentManager(), "nameeditdialog");
386 break;
387 }
388 case R.id.fdRemoveBtn: {
389 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
390 R.string.confirmation_remove_alert,
391 new String[]{mFile.getFileName()},
392 mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
393 mFile.isDown() ? R.string.confirmation_remove_local : -1,
394 R.string.common_cancel);
395 confDialog.setOnConfirmationListener(this);
396 confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
397 break;
398 }
399 case R.id.fdOpenBtn: {
400 openFile();
401 break;
402 }
403 default:
404 Log.e(TAG, "Incorrect view clicked!");
405 }
406
407 /* else if (v.getId() == R.id.fdShareBtn) {
408 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
409 t.start();
410 }*/
411 }
412
413
414 private void startVideoActivity() {
415 Intent i = new Intent(getActivity(), PreviewVideoActivity.class);
416 i.putExtra(PreviewVideoActivity.EXTRA_FILE, mFile);
417 i.putExtra(PreviewVideoActivity.EXTRA_ACCOUNT, mAccount);
418 startActivity(i);
419 }
420
421
422 private void bindMediaService() {
423 Log.d(TAG, "Binding to MediaService...");
424 if (mMediaServiceConnection == null) {
425 mMediaServiceConnection = new MediaServiceConnection();
426 }
427 getActivity().bindService( new Intent(getActivity(),
428 MediaService.class),
429 mMediaServiceConnection,
430 Context.BIND_AUTO_CREATE);
431 // follow the flow in MediaServiceConnection#onServiceConnected(...)
432 }
433
434 /** Defines callbacks for service binding, passed to bindService() */
435 private class MediaServiceConnection implements ServiceConnection {
436
437 @Override
438 public void onServiceConnected(ComponentName component, IBinder service) {
439 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
440 Log.d(TAG, "Media service connected");
441 mMediaServiceBinder = (MediaServiceBinder) service;
442 if (mMediaServiceBinder != null) {
443 if (mMediaController == null) {
444 mMediaController = new MediaController(getSherlockActivity());
445 }
446 prepareMediaController();
447
448 Log.d(TAG, "Successfully bound to MediaService, MediaController ready");
449
450 } else {
451 Log.e(TAG, "Unexpected response from MediaService while binding");
452 }
453 }
454 }
455
456 private void prepareMediaController() {
457 mMediaServiceBinder.registerMediaController(mMediaController);
458 mMediaController.setMediaPlayer(mMediaServiceBinder);
459 mMediaController.setAnchorView(getView());
460 mMediaController.setEnabled(mMediaServiceBinder.isInPlaybackState());
461 }
462
463 @Override
464 public void onServiceDisconnected(ComponentName component) {
465 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
466 Log.e(TAG, "Media service suddenly disconnected");
467 if (mMediaController != null) {
468 mMediaController.hide();
469 mMediaController.setMediaPlayer(null);
470 mMediaController = null;
471 }
472 mMediaServiceBinder = null;
473 mMediaServiceConnection = null;
474 }
475 }
476 }
477
478
479 /**
480 * Opens mFile.
481 */
482 private void openFile() {
483
484 String storagePath = mFile.getStoragePath();
485 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
486 try {
487 Intent i = new Intent(Intent.ACTION_VIEW);
488 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
489 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
490 startActivity(i);
491
492 } catch (Throwable t) {
493 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
494 boolean toastIt = true;
495 String mimeType = "";
496 try {
497 Intent i = new Intent(Intent.ACTION_VIEW);
498 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
499 if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
500 if (mimeType != null) {
501 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
502 } else {
503 // desperate try
504 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*/*");
505 }
506 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
507 startActivity(i);
508 toastIt = false;
509 }
510
511 } catch (IndexOutOfBoundsException e) {
512 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
513
514 } catch (ActivityNotFoundException e) {
515 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
516
517 } catch (Throwable th) {
518 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
519
520 } finally {
521 if (toastIt) {
522 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
523 }
524 }
525
526 }
527 }
528
529
530 @Override
531 public void onConfirmation(String callerTag) {
532 if (callerTag.equals(FTAG_CONFIRMATION)) {
533 if (mStorageManager.getFileById(mFile.getFileId()) != null) {
534 mLastRemoteOperation = new RemoveFileOperation( mFile,
535 true,
536 mStorageManager);
537 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
538 mLastRemoteOperation.execute(wc, this, mHandler);
539
540 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
541 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
542 }
543 }
544 }
545
546 @Override
547 public void onNeutral(String callerTag) {
548 File f = null;
549 if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {
550 f.delete();
551 mFile.setStoragePath(null);
552 mStorageManager.saveFile(mFile);
553 updateFileDetails(mFile, mAccount);
554 }
555 }
556
557 @Override
558 public void onCancel(String callerTag) {
559 Log.d(TAG, "REMOVAL CANCELED");
560 }
561
562
563 /**
564 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
565 *
566 * @return True when the fragment was created with the empty layout.
567 */
568 public boolean isEmpty() {
569 return (mLayout == R.layout.file_details_empty || mFile == null || mAccount == null);
570 }
571
572
573 /**
574 * {@inheritDoc}
575 */
576 public OCFile getFile(){
577 return mFile;
578 }
579
580 /**
581 * Use this method to signal this Activity that it shall update its view.
582 *
583 * @param file : An {@link OCFile}
584 */
585 public void updateFileDetails(OCFile file, Account ocAccount) {
586 mFile = file;
587 if (ocAccount != null && (
588 mStorageManager == null ||
589 (mAccount != null && !mAccount.equals(ocAccount))
590 )) {
591 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
592 }
593 mAccount = ocAccount;
594 updateFileDetails(false, false);
595 }
596
597
598 /**
599 * Updates the view with all relevant details about that file.
600 *
601 * TODO Remove parameter when the transferring state of files is kept in database.
602 *
603 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
604 *
605 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
606 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
607 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
608 *
609 * @param refresh If 'true', try to refresh the hold file from the database
610 */
611 public void updateFileDetails(boolean transferring, boolean refresh) {
612
613 if (readyToShow()) {
614
615 if (refresh && mStorageManager != null) {
616 mFile = mStorageManager.getFileByPath(mFile.getRemotePath());
617 }
618
619 // set file details
620 setFilename(mFile.getFileName());
621 setFiletype(mFile.getMimetype());
622 setFilesize(mFile.getFileLength());
623 if(ocVersionSupportsTimeCreated()){
624 setTimeCreated(mFile.getCreationTimestamp());
625 }
626
627 setTimeModified(mFile.getModificationTimestamp());
628
629 CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
630 cb.setChecked(mFile.keepInSync());
631
632 // configure UI for depending upon local state of the file
633 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
634 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
635 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
636 if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile))) {
637 setButtonsForTransferring();
638
639 } else if (mFile.isDown()) {
640
641 setButtonsForDown();
642
643 } else {
644 // TODO load default preview image; when the local file is removed, the preview remains there
645 setButtonsForRemote();
646 }
647 }
648 getView().invalidate();
649 }
650
651
652 /**
653 * Checks if the fragment is ready to show details of a OCFile
654 *
655 * @return 'True' when the fragment is ready to show details of a file
656 */
657 private boolean readyToShow() {
658 return (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment);
659 }
660
661
662
663 /**
664 * Updates the filename in view
665 * @param filename to set
666 */
667 private void setFilename(String filename) {
668 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
669 if (tv != null)
670 tv.setText(filename);
671 }
672
673 /**
674 * Updates the MIME type in view
675 * @param mimetype to set
676 */
677 private void setFiletype(String mimetype) {
678 TextView tv = (TextView) getView().findViewById(R.id.fdType);
679 if (tv != null) {
680 String printableMimetype = DisplayUtils.convertMIMEtoPrettyPrint(mimetype);;
681 tv.setText(printableMimetype);
682 }
683 ImageView iv = (ImageView) getView().findViewById(R.id.fdIcon);
684 if (iv != null) {
685 iv.setImageResource(DisplayUtils.getResourceId(mimetype));
686 }
687 }
688
689 /**
690 * Updates the file size in view
691 * @param filesize in bytes to set
692 */
693 private void setFilesize(long filesize) {
694 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
695 if (tv != null)
696 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
697 }
698
699 /**
700 * Updates the time that the file was created in view
701 * @param milliseconds Unix time to set
702 */
703 private void setTimeCreated(long milliseconds){
704 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
705 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
706 if(tv != null){
707 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
708 tv.setVisibility(View.VISIBLE);
709 tvLabel.setVisibility(View.VISIBLE);
710 }
711 }
712
713 /**
714 * Updates the time that the file was last modified
715 * @param milliseconds Unix time to set
716 */
717 private void setTimeModified(long milliseconds){
718 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
719 if(tv != null){
720 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
721 }
722 }
723
724 /**
725 * Enables or disables buttons for a file being downloaded
726 */
727 private void setButtonsForTransferring() {
728 if (!isEmpty()) {
729 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
730 downloadButton.setText(R.string.common_cancel);
731 //downloadButton.setEnabled(false);
732
733 // let's protect the user from himself ;)
734 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
735 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(false);
736 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(false);
737 getView().findViewById(R.id.fdKeepInSync).setEnabled(false);
738
739 // show the progress bar for the transfer
740 ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
741 progressBar.setVisibility(View.VISIBLE);
742 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
743 progressText.setVisibility(View.VISIBLE);
744 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
745 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
746 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
747 progressText.setText(R.string.downloader_download_in_progress_ticker);
748 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
749 progressText.setText(R.string.uploader_upload_in_progress_ticker);
750 }
751 }
752 }
753
754
755 /**
756 * Enables or disables buttons for a file locally available
757 */
758 private void setButtonsForDown() {
759 if (!isEmpty()) {
760 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
761 downloadButton.setText(R.string.filedetails_sync_file);
762
763 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(true);
764 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
765 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
766 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
767
768 // hides the progress bar
769 ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
770 progressBar.setVisibility(View.GONE);
771 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
772 progressText.setVisibility(View.GONE);
773 }
774 }
775
776 /**
777 * Enables or disables buttons for a file not locally available
778 */
779 private void setButtonsForRemote() {
780 if (!isEmpty()) {
781 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
782 downloadButton.setText(R.string.filedetails_download);
783
784 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
785 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
786 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
787 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
788
789 // hides the progress bar
790 ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
791 progressBar.setVisibility(View.GONE);
792 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
793 progressText.setVisibility(View.GONE);
794 }
795 }
796
797
798 /**
799 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
800 * the time that the file was created. There is a chance that this will
801 * be fixed in future versions. Use this method to check if this version of
802 * ownCloud has this fix.
803 * @return True, if ownCloud the ownCloud version is supporting creation time
804 */
805 private boolean ocVersionSupportsTimeCreated(){
806 /*if(mAccount != null){
807 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
808 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
809 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
810 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
811 return true;
812 }
813 }*/
814 return false;
815 }
816
817
818 /* *
819 * Once the file download has finished -> update view
820 * @author Bartek Przybylski
821 * - /
822 private class DownloadFinishReceiver extends BroadcastReceiver {
823 @Override
824 public void onReceive(Context context, Intent intent) {
825 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
826
827 if (!isEmpty() && accountName.equals(mAccount.name)) {
828 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
829 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
830 if (mFile.getRemotePath().equals(downloadedRemotePath)) {
831 if (downloadWasFine) {
832 mFile = mStorageManager.getFileByPath(downloadedRemotePath);
833 }
834 mContainerActivity.notifySuccessfulDownload(mFile, intent, downloadWasFine);
835 getActivity().removeStickyBroadcast(intent);
836 updateFileDetails(false); // it updates the buttons; must be called although !downloadWasFine
837 }
838 }
839 }
840 }
841 */
842
843
844 /**
845 * Once the file upload has finished -> update view
846 *
847 * Being notified about the finish of an upload is necessary for the next sequence:
848 * 1. Upload a big file.
849 * 2. Force a synchronization; if it finished before the upload, the file in transfer will be included in the local database and in the file list
850 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
851 * 3. Click the file in the list to see its details.
852 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
853 */
854 private class UploadFinishReceiver extends BroadcastReceiver {
855 @Override
856 public void onReceive(Context context, Intent intent) {
857 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
858
859 if (!isEmpty() && accountName.equals(mAccount.name)) {
860 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
861 String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
862 boolean renamedInUpload = mFile.getRemotePath().equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
863 if (mFile.getRemotePath().equals(uploadRemotePath) ||
864 renamedInUpload) {
865 if (uploadWasFine) {
866 mFile = mStorageManager.getFileByPath(uploadRemotePath);
867 }
868 if (renamedInUpload) {
869 String newName = (new File(uploadRemotePath)).getName();
870 Toast msg = Toast.makeText(getActivity().getApplicationContext(), String.format(getString(R.string.filedetails_renamed_in_upload_msg), newName), Toast.LENGTH_LONG);
871 msg.show();
872 }
873 getSherlockActivity().removeStickyBroadcast(intent); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
874 updateFileDetails(false, false); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
875 }
876 }
877 }
878 }
879
880
881 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
882 @SuppressWarnings("unused")
883 private class ShareRunnable implements Runnable {
884 private String mPath;
885
886 public ShareRunnable(String path) {
887 mPath = path;
888 }
889
890 public void run() {
891 AccountManager am = AccountManager.get(getActivity());
892 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
893 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
894 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
895
896 Log.d("share", "sharing for version " + ocv.toString());
897
898 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
899 String APPS_PATH = "/apps/files_sharing/";
900 String SHARE_PATH = "ajax/share.php";
901
902 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
903
904 final String WEBDAV_SCRIPT = "webdav.php";
905 final String WEBDAV_FILES_LOCATION = "/files/";
906
907 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
908 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
909 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
910
911 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
912 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
913
914 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
915
916 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
917 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
918 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
919 Log.d("share", mPath+"");
920 formparams.add(new BasicNameValuePair("sources",mPath));
921 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
922 formparams.add(new BasicNameValuePair("permissions", "0"));
923 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
924
925 int status;
926 try {
927 PropFindMethod find = new PropFindMethod(url+"/");
928 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
929 Log.d("sharer", ""+ url+"/");
930
931 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
932 Log.d("sharer-h", a.getName() + ":"+a.getValue());
933 }
934
935 int status2 = wc.executeMethod(find);
936
937 Log.d("sharer", "propstatus "+status2);
938
939 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
940 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
941
942 status2 = wc.executeMethod(get);
943
944 Log.d("sharer", "getstatus "+status2);
945 Log.d("sharer", "" + get.getResponseBodyAsString());
946
947 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
948 Log.d("sharer", a.getName() + ":"+a.getValue());
949 }
950
951 status = wc.executeMethod(post);
952 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
953 Log.d("sharer-h", a.getName() + ":"+a.getValue());
954 }
955 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
956 Log.d("sharer", a.getName() + ":"+a.getValue());
957 }
958 String resp = post.getResponseBodyAsString();
959 Log.d("share", ""+post.getURI().toString());
960 Log.d("share", "returned status " + status);
961 Log.d("share", " " +resp);
962
963 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
964 return;
965 }
966
967 JSONObject jsonObject = new JSONObject (resp);
968 String jsonStatus = jsonObject.getString("status");
969 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
970
971 String token = jsonObject.getString("data");
972 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
973 Log.d("Actions:shareFile ok", "url: " + uri);
974
975 } catch (Exception e) {
976 e.printStackTrace();
977 }
978
979 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
980
981 }
982 }
983 }
984
985 public void onDismiss(EditNameDialog dialog) {
986 if (dialog.getResult()) {
987 String newFilename = dialog.getNewFilename();
988 Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
989 mLastRemoteOperation = new RenameFileOperation( mFile,
990 mAccount,
991 newFilename,
992 new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
993 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
994 mLastRemoteOperation.execute(wc, this, mHandler);
995 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
996 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
997 }
998 }
999
1000
1001 /**
1002 * {@inheritDoc}
1003 */
1004 @Override
1005 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1006 if (operation.equals(mLastRemoteOperation)) {
1007 if (operation instanceof RemoveFileOperation) {
1008 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1009
1010 } else if (operation instanceof RenameFileOperation) {
1011 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1012
1013 } else if (operation instanceof SynchronizeFileOperation) {
1014 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1015 }
1016 }
1017 }
1018
1019
1020 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1021 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1022 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1023
1024 if (result.isSuccess()) {
1025 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
1026 msg.show();
1027 if (inDisplayActivity) {
1028 // double pane
1029 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
1030 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
1031 transaction.commit();
1032 mContainerActivity.onFileStateChanged();
1033 } else {
1034 getActivity().finish();
1035 }
1036
1037 } else {
1038 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
1039 msg.show();
1040 if (result.isSslRecoverableException()) {
1041 // TODO show the SSL warning dialog
1042 }
1043 }
1044 }
1045
1046 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1047 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1048 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1049
1050 if (result.isSuccess()) {
1051 updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
1052 mContainerActivity.onFileStateChanged();
1053
1054 } else {
1055 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1056 Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1057 msg.show();
1058 // TODO throw again the new rename dialog
1059 } else {
1060 Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1061 msg.show();
1062 if (result.isSslRecoverableException()) {
1063 // TODO show the SSL warning dialog
1064 }
1065 }
1066 }
1067 }
1068
1069 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1070 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1071 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1072
1073 if (!result.isSuccess()) {
1074 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1075 Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
1076 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, mFile);
1077 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
1078 startActivity(i);
1079
1080 } else {
1081 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1082 msg.show();
1083 }
1084
1085 if (mFile.isDown()) {
1086 setButtonsForDown();
1087
1088 } else {
1089 setButtonsForRemote();
1090 }
1091
1092 } else {
1093 if (operation.transferWasRequested()) {
1094 setButtonsForTransferring();
1095 mContainerActivity.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1096 // checking the service to see if the file is downloading results in FALSE
1097 } else {
1098 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1099 msg.show();
1100 if (mFile.isDown()) {
1101 setButtonsForDown();
1102
1103 } else {
1104 setButtonsForRemote();
1105 }
1106 }
1107 }
1108 }
1109
1110
1111 public void listenForTransferProgress() {
1112 if (mProgressListener != null) {
1113 if (mContainerActivity.getFileDownloaderBinder() != null) {
1114 mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
1115 }
1116 if (mContainerActivity.getFileUploaderBinder() != null) {
1117 mContainerActivity.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
1118 }
1119 }
1120 }
1121
1122
1123 public void leaveTransferProgress() {
1124 if (mProgressListener != null) {
1125 if (mContainerActivity.getFileDownloaderBinder() != null) {
1126 mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
1127 }
1128 if (mContainerActivity.getFileUploaderBinder() != null) {
1129 mContainerActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
1130 }
1131 }
1132 }
1133
1134
1135
1136 /**
1137 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1138 *
1139 * @author David A. Velasco
1140 */
1141 private class ProgressListener implements OnDatatransferProgressListener {
1142 int mLastPercent = 0;
1143 WeakReference<ProgressBar> mProgressBar = null;
1144
1145 ProgressListener(ProgressBar progressBar) {
1146 mProgressBar = new WeakReference<ProgressBar>(progressBar);
1147 }
1148
1149 @Override
1150 public void onTransferProgress(long progressRate) {
1151 // old method, nothing here
1152 };
1153
1154 @Override
1155 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename) {
1156 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
1157 if (percent != mLastPercent) {
1158 ProgressBar pb = mProgressBar.get();
1159 if (pb != null) {
1160 pb.setProgress(percent);
1161 pb.postInvalidate();
1162 }
1163 }
1164 mLastPercent = percent;
1165 }
1166
1167 };
1168
1169
1170
1171 }