Refactoring and clean-up of fragment for media previews
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewMediaFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
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 2 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.preview;
19
20 import java.io.File;
21 import java.util.ArrayList;
22 import java.util.List;
23
24 import android.accounts.Account;
25 import android.app.Activity;
26 import android.app.AlertDialog;
27 import android.content.ActivityNotFoundException;
28 import android.content.ComponentName;
29 import android.content.Context;
30 import android.content.DialogInterface;
31 import android.content.Intent;
32 import android.content.ServiceConnection;
33 import android.media.MediaPlayer;
34 import android.media.MediaPlayer.OnCompletionListener;
35 import android.media.MediaPlayer.OnErrorListener;
36 import android.media.MediaPlayer.OnPreparedListener;
37 import android.net.Uri;
38 import android.os.Bundle;
39 import android.os.Handler;
40 import android.os.IBinder;
41 import android.support.v4.app.FragmentTransaction;
42 import android.util.Log;
43 import android.view.LayoutInflater;
44 import android.view.MotionEvent;
45 import android.view.View;
46 import android.view.View.OnTouchListener;
47 import android.view.ViewGroup;
48 import android.webkit.MimeTypeMap;
49 import android.widget.ImageView;
50 import android.widget.MediaController;
51 import android.widget.Toast;
52 import android.widget.VideoView;
53
54 import com.actionbarsherlock.app.SherlockFragment;
55 import com.actionbarsherlock.view.Menu;
56 import com.actionbarsherlock.view.MenuInflater;
57 import com.actionbarsherlock.view.MenuItem;
58 import com.owncloud.android.datamodel.FileDataStorageManager;
59 import com.owncloud.android.datamodel.OCFile;
60 import com.owncloud.android.media.MediaService;
61 import com.owncloud.android.media.MediaServiceBinder;
62 import com.owncloud.android.network.OwnCloudClientUtils;
63 import com.owncloud.android.operations.OnRemoteOperationListener;
64 import com.owncloud.android.operations.RemoteOperation;
65 import com.owncloud.android.operations.RemoteOperationResult;
66 import com.owncloud.android.operations.RemoveFileOperation;
67 import com.owncloud.android.ui.activity.FileDetailActivity;
68 import com.owncloud.android.ui.activity.FileDisplayActivity;
69 import com.owncloud.android.ui.activity.TransferServiceGetter;
70 import com.owncloud.android.ui.fragment.ConfirmationDialogFragment;
71 import com.owncloud.android.ui.fragment.FileDetailFragment;
72 import com.owncloud.android.ui.fragment.FileFragment;
73 import com.owncloud.android.ui.fragment.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
74 import com.owncloud.android.ui.fragment.FileFragment.ContainerActivity;
75
76 import com.owncloud.android.R;
77 import eu.alefzero.webdav.WebdavClient;
78 import eu.alefzero.webdav.WebdavUtils;
79
80 /**
81 * This fragment shows a preview of a downloaded media file (audio or video).
82 *
83 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
84 *
85 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
86 *
87 * @author David A. Velasco
88 */
89 public class PreviewMediaFragment extends SherlockFragment implements
90 OnTouchListener , FileFragment,
91 ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener {
92
93 public static final String EXTRA_FILE = "FILE";
94 public static final String EXTRA_ACCOUNT = "ACCOUNT";
95 private static final String EXTRA_PLAY_POSITION = "PLAY_POSITION";
96
97 private View mView;
98 private OCFile mFile;
99 private Account mAccount;
100 private FileDataStorageManager mStorageManager;
101 private ImageView mImagePreview;
102 private VideoView mVideoPreview;
103 private int mSavedPlaybackPosition;
104
105 private Handler mHandler;
106 private RemoteOperation mLastRemoteOperation;
107
108 private MediaServiceBinder mMediaServiceBinder = null;
109 private MediaController mMediaController = null;
110 private MediaServiceConnection mMediaServiceConnection = null;
111 private VideoHelper mVideoHelper;
112
113 private static final String TAG = PreviewMediaFragment.class.getSimpleName();
114
115
116 /**
117 * Creates a fragment to preview a file.
118 *
119 * When 'fileToDetail' or 'ocAccount' are null
120 *
121 * @param fileToDetail An {@link OCFile} to preview in the fragment
122 * @param ocAccount An ownCloud account; needed to start downloads
123 */
124 public PreviewMediaFragment(OCFile fileToDetail, Account ocAccount) {
125 mFile = fileToDetail;
126 mAccount = ocAccount;
127 mSavedPlaybackPosition = 0;
128 mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
129 }
130
131
132 /**
133 * Creates an empty fragment for previews.
134 *
135 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
136 *
137 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
138 */
139 public PreviewMediaFragment() {
140 mFile = null;
141 mAccount = null;
142 mSavedPlaybackPosition = 0;
143 mStorageManager = null;
144 }
145
146
147 /**
148 * {@inheritDoc}
149 */
150 @Override
151 public void onCreate(Bundle savedInstanceState) {
152 super.onCreate(savedInstanceState);
153 mHandler = new Handler();
154 setHasOptionsMenu(true);
155 }
156
157
158 /**
159 * {@inheritDoc}
160 */
161 @Override
162 public View onCreateView(LayoutInflater inflater, ViewGroup container,
163 Bundle savedInstanceState) {
164 super.onCreateView(inflater, container, savedInstanceState);
165
166 mView = inflater.inflate(R.layout.file_preview, container, false);
167
168 mImagePreview = (ImageView)mView.findViewById(R.id.image_preview);
169 mImagePreview.setOnTouchListener(this);
170 mVideoPreview = (VideoView)mView.findViewById(R.id.video_preview);
171
172 //updateFileDetails(false);
173 return mView;
174 }
175
176
177 /**
178 * {@inheritDoc}
179 */
180 @Override
181 public void onAttach(Activity activity) {
182 super.onAttach(activity);
183 if (!(activity instanceof FileFragment.ContainerActivity))
184 throw new ClassCastException(activity.toString() + " must implement " + FileFragment.ContainerActivity.class.getSimpleName());
185 }
186
187
188 /**
189 * {@inheritDoc}
190 */
191 @Override
192 public void onActivityCreated(Bundle savedInstanceState) {
193 super.onActivityCreated(savedInstanceState);
194
195 mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
196 if (savedInstanceState != null) {
197 mFile = savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_FILE);
198 mAccount = savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_ACCOUNT);
199 mSavedPlaybackPosition = savedInstanceState.getInt(PreviewMediaFragment.EXTRA_PLAY_POSITION);
200
201 }
202 if (mFile == null) {
203 throw new IllegalStateException("Instanced with a NULL OCFile");
204 }
205 if (mAccount == null) {
206 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
207 }
208 if (!mFile.isDown()) {
209 throw new IllegalStateException("There is no local file to preview");
210 }
211 if (mFile.isVideo()) {
212 mVideoPreview.setVisibility(View.VISIBLE);
213 mImagePreview.setVisibility(View.GONE);
214 prepareVideo();
215
216 } else {
217 mVideoPreview.setVisibility(View.GONE);
218 mImagePreview.setVisibility(View.VISIBLE);
219 }
220
221 }
222
223
224 /**
225 * {@inheritDoc}
226 */
227 @Override
228 public void onSaveInstanceState(Bundle outState) {
229 super.onSaveInstanceState(outState);
230
231 outState.putParcelable(PreviewMediaFragment.EXTRA_FILE, mFile);
232 outState.putParcelable(PreviewMediaFragment.EXTRA_ACCOUNT, mAccount);
233
234 if (mVideoPreview.isPlaying()) {
235 outState.putInt(PreviewMediaFragment.EXTRA_PLAY_POSITION , mVideoPreview.getCurrentPosition());
236 }
237 }
238
239
240 @Override
241 public void onStart() {
242 super.onStart();
243
244 if (mFile != null) {
245 if (mFile.isAudio()) {
246 bindMediaService();
247
248 } else if (mFile.isVideo()) {
249 playVideo();
250 }
251 }
252 }
253
254
255 /**
256 * {@inheritDoc}
257 */
258 @Override
259 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
260 super.onCreateOptionsMenu(menu, inflater);
261
262 inflater.inflate(R.menu.file_actions_menu, menu);
263 List<Integer> toHide = new ArrayList<Integer>();
264
265 MenuItem item = null;
266 toHide.add(R.id.action_cancel_download);
267 toHide.add(R.id.action_cancel_upload);
268 toHide.add(R.id.action_download_file);
269 toHide.add(R.id.action_rename_file); // by now
270
271 for (int i : toHide) {
272 item = menu.findItem(i);
273 if (item != null) {
274 item.setVisible(false);
275 item.setEnabled(false);
276 }
277 }
278
279 }
280
281
282 /**
283 * {@inheritDoc}
284 */
285 @Override
286 public boolean onOptionsItemSelected(MenuItem item) {
287 switch (item.getItemId()) {
288 case R.id.action_open_file_with: {
289 openFile();
290 return true;
291 }
292 case R.id.action_remove_file: {
293 removeFile();
294 return true;
295 }
296 case R.id.action_see_details: {
297 seeDetails();
298 return true;
299 }
300
301 default:
302 return false;
303 }
304 }
305
306
307 private void seeDetails() {
308 stopPreview(false);
309 ((FileFragment.ContainerActivity)getActivity()).showFragmentWithDetails(mFile);
310 }
311
312
313 private void prepareVideo() {
314 // create helper to get more control on the playback
315 mVideoHelper = new VideoHelper();
316 mVideoPreview.setOnPreparedListener(mVideoHelper);
317 mVideoPreview.setOnCompletionListener(mVideoHelper);
318 mVideoPreview.setOnErrorListener(mVideoHelper);
319 }
320
321 private void playVideo() {
322 // load the video file in the video player ; when done, VideoHelper#onPrepared() will be called
323 mVideoPreview.setVideoPath(mFile.getStoragePath());
324
325 // create and prepare control panel for the user
326 mMediaController = new MediaController(getActivity());
327 mMediaController.setMediaPlayer(mVideoPreview);
328 mMediaController.setAnchorView(mVideoPreview);
329 mVideoPreview.setMediaController(mMediaController);
330 }
331
332
333 private class VideoHelper implements OnCompletionListener, OnPreparedListener, OnErrorListener {
334
335 /**
336 * Called when the file is ready to be played.
337 *
338 * Just starts the playback.
339 *
340 * @param mp {@link MediaPlayer} instance performing the playback.
341 */
342 @Override
343 public void onPrepared(MediaPlayer vp) {
344 mVideoPreview.seekTo(mSavedPlaybackPosition);
345 mVideoPreview.start();
346 mMediaController.show(MediaService.MEDIA_CONTROL_SHORT_LIFE);
347 }
348
349
350 /**
351 * Called when the file is finished playing.
352 *
353 * Finishes the activity.
354 *
355 * @param mp {@link MediaPlayer} instance performing the playback.
356 */
357 @Override
358 public void onCompletion(MediaPlayer mp) {
359 // nothing, right now
360 }
361
362
363 /**
364 * Called when an error in playback occurs.
365 *
366 * @param mp {@link MediaPlayer} instance performing the playback.
367 * @param what Type of error
368 * @param extra Extra code specific to the error
369 */
370 @Override
371 public boolean onError(MediaPlayer mp, int what, int extra) {
372 Log.e(TAG, "Error in video playback, what = " + what + ", extra = " + extra);
373
374 if (mMediaController != null) {
375 mMediaController.hide();
376 }
377
378 if (mVideoPreview.getWindowToken() != null) {
379 String message = MediaService.getMessageForMediaError(getActivity(), what, extra);
380 new AlertDialog.Builder(getActivity())
381 .setMessage(message)
382 .setPositiveButton(android.R.string.VideoView_error_button,
383 new DialogInterface.OnClickListener() {
384 public void onClick(DialogInterface dialog, int whichButton) {
385 dialog.dismiss();
386 VideoHelper.this.onCompletion(null);
387 }
388 })
389 .setCancelable(false)
390 .show();
391 }
392 return true;
393 }
394
395 }
396
397
398 @Override
399 public void onResume() {
400 super.onResume();
401 /*
402 mDownloadFinishReceiver = new DownloadFinishReceiver();
403 IntentFilter filter = new IntentFilter(
404 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
405 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
406
407 mUploadFinishReceiver = new UploadFinishReceiver();
408 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
409 getActivity().registerReceiver(mUploadFinishReceiver, filter);
410 */
411
412 }
413
414
415 @Override
416 public void onPause() {
417 super.onPause();
418 /*
419 if (mVideoPreview.getVisibility() == View.VISIBLE) {
420 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
421 }*/
422 /*
423 getActivity().unregisterReceiver(mDownloadFinishReceiver);
424 mDownloadFinishReceiver = null;
425
426 getActivity().unregisterReceiver(mUploadFinishReceiver);
427 mUploadFinishReceiver = null;
428 */
429 }
430
431
432 @Override
433 public void onStop() {
434 super.onStop();
435 if (mMediaServiceConnection != null) {
436 Log.d(TAG, "Unbinding from MediaService ...");
437 if (mMediaServiceBinder != null && mMediaController != null) {
438 mMediaServiceBinder.unregisterMediaController(mMediaController);
439 }
440 getActivity().unbindService(mMediaServiceConnection);
441 mMediaServiceConnection = null;
442 mMediaServiceBinder = null;
443 if (mMediaController != null) {
444 mMediaController.hide();
445 mMediaController = null;
446 }
447 }
448 }
449
450 @Override
451 public void onDestroy() {
452 super.onDestroy();
453 }
454
455 /*
456 @Override
457 public View getView() {
458 return super.getView() == null ? mView : super.getView();
459 }
460 */
461
462 /*
463 @Override
464 public void onClick(View v) {
465 switch (v.getId()) {
466 case R.id.fdDownloadBtn: {
467 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
468 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
469 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
470 downloaderBinder.cancel(mAccount, mFile);
471 if (mFile.isDown()) {
472 setButtonsForDown();
473 } else {
474 setButtonsForRemote();
475 }
476
477 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
478 uploaderBinder.cancel(mAccount, mFile);
479 if (!mFile.fileExists()) {
480 // TODO make something better
481 if (getActivity() instanceof FileDisplayActivity) {
482 // double pane
483 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
484 transaction.replace(R.id.file_details_container, new PreviewMediaFragment(null, null), FTAG); // empty FileDetailFragment
485 transaction.commit();
486 mContainerActivity.onFileStateChanged();
487 } else {
488 getActivity().finish();
489 }
490
491 } else if (mFile.isDown()) {
492 setButtonsForDown();
493 } else {
494 setButtonsForRemote();
495 }
496
497 } else {
498 mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());
499 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
500 mLastRemoteOperation.execute(wc, this, mHandler);
501
502 // update ui
503 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
504 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
505 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
506
507 }
508 break;
509 }
510 case R.id.fdKeepInSync: {
511 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
512 mFile.setKeepInSync(cb.isChecked());
513 mStorageManager.saveFile(mFile);
514
515 /// register the OCFile instance in the observer service to monitor local updates;
516 /// if necessary, the file is download
517 Intent intent = new Intent(getActivity().getApplicationContext(),
518 FileObserverService.class);
519 intent.putExtra(FileObserverService.KEY_FILE_CMD,
520 (cb.isChecked()?
521 FileObserverService.CMD_ADD_OBSERVED_FILE:
522 FileObserverService.CMD_DEL_OBSERVED_FILE));
523 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
524 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
525 Log.e(TAG, "starting observer service");
526 getActivity().startService(intent);
527
528 if (mFile.keepInSync()) {
529 onClick(getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
530 }
531 break;
532 }
533 case R.id.fdRenameBtn: {
534 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), mFile.getFileName(), this);
535 dialog.show(getFragmentManager(), "nameeditdialog");
536 break;
537 }
538 case R.id.fdRemoveBtn: {
539 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
540 R.string.confirmation_remove_alert,
541 new String[]{mFile.getFileName()},
542 mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
543 mFile.isDown() ? R.string.confirmation_remove_local : -1,
544 R.string.common_cancel);
545 confDialog.setOnConfirmationListener(this);
546 mCurrentDialog = confDialog;
547 mCurrentDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
548 break;
549 }
550 case R.id.fdOpenBtn: {
551 openFile();
552 break;
553 }
554 default:
555 Log.e(TAG, "Incorrect view clicked!");
556 }
557
558 }
559 */
560
561
562 @Override
563 public boolean onTouch(View v, MotionEvent event) {
564 if (event.getAction() == MotionEvent.ACTION_DOWN) {
565 if (v == mImagePreview &&
566 mMediaServiceBinder != null && mFile.isAudio() && mMediaServiceBinder.isPlaying(mFile)) {
567 toggleMediaController(MediaService.MEDIA_CONTROL_PERMANENT);
568 return true;
569
570 } else if (v == mVideoPreview) {
571 toggleMediaController(MediaService.MEDIA_CONTROL_SHORT_LIFE);
572 return true;
573 }
574 }
575 return false;
576 }
577
578
579 private void toggleMediaController(int time) {
580 if (mMediaController.isShowing()) {
581 mMediaController.hide();
582 } else {
583 mMediaController.show(time);
584 }
585 }
586
587
588 private void playAudio() {
589 if (!mMediaServiceBinder.isPlaying(mFile)) {
590 Log.d(TAG, "starting playback of " + mFile.getStoragePath());
591 mMediaServiceBinder.start(mAccount, mFile);
592
593 } else {
594 if (!mMediaServiceBinder.isPlaying()) {
595 mMediaServiceBinder.start();
596 }
597 if (!mMediaController.isShowing() && isVisible()) {
598 mMediaController.show(MediaService.MEDIA_CONTROL_PERMANENT);
599 // TODO - fix strange bug; steps to trigger :
600 // 1. remove the "isVisible()" control
601 // 2. start the app and preview an audio file
602 // 3. exit from the app (home button, for instance) while the audio file is still being played
603 // 4. go to notification bar and click on the "ownCloud music app" notification
604 // PUM!
605 }
606 }
607 }
608
609
610 private void bindMediaService() {
611 Log.d(TAG, "Binding to MediaService...");
612 if (mMediaServiceConnection == null) {
613 mMediaServiceConnection = new MediaServiceConnection();
614 }
615 getActivity().bindService( new Intent(getActivity(),
616 MediaService.class),
617 mMediaServiceConnection,
618 Context.BIND_AUTO_CREATE);
619 // follow the flow in MediaServiceConnection#onServiceConnected(...)
620 }
621
622 /** Defines callbacks for service binding, passed to bindService() */
623 private class MediaServiceConnection implements ServiceConnection {
624
625 @Override
626 public void onServiceConnected(ComponentName component, IBinder service) {
627 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
628 Log.d(TAG, "Media service connected");
629 mMediaServiceBinder = (MediaServiceBinder) service;
630 if (mMediaServiceBinder != null) {
631 if (mMediaController == null) {
632 mMediaController = new MediaController(getSherlockActivity());
633 }
634 prepareMediaController();
635 playAudio(); // do not wait for the touch of nobody to play audio
636
637 Log.d(TAG, "Successfully bound to MediaService, MediaController ready");
638
639 } else {
640 Log.e(TAG, "Unexpected response from MediaService while binding");
641 }
642 }
643 }
644
645 private void prepareMediaController() {
646 mMediaServiceBinder.registerMediaController(mMediaController);
647 mMediaController.setMediaPlayer(mMediaServiceBinder);
648 mMediaController.setAnchorView(getView());
649 mMediaController.setEnabled(mMediaServiceBinder.isInPlaybackState());
650 }
651
652 @Override
653 public void onServiceDisconnected(ComponentName component) {
654 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
655 Log.e(TAG, "Media service suddenly disconnected");
656 if (mMediaController != null) {
657 mMediaController.hide();
658 mMediaController.setMediaPlayer(null);
659 mMediaController = null;
660 }
661 mMediaServiceBinder = null;
662 mMediaServiceConnection = null;
663 }
664 }
665 }
666
667
668
669 /**
670 * Opens the previewed file with an external application.
671 *
672 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
673 * we should get a list of available apps for MIME tpye in the server and join it with the list of
674 * available apps for the MIME type known from the file extension, to let the user choose
675 */
676 private void openFile() {
677 stopPreview(true);
678 String storagePath = mFile.getStoragePath();
679 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
680 try {
681 Intent i = new Intent(Intent.ACTION_VIEW);
682 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
683 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
684 startActivity(i);
685
686 } catch (Throwable t) {
687 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
688 boolean toastIt = true;
689 String mimeType = "";
690 try {
691 Intent i = new Intent(Intent.ACTION_VIEW);
692 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
693 if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
694 if (mimeType != null) {
695 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
696 } else {
697 // desperate try
698 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*-/*");
699 }
700 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
701 startActivity(i);
702 toastIt = false;
703 }
704
705 } catch (IndexOutOfBoundsException e) {
706 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
707
708 } catch (ActivityNotFoundException e) {
709 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
710
711 } catch (Throwable th) {
712 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
713
714 } finally {
715 if (toastIt) {
716 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
717 }
718 }
719
720 }
721 finish();
722 }
723
724 /**
725 * Starts a the removal of the previewed file.
726 *
727 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
728 * depending upon the user selection in the dialog.
729 */
730 private void removeFile() {
731 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
732 R.string.confirmation_remove_alert,
733 new String[]{mFile.getFileName()},
734 R.string.confirmation_remove_remote_and_local,
735 R.string.confirmation_remove_local,
736 R.string.common_cancel);
737 confDialog.setOnConfirmationListener(this);
738 confDialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
739 }
740
741
742 /**
743 * Performs the removal of the previewed file, both locally and in the server.
744 */
745 @Override
746 public void onConfirmation(String callerTag) {
747 if (mStorageManager.getFileById(mFile.getFileId()) != null) { // check that the file is still there;
748 stopPreview(true);
749 mLastRemoteOperation = new RemoveFileOperation( mFile, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
750 true,
751 mStorageManager);
752 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
753 mLastRemoteOperation.execute(wc, this, mHandler);
754
755 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
756 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
757 }
758 }
759
760
761 /**
762 * Removes the file from local storage
763 */
764 @Override
765 public void onNeutral(String callerTag) {
766 // TODO this code should be made in a secondary thread,
767 if (mFile.isDown()) { // checks it is still there
768 stopPreview(true);
769 File f = new File(mFile.getStoragePath());
770 f.delete();
771 mFile.setStoragePath(null);
772 mStorageManager.saveFile(mFile);
773 finish();
774 }
775 }
776
777 /**
778 * User cancelled the removal action.
779 */
780 @Override
781 public void onCancel(String callerTag) {
782 // nothing to do here
783 }
784
785
786 /**
787 * {@inheritDoc}
788 */
789 public OCFile getFile(){
790 return mFile;
791 }
792
793 /*
794 /**
795 * Use this method to signal this Activity that it shall update its view.
796 *
797 * @param file : An {@link OCFile}
798 *-/
799 public void updateFileDetails(OCFile file, Account ocAccount) {
800 mFile = file;
801 if (ocAccount != null && (
802 mStorageManager == null ||
803 (mAccount != null && !mAccount.equals(ocAccount))
804 )) {
805 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
806 }
807 mAccount = ocAccount;
808 updateFileDetails(false);
809 }
810 */
811
812
813 /**
814 * Interface to implement by any Activity that includes some instance of FileDetailFragment
815 *
816 * @author David A. Velasco
817 */
818 public interface ContainerActivity extends TransferServiceGetter {
819
820 /**
821 * Callback method invoked when the detail fragment wants to notice its container
822 * activity about a relevant state the file shown by the fragment.
823 *
824 * Added to notify to FileDisplayActivity about the need of refresh the files list.
825 *
826 * Currently called when:
827 * - a download is started;
828 * - a rename is completed;
829 * - a deletion is completed;
830 * - the 'inSync' flag is changed;
831 */
832 public void onFileStateChanged();
833
834 }
835
836 /**
837 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment} to be previewed.
838 *
839 * @param file File to test if can be previewed.
840 * @return 'True' if the file can be handled by the fragment.
841 */
842 public static boolean canBePreviewed(OCFile file) {
843 return (file != null && (file.isAudio() || file.isVideo()));
844 }
845
846 /**
847 * {@inheritDoc}
848 */
849 @Override
850 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
851 if (operation.equals(mLastRemoteOperation)) {
852 if (operation instanceof RemoveFileOperation) {
853 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
854 }
855 }
856 }
857
858 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
859 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
860 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
861
862 if (result.isSuccess()) {
863 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
864 msg.show();
865 finish();
866
867 } else {
868 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
869 msg.show();
870 if (result.isSslRecoverableException()) {
871 // TODO show the SSL warning dialog
872 }
873 }
874 }
875
876 private void stopPreview(boolean stopAudio) {
877 if (mMediaController != null) {
878 mMediaController.hide();
879 }
880 if (mFile.isAudio() && stopAudio) {
881 mMediaServiceBinder.pause();
882
883 } else if (mFile.isVideo()) {
884 mVideoPreview.stopPlayback();
885 }
886 }
887
888
889
890 /**
891 * Finishes the preview
892 */
893 private void finish() {
894 Activity container = getActivity();
895 if (container instanceof FileDisplayActivity) {
896 // double pane
897 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
898 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
899 transaction.commit();
900 ((FileFragment.ContainerActivity)container).onFileStateChanged();
901 } else {
902 container.finish();
903 }
904 }
905
906 }