1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
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 2 of the License, or
7 * (at your option) any later version.
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.
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/>.
18 package com
.owncloud
.android
.ui
.fragment
;
21 import java
.lang
.ref
.WeakReference
;
22 import java
.sql
.PreparedStatement
;
23 import java
.util
.ArrayList
;
24 import java
.util
.List
;
26 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
27 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
28 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
29 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
30 import org
.apache
.http
.HttpStatus
;
31 import org
.apache
.http
.NameValuePair
;
32 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
33 import org
.apache
.http
.entity
.FileEntity
;
34 import org
.apache
.http
.message
.BasicNameValuePair
;
35 import org
.apache
.http
.protocol
.HTTP
;
36 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
37 import org
.json
.JSONObject
;
39 import android
.accounts
.Account
;
40 import android
.accounts
.AccountManager
;
41 import android
.annotation
.SuppressLint
;
42 import android
.app
.Activity
;
43 import android
.app
.AlertDialog
;
44 import android
.content
.ActivityNotFoundException
;
45 import android
.content
.BroadcastReceiver
;
46 import android
.content
.ComponentName
;
47 import android
.content
.Context
;
48 import android
.content
.DialogInterface
;
49 import android
.content
.Intent
;
50 import android
.content
.IntentFilter
;
51 import android
.content
.ServiceConnection
;
52 import android
.graphics
.Bitmap
;
53 import android
.graphics
.BitmapFactory
;
54 import android
.graphics
.BitmapFactory
.Options
;
55 import android
.graphics
.Point
;
56 import android
.media
.MediaPlayer
;
57 import android
.media
.MediaPlayer
.OnCompletionListener
;
58 import android
.media
.MediaPlayer
.OnErrorListener
;
59 import android
.media
.MediaPlayer
.OnPreparedListener
;
60 import android
.net
.Uri
;
61 import android
.os
.AsyncTask
;
62 import android
.os
.Bundle
;
63 import android
.os
.Handler
;
64 import android
.os
.IBinder
;
65 import android
.support
.v4
.app
.DialogFragment
;
66 import android
.support
.v4
.app
.FragmentTransaction
;
67 import android
.util
.Log
;
68 import android
.view
.Display
;
69 import android
.view
.LayoutInflater
;
70 import android
.view
.MotionEvent
;
71 import android
.view
.View
;
72 import android
.view
.View
.OnClickListener
;
73 import android
.view
.View
.OnTouchListener
;
74 import android
.view
.ViewGroup
;
75 import android
.webkit
.MimeTypeMap
;
76 import android
.widget
.Button
;
77 import android
.widget
.CheckBox
;
78 import android
.widget
.ImageView
;
79 import android
.widget
.MediaController
;
80 import android
.widget
.TextView
;
81 import android
.widget
.Toast
;
82 import android
.widget
.VideoView
;
84 import com
.actionbarsherlock
.app
.SherlockFragment
;
85 import com
.owncloud
.android
.AccountUtils
;
86 import com
.owncloud
.android
.DisplayUtils
;
87 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
88 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
89 import com
.owncloud
.android
.datamodel
.OCFile
;
90 import com
.owncloud
.android
.files
.services
.FileDownloader
;
91 import com
.owncloud
.android
.files
.services
.FileObserverService
;
92 import com
.owncloud
.android
.files
.services
.FileUploader
;
93 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
94 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
95 import com
.owncloud
.android
.media
.MediaService
;
96 import com
.owncloud
.android
.media
.MediaServiceBinder
;
97 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
98 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
99 import com
.owncloud
.android
.operations
.RemoteOperation
;
100 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
101 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
102 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
103 import com
.owncloud
.android
.operations
.RenameFileOperation
;
104 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
105 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
106 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
107 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
108 import com
.owncloud
.android
.ui
.OnSwipeTouchListener
;
109 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
110 import com
.owncloud
.android
.ui
.activity
.VideoActivity
;
111 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
112 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
113 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
115 import com
.owncloud
.android
.R
;
116 import eu
.alefzero
.webdav
.WebdavClient
;
117 import eu
.alefzero
.webdav
.WebdavUtils
;
120 * This fragment shows a preview of a downloaded file.
122 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
124 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
126 * @author David A. Velasco
128 public class FilePreviewFragment
extends SherlockFragment
implements
129 /*OnClickListener,*/ OnTouchListener
, FileFragment
130 /*ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener, EditNameDialogListener*/ {
132 public static final String EXTRA_FILE
= "FILE";
133 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
134 private static final String EXTRA_PLAY_POSITION
= "PLAY_POSITION";
136 //private FilePreviewFragment.ContainerActivity mContainerActivity;
139 private OCFile mFile
;
140 private Account mAccount
;
141 //private FileDataStorageManager mStorageManager;
142 private ImageView mImagePreview
;
143 public Bitmap mBitmap
= null
;
144 private VideoView mVideoPreview
;
145 private int mSavedPlaybackPosition
;
147 //private DownloadFinishReceiver mDownloadFinishReceiver;
148 //private UploadFinishReceiver mUploadFinishReceiver;
150 //private Handler mHandler;
151 //private RemoteOperation mLastRemoteOperation;
152 //private DialogFragment mCurrentDialog;
154 private MediaServiceBinder mMediaServiceBinder
= null
;
155 private MediaController mMediaController
= null
;
156 private MediaServiceConnection mMediaServiceConnection
= null
;
157 private VideoHelper mVideoHelper
;
159 private static final String TAG
= FilePreviewFragment
.class.getSimpleName();
160 public static final String FTAG
= FilePreviewFragment
.class.getSimpleName();;
161 //public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
165 * Creates a fragment to preview a file.
167 * When 'fileToDetail' or 'ocAccount' are null
169 * @param fileToDetail An {@link OCFile} to preview in the fragment
170 * @param ocAccount An ownCloud account; needed to start downloads
172 public FilePreviewFragment(OCFile fileToDetail
, Account ocAccount
) {
173 mFile
= fileToDetail
;
174 mAccount
= ocAccount
;
175 mSavedPlaybackPosition
= 0;
176 //mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
181 * Creates an empty fragment for previews.
183 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
185 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
187 public FilePreviewFragment() {
190 mSavedPlaybackPosition
= 0;
191 //mStorageManager = null;
199 public void onCreate(Bundle savedInstanceState
) {
200 super.onCreate(savedInstanceState
);
201 //mHandler = new Handler();
209 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
210 Bundle savedInstanceState
) {
211 super.onCreateView(inflater
, container
, savedInstanceState
);
213 mView
= inflater
.inflate(R
.layout
.file_preview
, container
, false
);
215 //mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
216 //mView.findViewById(R.id.fdRenameBtn).setOnClickListener(this);
217 //mView.findViewById(R.id.fdDownloadBtn).setOnClickListener(this);
218 //mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);
219 //mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);
220 mImagePreview
= (ImageView
)mView
.findViewById(R
.id
.image_preview
);
221 mImagePreview
.setOnTouchListener(this);
222 mVideoPreview
= (VideoView
)mView
.findViewById(R
.id
.video_preview
);
224 //updateFileDetails(false);
233 public void onAttach(Activity activity
) {
234 super.onAttach(activity
);
242 public void onActivityCreated(Bundle savedInstanceState
) {
243 super.onActivityCreated(savedInstanceState
);
245 //mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
246 if (savedInstanceState
!= null
) {
247 mFile
= savedInstanceState
.getParcelable(FilePreviewFragment
.EXTRA_FILE
);
248 mAccount
= savedInstanceState
.getParcelable(FilePreviewFragment
.EXTRA_ACCOUNT
);
249 mSavedPlaybackPosition
= savedInstanceState
.getInt(FilePreviewFragment
.EXTRA_PLAY_POSITION
);
253 throw new IllegalStateException("Instanced with a NULL OCFile");
255 if (mAccount
== null
) {
256 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
258 if (!mFile
.isDown()) {
259 throw new IllegalStateException("There is no local file to preview");
261 if (mFile
.isVideo()) {
262 mVideoPreview
.setVisibility(View
.VISIBLE
);
263 mImagePreview
.setVisibility(View
.GONE
);
267 mVideoPreview
.setVisibility(View
.GONE
);
268 mImagePreview
.setVisibility(View
.VISIBLE
);
278 public void onSaveInstanceState(Bundle outState
) {
279 super.onSaveInstanceState(outState
);
281 outState
.putParcelable(FilePreviewFragment
.EXTRA_FILE
, mFile
);
282 outState
.putParcelable(FilePreviewFragment
.EXTRA_ACCOUNT
, mAccount
);
284 if (mVideoPreview
.isPlaying()) {
285 outState
.putInt(FilePreviewFragment
.EXTRA_PLAY_POSITION
, mVideoPreview
.getCurrentPosition());
291 public void onStart() {
295 if (mFile
.isAudio()) {
298 } else if (mFile
.isImage()) {
299 BitmapLoader bl
= new BitmapLoader(mImagePreview
);
300 bl
.execute(new String
[]{mFile
.getStoragePath()});
302 } else if (mFile
.isVideo()) {
309 private void prepareVideo() {
310 // create helper to get more control on the playback
311 mVideoHelper
= new VideoHelper();
312 mVideoPreview
.setOnPreparedListener(mVideoHelper
);
313 mVideoPreview
.setOnCompletionListener(mVideoHelper
);
314 mVideoPreview
.setOnErrorListener(mVideoHelper
);
317 private void playVideo() {
318 // load the video file in the video player ; when done, VideoHelper#onPrepared() will be called
319 mVideoPreview
.setVideoPath(mFile
.getStoragePath());
321 // create and prepare control panel for the user
322 mMediaController
= new MediaController(getActivity());
323 mMediaController
.setMediaPlayer(mVideoPreview
);
324 mMediaController
.setAnchorView(mVideoPreview
);
325 mVideoPreview
.setMediaController(mMediaController
);
329 private class VideoHelper
implements OnCompletionListener
, OnPreparedListener
, OnErrorListener
{
332 * Called when the file is ready to be played.
334 * Just starts the playback.
336 * @param mp {@link MediaPlayer} instance performing the playback.
339 public void onPrepared(MediaPlayer vp
) {
340 mVideoPreview
.seekTo(mSavedPlaybackPosition
);
341 mVideoPreview
.start();
342 mMediaController
.show(MediaService
.MEDIA_CONTROL_SHORT_LIFE
);
347 * Called when the file is finished playing.
349 * Finishes the activity.
351 * @param mp {@link MediaPlayer} instance performing the playback.
354 public void onCompletion(MediaPlayer mp
) {
355 // nothing, right now
360 * Called when an error in playback occurs.
362 * @param mp {@link MediaPlayer} instance performing the playback.
363 * @param what Type of error
364 * @param extra Extra code specific to the error
367 public boolean onError(MediaPlayer mp
, int what
, int extra
) {
368 Log
.e(TAG
, "Error in video playback, what = " + what
+ ", extra = " + extra
);
370 if (mMediaController
!= null
) {
371 mMediaController
.hide();
374 if (mVideoPreview
.getWindowToken() != null
) {
375 String message
= MediaService
.getMessageForMediaError(getActivity(), what
, extra
);
376 new AlertDialog
.Builder(getActivity())
378 .setPositiveButton(android
.R
.string
.VideoView_error_button
,
379 new DialogInterface
.OnClickListener() {
380 public void onClick(DialogInterface dialog
, int whichButton
) {
382 VideoHelper
.this.onCompletion(null
);
385 .setCancelable(false
)
395 public void onResume() {
398 mDownloadFinishReceiver = new DownloadFinishReceiver();
399 IntentFilter filter = new IntentFilter(
400 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
401 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
403 mUploadFinishReceiver = new UploadFinishReceiver();
404 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
405 getActivity().registerReceiver(mUploadFinishReceiver, filter);
412 public void onPause() {
415 if (mVideoPreview.getVisibility() == View.VISIBLE) {
416 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
419 getActivity().unregisterReceiver(mDownloadFinishReceiver);
420 mDownloadFinishReceiver = null;
422 getActivity().unregisterReceiver(mUploadFinishReceiver);
423 mUploadFinishReceiver = null;
429 public void onStop() {
431 if (mMediaServiceConnection
!= null
) {
432 Log
.d(TAG
, "Unbinding from MediaService ...");
433 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
434 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
436 getActivity().unbindService(mMediaServiceConnection
);
437 mMediaServiceConnection
= null
;
438 mMediaServiceBinder
= null
;
439 if (mMediaController
!= null
) {
440 mMediaController
.hide();
441 mMediaController
= null
;
444 if (mBitmap
!= null
) {
451 public View getView() {
452 return super.getView() == null ? mView : super.getView();
458 public void onClick(View v) {
460 case R.id.fdDownloadBtn: {
461 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
462 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
463 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
464 downloaderBinder.cancel(mAccount, mFile);
465 if (mFile.isDown()) {
468 setButtonsForRemote();
471 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
472 uploaderBinder.cancel(mAccount, mFile);
473 if (!mFile.fileExists()) {
474 // TODO make something better
475 if (getActivity() instanceof FileDisplayActivity) {
477 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
478 transaction.replace(R.id.file_details_container, new FilePreviewFragment(null, null), FTAG); // empty FileDetailFragment
479 transaction.commit();
480 mContainerActivity.onFileStateChanged();
482 getActivity().finish();
485 } else if (mFile.isDown()) {
488 setButtonsForRemote();
492 mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());
493 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
494 mLastRemoteOperation.execute(wc, this, mHandler);
497 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
498 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
499 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
504 case R.id.fdKeepInSync: {
505 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
506 mFile.setKeepInSync(cb.isChecked());
507 mStorageManager.saveFile(mFile);
509 /// register the OCFile instance in the observer service to monitor local updates;
510 /// if necessary, the file is download
511 Intent intent = new Intent(getActivity().getApplicationContext(),
512 FileObserverService.class);
513 intent.putExtra(FileObserverService.KEY_FILE_CMD,
515 FileObserverService.CMD_ADD_OBSERVED_FILE:
516 FileObserverService.CMD_DEL_OBSERVED_FILE));
517 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
518 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
519 Log.e(TAG, "starting observer service");
520 getActivity().startService(intent);
522 if (mFile.keepInSync()) {
523 onClick(getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
527 case R.id.fdRenameBtn: {
528 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), mFile.getFileName(), this);
529 dialog.show(getFragmentManager(), "nameeditdialog");
532 case R.id.fdRemoveBtn: {
533 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
534 R.string.confirmation_remove_alert,
535 new String[]{mFile.getFileName()},
536 mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
537 mFile.isDown() ? R.string.confirmation_remove_local : -1,
538 R.string.common_cancel);
539 confDialog.setOnConfirmationListener(this);
540 mCurrentDialog = confDialog;
541 mCurrentDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
544 case R.id.fdOpenBtn: {
549 Log.e(TAG, "Incorrect view clicked!");
557 public boolean onTouch(View v
, MotionEvent event
) {
558 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
559 if (v
== mImagePreview
&&
560 mMediaServiceBinder
!= null
&& mFile
.isAudio() && mMediaServiceBinder
.isPlaying(mFile
)) {
561 toggleMediaController(MediaService
.MEDIA_CONTROL_PERMANENT
);
564 } else if (v
== mVideoPreview
) {
565 toggleMediaController(MediaService
.MEDIA_CONTROL_SHORT_LIFE
);
573 private void toggleMediaController(int time
) {
574 if (mMediaController
.isShowing()) {
575 mMediaController
.hide();
577 mMediaController
.show(time
);
582 private void playAudio() {
583 if (!mMediaServiceBinder
.isPlaying(mFile
)) {
584 Log
.d(TAG
, "starting playback of " + mFile
.getStoragePath());
585 mMediaServiceBinder
.start(mAccount
, mFile
);
588 if (!mMediaServiceBinder
.isPlaying()) {
589 mMediaServiceBinder
.start();
591 if (!mMediaController
.isShowing() && isVisible()) {
592 mMediaController
.show(MediaService
.MEDIA_CONTROL_PERMANENT
);
593 // TODO - fix strange bug; steps to trigger :
594 // 1. remove the "isVisible()" control
595 // 2. start the app and preview an audio file
596 // 3. exit from the app (home button, for instance) while the audio file is still being played
597 // 4. go to notification bar and click on the "ownCloud music app" notification
604 private void bindMediaService() {
605 Log
.d(TAG
, "Binding to MediaService...");
606 if (mMediaServiceConnection
== null
) {
607 mMediaServiceConnection
= new MediaServiceConnection();
609 getActivity().bindService( new Intent(getActivity(),
611 mMediaServiceConnection
,
612 Context
.BIND_AUTO_CREATE
);
613 // follow the flow in MediaServiceConnection#onServiceConnected(...)
616 /** Defines callbacks for service binding, passed to bindService() */
617 private class MediaServiceConnection
implements ServiceConnection
{
620 public void onServiceConnected(ComponentName component
, IBinder service
) {
621 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
622 Log
.d(TAG
, "Media service connected");
623 mMediaServiceBinder
= (MediaServiceBinder
) service
;
624 if (mMediaServiceBinder
!= null
) {
625 if (mMediaController
== null
) {
626 mMediaController
= new MediaController(getSherlockActivity());
628 prepareMediaController();
629 playAudio(); // do not wait for the touch of nobody to play audio
631 Log
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
634 Log
.e(TAG
, "Unexpected response from MediaService while binding");
639 private void prepareMediaController() {
640 mMediaServiceBinder
.registerMediaController(mMediaController
);
641 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
642 mMediaController
.setAnchorView(getView());
643 mMediaController
.setEnabled(mMediaServiceBinder
.isInPlaybackState());
647 public void onServiceDisconnected(ComponentName component
) {
648 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
649 Log
.e(TAG
, "Media service suddenly disconnected");
650 if (mMediaController
!= null
) {
651 mMediaController
.hide();
652 mMediaController
.setMediaPlayer(null
);
653 mMediaController
= null
;
655 mMediaServiceBinder
= null
;
656 mMediaServiceConnection
= null
;
666 private void openFile() {
668 String storagePath = mFile.getStoragePath();
669 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
671 Intent i = new Intent(Intent.ACTION_VIEW);
672 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
673 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
676 } catch (Throwable t) {
677 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
678 boolean toastIt = true;
679 String mimeType = "";
681 Intent i = new Intent(Intent.ACTION_VIEW);
682 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
683 if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
684 if (mimeType != null) {
685 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
688 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*-/*");
690 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
695 } catch (IndexOutOfBoundsException e) {
696 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
698 } catch (ActivityNotFoundException e) {
699 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
701 } catch (Throwable th) {
702 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
706 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
716 public void onConfirmation(String callerTag) {
717 if (callerTag.equals(FTAG_CONFIRMATION)) {
718 if (mStorageManager.getFileById(mFile.getFileId()) != null) {
719 mLastRemoteOperation = new RemoveFileOperation( mFile,
722 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
723 mLastRemoteOperation.execute(wc, this, mHandler);
725 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
726 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
729 mCurrentDialog.dismiss();
730 mCurrentDialog = null;
734 public void onNeutral(String callerTag) {
736 if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {
738 mFile.setStoragePath(null);
739 mStorageManager.saveFile(mFile);
740 updateFileDetails(mFile, mAccount);
742 mCurrentDialog.dismiss();
743 mCurrentDialog = null;
747 public void onCancel(String callerTag) {
748 Log.d(TAG, "REMOVAL CANCELED");
749 mCurrentDialog.dismiss();
750 mCurrentDialog = null;
757 public OCFile
getFile(){
763 * Use this method to signal this Activity that it shall update its view.
765 * @param file : An {@link OCFile}
767 public void updateFileDetails(OCFile file, Account ocAccount) {
769 if (ocAccount != null && (
770 mStorageManager == null ||
771 (mAccount != null && !mAccount.equals(ocAccount))
773 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
775 mAccount = ocAccount;
776 updateFileDetails(false);
782 * Interface to implement by any Activity that includes some instance of FileDetailFragment
784 * @author David A. Velasco
786 public interface ContainerActivity
extends TransferServiceGetter
{
789 * Callback method invoked when the detail fragment wants to notice its container
790 * activity about a relevant state the file shown by the fragment.
792 * Added to notify to FileDisplayActivity about the need of refresh the files list.
794 * Currently called when:
795 * - a download is started;
796 * - a rename is completed;
797 * - a deletion is completed;
798 * - the 'inSync' flag is changed;
800 public void onFileStateChanged();
805 public void onDismiss(EditNameDialog dialog) {
806 if (dialog.getResult()) {
807 String newFilename = dialog.getNewFilename();
808 Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
809 mLastRemoteOperation = new RenameFileOperation( mFile,
812 new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
813 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
814 mLastRemoteOperation.execute(wc, this, mHandler);
815 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
816 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
821 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
824 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
826 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
828 private final WeakReference
<ImageView
> mImageViewRef
;
834 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
836 public BitmapLoader(ImageView imageView
) {
837 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
841 @SuppressWarnings("deprecation")
842 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
844 protected Bitmap
doInBackground(String
... params
) {
845 Bitmap result
= null
;
846 if (params
.length
!= 1) return result
;
847 String storagePath
= params
[0];
849 // set desired options that will affect the size of the bitmap
850 BitmapFactory
.Options options
= new Options();
851 options
.inScaled
= true
;
852 options
.inPurgeable
= true
;
853 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
854 options
.inPreferQualityOverSpeed
= false
;
856 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
857 options
.inMutable
= false
;
859 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
860 options
.inJustDecodeBounds
= true
;
861 BitmapFactory
.decodeFile(storagePath
, options
);
863 int width
= options
.outWidth
;
864 int height
= options
.outHeight
;
866 if (width
>= 2048 || height
>= 2048) {
867 // try to scale down the image to save memory
868 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
869 options
.inSampleSize
= scale
;
871 Display display
= getActivity().getWindowManager().getDefaultDisplay();
872 Point size
= new Point();
874 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
875 display
.getSize(size
);
876 screenwidth
= size
.x
;
878 screenwidth
= display
.getWidth();
881 Log
.d(TAG
, "image width: " + width
+ ", screen width: " + screenwidth
);
883 if (width
> screenwidth
) {
884 // second try to scale down the image , this time depending upon the screen size; WTF...
885 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
886 options
.inSampleSize
= scale
;
889 // really load the bitmap
890 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
891 result
= BitmapFactory
.decodeFile(storagePath
, options
);
892 Log
.e(TAG
, "loaded width: " + options
.outWidth
+ ", loaded height: " + options
.outHeight
);
894 } catch (OutOfMemoryError e
) {
896 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
898 } catch (NoSuchFieldError e
) {
900 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
902 } catch (Throwable t
) {
904 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
910 protected void onPostExecute(Bitmap result
) {
911 if (result
!= null
&& mImageViewRef
!= null
) {
912 final ImageView imageView
= mImageViewRef
.get();
913 imageView
.setImageBitmap(result
);
921 * Helper method to test if an {@link OCFile} can be passed to a {@link FilePreviewFragment} to be previewed.
923 * @param file File to test if can be previewed.
924 * @return 'True' if the file can be handled by the fragment.
926 public static boolean canBePreviewed(OCFile file
) {
927 return (file
!= null
&& file
.isDown() &&
928 (file
.isAudio() || file
.isVideo() || file
.isImage()));
935 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
936 if (operation.equals(mLastRemoteOperation)) {
937 if (operation instanceof RemoveFileOperation) {
938 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
940 } else if (operation instanceof RenameFileOperation) {
941 onRenameFileOperationFinish((RenameFileOperation)operation, result);
943 } else if (operation instanceof SynchronizeFileOperation) {
944 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
951 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
952 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
953 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
955 if (result.isSuccess()) {
956 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
958 if (inDisplayActivity) {
960 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
961 transaction.replace(R.id.file_details_container, new FilePreviewFragment(null, null)); // empty FileDetailFragment
962 transaction.commit();
963 mContainerActivity.onFileStateChanged();
965 getActivity().finish();
969 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
971 if (result.isSslRecoverableException()) {
972 // TODO show the SSL warning dialog
977 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
978 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
979 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
981 if (result.isSuccess()) {
982 updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
983 mContainerActivity.onFileStateChanged();
986 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
987 Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
989 // TODO throw again the new rename dialog
991 Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
993 if (result.isSslRecoverableException()) {
994 // TODO show the SSL warning dialog
1000 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1001 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1002 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1004 if (!result.isSuccess()) {
1005 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1006 Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
1007 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, mFile);
1008 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
1012 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1016 if (mFile.isDown()) {
1017 setButtonsForDown();
1020 setButtonsForRemote();
1024 if (operation.transferWasRequested()) {
1025 mContainerActivity.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1026 // checking the service to see if the file is downloading results in FALSE
1028 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1030 if (mFile.isDown()) {
1031 setButtonsForDown();
1034 setButtonsForRemote();