PreviewMediaFragment.java 29 KB

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