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