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