512becd9e60ed71ca4bfe09e9e4681ec0b356eca
[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 boolean onTouch(View v, MotionEvent event) {
458 if (event.getAction() == MotionEvent.ACTION_DOWN) {
459 if (v == mImagePreview &&
460 mMediaServiceBinder != null && mFile.isAudio() && mMediaServiceBinder.isPlaying(mFile)) {
461 toggleMediaController(MediaService.MEDIA_CONTROL_PERMANENT);
462 return true;
463
464 } else if (v == mVideoPreview) {
465 toggleMediaController(MediaService.MEDIA_CONTROL_SHORT_LIFE);
466 return true;
467 }
468 }
469 return false;
470 }
471
472
473 private void toggleMediaController(int time) {
474 if (mMediaController.isShowing()) {
475 mMediaController.hide();
476 } else {
477 mMediaController.show(time);
478 }
479 }
480
481
482 private void playAudio() {
483 if (!mMediaServiceBinder.isPlaying(mFile)) {
484 Log.d(TAG, "starting playback of " + mFile.getStoragePath());
485 mMediaServiceBinder.start(mAccount, mFile);
486
487 } else {
488 if (!mMediaServiceBinder.isPlaying()) {
489 mMediaServiceBinder.start();
490 }
491 if (!mMediaController.isShowing() && isVisible()) {
492 mMediaController.show(MediaService.MEDIA_CONTROL_PERMANENT);
493 // TODO - fix strange bug; steps to trigger :
494 // 1. remove the "isVisible()" control
495 // 2. start the app and preview an audio file
496 // 3. exit from the app (home button, for instance) while the audio file is still being played
497 // 4. go to notification bar and click on the "ownCloud music app" notification
498 // PUM!
499 }
500 }
501 }
502
503
504 private void bindMediaService() {
505 Log.d(TAG, "Binding to MediaService...");
506 if (mMediaServiceConnection == null) {
507 mMediaServiceConnection = new MediaServiceConnection();
508 }
509 getActivity().bindService( new Intent(getActivity(),
510 MediaService.class),
511 mMediaServiceConnection,
512 Context.BIND_AUTO_CREATE);
513 // follow the flow in MediaServiceConnection#onServiceConnected(...)
514 }
515
516 /** Defines callbacks for service binding, passed to bindService() */
517 private class MediaServiceConnection implements ServiceConnection {
518
519 @Override
520 public void onServiceConnected(ComponentName component, IBinder service) {
521 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
522 Log.d(TAG, "Media service connected");
523 mMediaServiceBinder = (MediaServiceBinder) service;
524 if (mMediaServiceBinder != null) {
525 if (mMediaController == null) {
526 mMediaController = new MediaController(getSherlockActivity());
527 }
528 prepareMediaController();
529 playAudio(); // do not wait for the touch of nobody to play audio
530
531 Log.d(TAG, "Successfully bound to MediaService, MediaController ready");
532
533 } else {
534 Log.e(TAG, "Unexpected response from MediaService while binding");
535 }
536 }
537 }
538
539 private void prepareMediaController() {
540 mMediaServiceBinder.registerMediaController(mMediaController);
541 mMediaController.setMediaPlayer(mMediaServiceBinder);
542 mMediaController.setAnchorView(getView());
543 mMediaController.setEnabled(mMediaServiceBinder.isInPlaybackState());
544 }
545
546 @Override
547 public void onServiceDisconnected(ComponentName component) {
548 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
549 Log.e(TAG, "Media service suddenly disconnected");
550 if (mMediaController != null) {
551 mMediaController.hide();
552 mMediaController.setMediaPlayer(null);
553 mMediaController = null;
554 }
555 mMediaServiceBinder = null;
556 mMediaServiceConnection = null;
557 }
558 }
559 }
560
561
562
563 /**
564 * Opens the previewed file with an external application.
565 *
566 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
567 * we should get a list of available apps for MIME tpye in the server and join it with the list of
568 * available apps for the MIME type known from the file extension, to let the user choose
569 */
570 private void openFile() {
571 stopPreview(true);
572 String storagePath = mFile.getStoragePath();
573 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
574 try {
575 Intent i = new Intent(Intent.ACTION_VIEW);
576 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
577 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
578 startActivity(i);
579
580 } catch (Throwable t) {
581 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
582 boolean toastIt = true;
583 String mimeType = "";
584 try {
585 Intent i = new Intent(Intent.ACTION_VIEW);
586 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
587 if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
588 if (mimeType != null) {
589 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
590 } else {
591 // desperate try
592 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*-/*");
593 }
594 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
595 startActivity(i);
596 toastIt = false;
597 }
598
599 } catch (IndexOutOfBoundsException e) {
600 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
601
602 } catch (ActivityNotFoundException e) {
603 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
604
605 } catch (Throwable th) {
606 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
607
608 } finally {
609 if (toastIt) {
610 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
611 }
612 }
613
614 }
615 finish();
616 }
617
618 /**
619 * Starts a the removal of the previewed file.
620 *
621 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
622 * depending upon the user selection in the dialog.
623 */
624 private void removeFile() {
625 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
626 R.string.confirmation_remove_alert,
627 new String[]{mFile.getFileName()},
628 R.string.confirmation_remove_remote_and_local,
629 R.string.confirmation_remove_local,
630 R.string.common_cancel);
631 confDialog.setOnConfirmationListener(this);
632 confDialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
633 }
634
635
636 /**
637 * Performs the removal of the previewed file, both locally and in the server.
638 */
639 @Override
640 public void onConfirmation(String callerTag) {
641 if (mStorageManager.getFileById(mFile.getFileId()) != null) { // check that the file is still there;
642 stopPreview(true);
643 mLastRemoteOperation = new RemoveFileOperation( mFile, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
644 true,
645 mStorageManager);
646 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
647 mLastRemoteOperation.execute(wc, this, mHandler);
648
649 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
650 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
651 }
652 }
653
654
655 /**
656 * Removes the file from local storage
657 */
658 @Override
659 public void onNeutral(String callerTag) {
660 // TODO this code should be made in a secondary thread,
661 if (mFile.isDown()) { // checks it is still there
662 stopPreview(true);
663 File f = new File(mFile.getStoragePath());
664 f.delete();
665 mFile.setStoragePath(null);
666 mStorageManager.saveFile(mFile);
667 finish();
668 }
669 }
670
671 /**
672 * User cancelled the removal action.
673 */
674 @Override
675 public void onCancel(String callerTag) {
676 // nothing to do here
677 }
678
679
680 /**
681 * {@inheritDoc}
682 */
683 public OCFile getFile(){
684 return mFile;
685 }
686
687 /*
688 /**
689 * Use this method to signal this Activity that it shall update its view.
690 *
691 * @param file : An {@link OCFile}
692 *-/
693 public void updateFileDetails(OCFile file, Account ocAccount) {
694 mFile = file;
695 if (ocAccount != null && (
696 mStorageManager == null ||
697 (mAccount != null && !mAccount.equals(ocAccount))
698 )) {
699 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
700 }
701 mAccount = ocAccount;
702 updateFileDetails(false);
703 }
704 */
705
706
707 /**
708 * Interface to implement by any Activity that includes some instance of FileDetailFragment
709 *
710 * @author David A. Velasco
711 */
712 public interface ContainerActivity extends TransferServiceGetter {
713
714 /**
715 * Callback method invoked when the detail fragment wants to notice its container
716 * activity about a relevant state the file shown by the fragment.
717 *
718 * Added to notify to FileDisplayActivity about the need of refresh the files list.
719 *
720 * Currently called when:
721 * - a download is started;
722 * - a rename is completed;
723 * - a deletion is completed;
724 * - the 'inSync' flag is changed;
725 */
726 public void onFileStateChanged();
727
728 }
729
730 /**
731 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment} to be previewed.
732 *
733 * @param file File to test if can be previewed.
734 * @return 'True' if the file can be handled by the fragment.
735 */
736 public static boolean canBePreviewed(OCFile file) {
737 return (file != null && (file.isAudio() || file.isVideo()));
738 }
739
740 /**
741 * {@inheritDoc}
742 */
743 @Override
744 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
745 if (operation.equals(mLastRemoteOperation)) {
746 if (operation instanceof RemoveFileOperation) {
747 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
748 }
749 }
750 }
751
752 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
753 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
754 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
755
756 if (result.isSuccess()) {
757 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
758 msg.show();
759 finish();
760
761 } else {
762 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
763 msg.show();
764 if (result.isSslRecoverableException()) {
765 // TODO show the SSL warning dialog
766 }
767 }
768 }
769
770 private void stopPreview(boolean stopAudio) {
771 if (mMediaController != null) {
772 mMediaController.hide();
773 }
774 if (mFile.isAudio() && stopAudio) {
775 mMediaServiceBinder.pause();
776
777 } else if (mFile.isVideo()) {
778 mVideoPreview.stopPlayback();
779 }
780 }
781
782
783
784 /**
785 * Finishes the preview
786 */
787 private void finish() {
788 Activity container = getActivity();
789 if (container instanceof FileDisplayActivity) {
790 // double pane
791 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
792 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
793 transaction.commit();
794 ((FileFragment.ContainerActivity)container).onFileStateChanged();
795 } else {
796 container.finish();
797 }
798 }
799
800 }