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