PreviewMediaFragment.java 28 KB

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