d2b5e50985705c428e02138bd2a179d96a3c7293
[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 version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17 package com.owncloud.android.ui.preview;
18
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import android.accounts.Account;
23 import android.app.Activity;
24 import android.app.AlertDialog;
25 import android.content.ActivityNotFoundException;
26 import android.content.ComponentName;
27 import android.content.Context;
28 import android.content.DialogInterface;
29 import android.content.Intent;
30 import android.content.ServiceConnection;
31 import android.content.res.Configuration;
32 import android.media.MediaPlayer;
33 import android.media.MediaPlayer.OnCompletionListener;
34 import android.media.MediaPlayer.OnErrorListener;
35 import android.media.MediaPlayer.OnPreparedListener;
36 import android.net.Uri;
37 import android.os.Build;
38 import android.os.Bundle;
39 import android.os.Handler;
40 import android.os.IBinder;
41 import android.view.LayoutInflater;
42 import android.view.MotionEvent;
43 import android.view.View;
44 import android.view.View.OnTouchListener;
45 import android.view.ViewGroup;
46 import android.webkit.MimeTypeMap;
47 import android.widget.ImageView;
48 import android.widget.Toast;
49 import android.widget.VideoView;
50
51 import com.actionbarsherlock.view.Menu;
52 import com.actionbarsherlock.view.MenuInflater;
53 import com.actionbarsherlock.view.MenuItem;
54 import com.owncloud.android.R;
55 import com.owncloud.android.datamodel.FileDataStorageManager;
56 import com.owncloud.android.datamodel.OCFile;
57 import com.owncloud.android.media.MediaControlView;
58 import com.owncloud.android.media.MediaService;
59 import com.owncloud.android.media.MediaServiceBinder;
60 import com.owncloud.android.lib.common.network.WebdavUtils;
61 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
62 import com.owncloud.android.lib.common.operations.RemoteOperation;
63 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
64 import com.owncloud.android.operations.RemoveFileOperation;
65 import com.owncloud.android.ui.activity.FileActivity;
66 import com.owncloud.android.ui.activity.FileDisplayActivity;
67 import com.owncloud.android.ui.fragment.ConfirmationDialogFragment;
68 import com.owncloud.android.ui.fragment.FileFragment;
69 import com.owncloud.android.utils.Log_OC;
70
71
72 /**
73 * This fragment shows a preview of a downloaded media file (audio or video).
74 *
75 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
76 *
77 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
78 *
79 * @author David A. Velasco
80 */
81 public class PreviewMediaFragment extends FileFragment implements
82 OnTouchListener,
83 ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener {
84
85 public static final String EXTRA_FILE = "FILE";
86 public static final String EXTRA_ACCOUNT = "ACCOUNT";
87 private static final String EXTRA_PLAY_POSITION = "PLAY_POSITION";
88 private static final String EXTRA_PLAYING = "PLAYING";
89
90 private View mView;
91 private Account mAccount;
92 private FileDataStorageManager mStorageManager;
93 private ImageView mImagePreview;
94 private VideoView mVideoPreview;
95 private int mSavedPlaybackPosition;
96
97 private Handler mHandler;
98 private RemoteOperation mLastRemoteOperation;
99
100 private MediaServiceBinder mMediaServiceBinder = null;
101 private MediaControlView mMediaController = null;
102 private MediaServiceConnection mMediaServiceConnection = null;
103 private VideoHelper mVideoHelper;
104 private boolean mAutoplay;
105 public boolean mPrepared;
106
107 private static final String TAG = PreviewMediaFragment.class.getSimpleName();
108
109
110 /**
111 * Creates a fragment to preview a file.
112 *
113 * When 'fileToDetail' or 'ocAccount' are null
114 *
115 * @param fileToDetail An {@link OCFile} to preview in the fragment
116 * @param ocAccount An ownCloud account; needed to start downloads
117 */
118 public PreviewMediaFragment(OCFile fileToDetail, Account ocAccount, int startPlaybackPosition, boolean autoplay) {
119 super(fileToDetail);
120 mAccount = ocAccount;
121 mSavedPlaybackPosition = startPlaybackPosition;
122 mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
123 mAutoplay = autoplay;
124 }
125
126
127 /**
128 * Creates an empty fragment for previews.
129 *
130 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
131 *
132 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
133 */
134 public PreviewMediaFragment() {
135 super();
136 mAccount = null;
137 mSavedPlaybackPosition = 0;
138 mStorageManager = null;
139 mAutoplay = true;
140 }
141
142
143 /**
144 * {@inheritDoc}
145 */
146 @Override
147 public void onCreate(Bundle savedInstanceState) {
148 super.onCreate(savedInstanceState);
149 mHandler = new Handler();
150 setHasOptionsMenu(true);
151 }
152
153
154 /**
155 * {@inheritDoc}
156 */
157 @Override
158 public View onCreateView(LayoutInflater inflater, ViewGroup container,
159 Bundle savedInstanceState) {
160 super.onCreateView(inflater, container, savedInstanceState);
161 Log_OC.e(TAG, "onCreateView");
162
163
164 mView = inflater.inflate(R.layout.file_preview, container, false);
165
166 mImagePreview = (ImageView)mView.findViewById(R.id.image_preview);
167 mVideoPreview = (VideoView)mView.findViewById(R.id.video_preview);
168 mVideoPreview.setOnTouchListener(this);
169
170 mMediaController = (MediaControlView)mView.findViewById(R.id.media_controller);
171
172 return mView;
173 }
174
175
176 /**
177 * {@inheritDoc}
178 */
179 @Override
180 public void onAttach(Activity activity) {
181 super.onAttach(activity);
182 Log_OC.e(TAG, "onAttach");
183
184 if (!(activity instanceof FileFragment.ContainerActivity))
185 throw new ClassCastException(activity.toString() + " must implement " + FileFragment.ContainerActivity.class.getSimpleName());
186 }
187
188
189 /**
190 * {@inheritDoc}
191 */
192 @Override
193 public void onActivityCreated(Bundle savedInstanceState) {
194 super.onActivityCreated(savedInstanceState);
195 Log_OC.e(TAG, "onActivityCreated");
196
197 mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
198 if (savedInstanceState != null) {
199 setFile((OCFile)savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_FILE));
200 mAccount = savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_ACCOUNT);
201 mSavedPlaybackPosition = savedInstanceState.getInt(PreviewMediaFragment.EXTRA_PLAY_POSITION);
202 mAutoplay = savedInstanceState.getBoolean(PreviewMediaFragment.EXTRA_PLAYING);
203
204 }
205 OCFile file = getFile();
206 if (file == null) {
207 throw new IllegalStateException("Instanced with a NULL OCFile");
208 }
209 if (mAccount == null) {
210 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
211 }
212 if (!file.isDown()) {
213 throw new IllegalStateException("There is no local file to preview");
214 }
215 if (file.isVideo()) {
216 mVideoPreview.setVisibility(View.VISIBLE);
217 mImagePreview.setVisibility(View.GONE);
218 prepareVideo();
219
220 } else {
221 mVideoPreview.setVisibility(View.GONE);
222 mImagePreview.setVisibility(View.VISIBLE);
223 }
224
225 }
226
227
228 /**
229 * {@inheritDoc}
230 */
231 @Override
232 public void onSaveInstanceState(Bundle outState) {
233 super.onSaveInstanceState(outState);
234 Log_OC.e(TAG, "onSaveInstanceState");
235
236 outState.putParcelable(PreviewMediaFragment.EXTRA_FILE, getFile());
237 outState.putParcelable(PreviewMediaFragment.EXTRA_ACCOUNT, mAccount);
238
239 if (getFile().isVideo()) {
240 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
241 mAutoplay = mVideoPreview.isPlaying();
242 outState.putInt(PreviewMediaFragment.EXTRA_PLAY_POSITION , mSavedPlaybackPosition);
243 outState.putBoolean(PreviewMediaFragment.EXTRA_PLAYING , mAutoplay);
244 } else {
245 outState.putInt(PreviewMediaFragment.EXTRA_PLAY_POSITION , mMediaServiceBinder.getCurrentPosition());
246 outState.putBoolean(PreviewMediaFragment.EXTRA_PLAYING , mMediaServiceBinder.isPlaying());
247 }
248 }
249
250
251 @Override
252 public void onStart() {
253 super.onStart();
254 Log_OC.e(TAG, "onStart");
255
256 OCFile file = getFile();
257 if (file != null) {
258 if (file.isAudio()) {
259 bindMediaService();
260
261 } else if (file.isVideo()) {
262 stopAudio();
263 playVideo();
264 }
265 }
266 }
267
268
269 private void stopAudio() {
270 Intent i = new Intent(getSherlockActivity(), MediaService.class);
271 i.setAction(MediaService.ACTION_STOP_ALL);
272 getSherlockActivity().startService(i);
273 }
274
275
276 /**
277 * {@inheritDoc}
278 */
279 @Override
280 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
281 super.onCreateOptionsMenu(menu, inflater);
282
283 inflater.inflate(R.menu.file_actions_menu, menu);
284 List<Integer> toHide = new ArrayList<Integer>();
285
286 MenuItem item = null;
287 toHide.add(R.id.action_cancel_download);
288 toHide.add(R.id.action_cancel_upload);
289 toHide.add(R.id.action_download_file);
290 toHide.add(R.id.action_sync_file);
291 toHide.add(R.id.action_rename_file); // by now
292
293 // Options shareLink
294 if (!getFile().isShareByLink()) {
295 toHide.add(R.id.action_unshare_file);
296 }
297
298 for (int i : toHide) {
299 item = menu.findItem(i);
300 if (item != null) {
301 item.setVisible(false);
302 item.setEnabled(false);
303 }
304 }
305
306 }
307
308
309 /**
310 * {@inheritDoc}
311 */
312 @Override
313 public void onPrepareOptionsMenu(Menu menu) {
314 super.onPrepareOptionsMenu(menu);
315
316 MenuItem item = menu.findItem(R.id.action_unshare_file);
317 // Options shareLink
318 if (!getFile().isShareByLink()) {
319 item.setVisible(false);
320 item.setEnabled(false);
321 } else {
322 item.setVisible(true);
323 item.setEnabled(true);
324 }
325 }
326
327
328 /**
329 * {@inheritDoc}
330 */
331 @Override
332 public boolean onOptionsItemSelected(MenuItem item) {
333 switch (item.getItemId()) {
334 case R.id.action_share_file: {
335 shareFileWithLink();
336 return true;
337 }
338 case R.id.action_unshare_file: {
339 unshareFileWithLink();
340 return true;
341 }
342 case R.id.action_open_file_with: {
343 openFile();
344 return true;
345 }
346 case R.id.action_remove_file: {
347 removeFile();
348 return true;
349 }
350 case R.id.action_see_details: {
351 seeDetails();
352 return true;
353 }
354 case R.id.action_send_file: {
355 sendFile();
356 }
357
358 default:
359 return false;
360 }
361 }
362
363
364
365 /**
366 * Update the file of the fragment with file value
367 * @param file
368 */
369 public void updateFile(OCFile file){
370 setFile(file);
371 }
372
373 private void unshareFileWithLink() {
374 stopPreview(false);
375 FileActivity activity = (FileActivity)((FileFragment.ContainerActivity)getActivity());
376 activity.getFileOperationsHelper().unshareFileWithLink(getFile(), activity);
377 }
378
379 private void shareFileWithLink() {
380 stopPreview(false);
381 FileActivity activity = (FileActivity)((FileFragment.ContainerActivity)getActivity());
382 activity.getFileOperationsHelper().shareFileWithLink(getFile(), activity);
383
384 }
385
386 private void sendFile() {
387 stopPreview(false);
388 FileActivity activity = (FileActivity)((FileFragment.ContainerActivity)getActivity());
389 activity.getFileOperationsHelper().sendDownloadedFile(getFile(), activity);
390
391 }
392
393 private void seeDetails() {
394 stopPreview(false);
395 ((FileFragment.ContainerActivity)getActivity()).showDetails(getFile());
396 }
397
398
399 private void prepareVideo() {
400 // create helper to get more control on the playback
401 mVideoHelper = new VideoHelper();
402 mVideoPreview.setOnPreparedListener(mVideoHelper);
403 mVideoPreview.setOnCompletionListener(mVideoHelper);
404 mVideoPreview.setOnErrorListener(mVideoHelper);
405 }
406
407 private void playVideo() {
408 // create and prepare control panel for the user
409 mMediaController.setMediaPlayer(mVideoPreview);
410
411 // load the video file in the video player ; when done, VideoHelper#onPrepared() will be called
412 mVideoPreview.setVideoPath(getFile().getStoragePath());
413 }
414
415
416 private class VideoHelper implements OnCompletionListener, OnPreparedListener, OnErrorListener {
417
418 /**
419 * Called when the file is ready to be played.
420 *
421 * Just starts the playback.
422 *
423 * @param mp {@link MediaPlayer} instance performing the playback.
424 */
425 @Override
426 public void onPrepared(MediaPlayer vp) {
427 Log_OC.e(TAG, "onPrepared");
428 mVideoPreview.seekTo(mSavedPlaybackPosition);
429 if (mAutoplay) {
430 mVideoPreview.start();
431 }
432 mMediaController.setEnabled(true);
433 mMediaController.updatePausePlay();
434 mPrepared = true;
435 }
436
437
438 /**
439 * Called when the file is finished playing.
440 *
441 * Finishes the activity.
442 *
443 * @param mp {@link MediaPlayer} instance performing the playback.
444 */
445 @Override
446 public void onCompletion(MediaPlayer mp) {
447 Log_OC.e(TAG, "completed");
448 if (mp != null) {
449 mVideoPreview.seekTo(0);
450 // next lines are necessary to work around undesired video loops
451 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD) {
452 mVideoPreview.pause();
453
454 } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD_MR1) {
455 // mVideePreview.pause() is not enough
456
457 mMediaController.setEnabled(false);
458 mVideoPreview.stopPlayback();
459 mAutoplay = false;
460 mSavedPlaybackPosition = 0;
461 mVideoPreview.setVideoPath(getFile().getStoragePath());
462 }
463 } // else : called from onError()
464 mMediaController.updatePausePlay();
465 }
466
467
468 /**
469 * Called when an error in playback occurs.
470 *
471 * @param mp {@link MediaPlayer} instance performing the playback.
472 * @param what Type of error
473 * @param extra Extra code specific to the error
474 */
475 @Override
476 public boolean onError(MediaPlayer mp, int what, int extra) {
477 if (mVideoPreview.getWindowToken() != null) {
478 String message = MediaService.getMessageForMediaError(getActivity(), what, extra);
479 new AlertDialog.Builder(getActivity())
480 .setMessage(message)
481 .setPositiveButton(android.R.string.VideoView_error_button,
482 new DialogInterface.OnClickListener() {
483 public void onClick(DialogInterface dialog, int whichButton) {
484 dialog.dismiss();
485 VideoHelper.this.onCompletion(null);
486 }
487 })
488 .setCancelable(false)
489 .show();
490 }
491 return true;
492 }
493
494 }
495
496
497 @Override
498 public void onPause() {
499 super.onPause();
500 Log_OC.e(TAG, "onPause");
501 }
502
503 @Override
504 public void onResume() {
505 super.onResume();
506 Log_OC.e(TAG, "onResume");
507 }
508
509 @Override
510 public void onDestroy() {
511 super.onDestroy();
512 Log_OC.e(TAG, "onDestroy");
513 }
514
515 @Override
516 public void onStop() {
517 Log_OC.e(TAG, "onStop");
518 super.onStop();
519
520 mPrepared = false;
521 if (mMediaServiceConnection != null) {
522 Log_OC.d(TAG, "Unbinding from MediaService ...");
523 if (mMediaServiceBinder != null && mMediaController != null) {
524 mMediaServiceBinder.unregisterMediaController(mMediaController);
525 }
526 getActivity().unbindService(mMediaServiceConnection);
527 mMediaServiceConnection = null;
528 mMediaServiceBinder = null;
529 }
530 }
531
532 @Override
533 public boolean onTouch(View v, MotionEvent event) {
534 if (event.getAction() == MotionEvent.ACTION_DOWN && v == mVideoPreview) {
535 startFullScreenVideo();
536 return true;
537 }
538 return false;
539 }
540
541
542 private void startFullScreenVideo() {
543 Intent i = new Intent(getActivity(), PreviewVideoActivity.class);
544 i.putExtra(FileActivity.EXTRA_ACCOUNT, mAccount);
545 i.putExtra(FileActivity.EXTRA_FILE, getFile());
546 i.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, mVideoPreview.isPlaying());
547 mVideoPreview.pause();
548 i.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, mVideoPreview.getCurrentPosition());
549 startActivityForResult(i, 0);
550 }
551
552 @Override
553 public void onConfigurationChanged (Configuration newConfig) {
554 Log_OC.e(TAG, "onConfigurationChanged " + this);
555 }
556
557 @Override
558 public void onActivityResult (int requestCode, int resultCode, Intent data) {
559 Log_OC.e(TAG, "onActivityResult " + this);
560 super.onActivityResult(requestCode, resultCode, data);
561 if (resultCode == Activity.RESULT_OK) {
562 mSavedPlaybackPosition = data.getExtras().getInt(PreviewVideoActivity.EXTRA_START_POSITION);
563 mAutoplay = data.getExtras().getBoolean(PreviewVideoActivity.EXTRA_AUTOPLAY);
564 }
565 }
566
567
568 private void playAudio() {
569 OCFile file = getFile();
570 if (!mMediaServiceBinder.isPlaying(file)) {
571 Log_OC.d(TAG, "starting playback of " + file.getStoragePath());
572 mMediaServiceBinder.start(mAccount, file, mAutoplay, mSavedPlaybackPosition);
573
574 } else {
575 if (!mMediaServiceBinder.isPlaying() && mAutoplay) {
576 mMediaServiceBinder.start();
577 mMediaController.updatePausePlay();
578 }
579 }
580 }
581
582
583 private void bindMediaService() {
584 Log_OC.d(TAG, "Binding to MediaService...");
585 if (mMediaServiceConnection == null) {
586 mMediaServiceConnection = new MediaServiceConnection();
587 }
588 getActivity().bindService( new Intent(getActivity(),
589 MediaService.class),
590 mMediaServiceConnection,
591 Context.BIND_AUTO_CREATE);
592 // follow the flow in MediaServiceConnection#onServiceConnected(...)
593 }
594
595 /** Defines callbacks for service binding, passed to bindService() */
596 private class MediaServiceConnection implements ServiceConnection {
597
598 @Override
599 public void onServiceConnected(ComponentName component, IBinder service) {
600 if (getActivity() != null) {
601 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
602 Log_OC.d(TAG, "Media service connected");
603 mMediaServiceBinder = (MediaServiceBinder) service;
604 if (mMediaServiceBinder != null) {
605 prepareMediaController();
606 playAudio(); // do not wait for the touch of nobody to play audio
607
608 Log_OC.d(TAG, "Successfully bound to MediaService, MediaController ready");
609
610 } else {
611 Log_OC.e(TAG, "Unexpected response from MediaService while binding");
612 }
613 }
614 }
615 }
616
617 private void prepareMediaController() {
618 mMediaServiceBinder.registerMediaController(mMediaController);
619 if (mMediaController != null) {
620 mMediaController.setMediaPlayer(mMediaServiceBinder);
621 mMediaController.setEnabled(true);
622 mMediaController.updatePausePlay();
623 }
624 }
625
626 @Override
627 public void onServiceDisconnected(ComponentName component) {
628 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
629 Log_OC.e(TAG, "Media service suddenly disconnected");
630 if (mMediaController != null) {
631 mMediaController.setMediaPlayer(null);
632 } else {
633 Toast.makeText(getActivity(), "No media controller to release when disconnected from media service", Toast.LENGTH_SHORT).show();
634 }
635 mMediaServiceBinder = null;
636 mMediaServiceConnection = null;
637 }
638 }
639 }
640
641
642
643 /**
644 * Opens the previewed file with an external application.
645 *
646 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
647 * we should get a list of available apps for MIME tpye in the server and join it with the list of
648 * available apps for the MIME type known from the file extension, to let the user choose
649 */
650 private void openFile() {
651 OCFile file = getFile();
652 stopPreview(true);
653 String storagePath = file.getStoragePath();
654 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
655 try {
656 Intent i = new Intent(Intent.ACTION_VIEW);
657 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), file.getMimetype());
658 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
659 startActivity(i);
660
661 } catch (Throwable t) {
662 Log_OC.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + file.getMimetype());
663 boolean toastIt = true;
664 String mimeType = "";
665 try {
666 Intent i = new Intent(Intent.ACTION_VIEW);
667 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
668 if (mimeType == null || !mimeType.equals(file.getMimetype())) {
669 if (mimeType != null) {
670 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
671 } else {
672 // desperate try
673 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*-/*");
674 }
675 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
676 startActivity(i);
677 toastIt = false;
678 }
679
680 } catch (IndexOutOfBoundsException e) {
681 Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
682
683 } catch (ActivityNotFoundException e) {
684 Log_OC.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
685
686 } catch (Throwable th) {
687 Log_OC.e(TAG, "Unexpected problem when opening: " + storagePath, th);
688
689 } finally {
690 if (toastIt) {
691 Toast.makeText(getActivity(), "There is no application to handle file " + file.getFileName(), Toast.LENGTH_SHORT).show();
692 }
693 }
694
695 }
696 finish();
697 }
698
699 /**
700 * Starts a the removal of the previewed file.
701 *
702 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
703 * depending upon the user selection in the dialog.
704 */
705 private void removeFile() {
706 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
707 R.string.confirmation_remove_alert,
708 new String[]{getFile().getFileName()},
709 R.string.confirmation_remove_remote_and_local,
710 R.string.confirmation_remove_local,
711 R.string.common_cancel);
712 confDialog.setOnConfirmationListener(this);
713 confDialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
714 }
715
716
717 /**
718 * Performs the removal of the previewed file, both locally and in the server.
719 */
720 @Override
721 public void onConfirmation(String callerTag) {
722 OCFile file = getFile();
723 if (mStorageManager.getFileById(file.getFileId()) != null) { // check that the file is still there;
724 stopPreview(true);
725 mLastRemoteOperation = new RemoveFileOperation( file, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
726 true,
727 mStorageManager);
728 mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
729
730 ((FileDisplayActivity) getActivity()).showLoadingDialog();
731 }
732 }
733
734
735 /**
736 * Removes the file from local storage
737 */
738 @Override
739 public void onNeutral(String callerTag) {
740 OCFile file = getFile();
741 stopPreview(true);
742 mStorageManager.removeFile(file, false, true); // TODO perform in background task / new thread
743 finish();
744 }
745
746 /**
747 * User cancelled the removal action.
748 */
749 @Override
750 public void onCancel(String callerTag) {
751 // nothing to do here
752 }
753
754
755 /**
756 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment} to be previewed.
757 *
758 * @param file File to test if can be previewed.
759 * @return 'True' if the file can be handled by the fragment.
760 */
761 public static boolean canBePreviewed(OCFile file) {
762 return (file != null && (file.isAudio() || file.isVideo()));
763 }
764
765 /**
766 * {@inheritDoc}
767 */
768 @Override
769 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
770 if (operation.equals(mLastRemoteOperation)) {
771 if (operation instanceof RemoveFileOperation) {
772 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
773 }
774 }
775 }
776
777 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
778 ((FileDisplayActivity) getActivity()).dismissLoadingDialog();
779 if (result.isSuccess()) {
780 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
781 msg.show();
782 finish();
783
784 } else {
785 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
786 msg.show();
787 if (result.isSslRecoverableException()) {
788 // TODO show the SSL warning dialog
789 }
790 }
791 }
792
793 private void stopPreview(boolean stopAudio) {
794 OCFile file = getFile();
795 if (file.isAudio() && stopAudio) {
796 mMediaServiceBinder.pause();
797
798 } else if (file.isVideo()) {
799 mVideoPreview.stopPlayback();
800 }
801 }
802
803
804
805 /**
806 * Finishes the preview
807 */
808 private void finish() {
809 getActivity().onBackPressed();
810 }
811
812
813 public int getPosition() {
814 if (mPrepared) {
815 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
816 }
817 Log_OC.e(TAG, "getting position: " + mSavedPlaybackPosition);
818 return mSavedPlaybackPosition;
819 }
820
821 public boolean isPlaying() {
822 if (mPrepared) {
823 mAutoplay = mVideoPreview.isPlaying();
824 }
825 return mAutoplay;
826 }
827
828 }