FilePreviewFragment.java 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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.fragment;
  19. import java.io.File;
  20. import java.lang.ref.WeakReference;
  21. import java.sql.PreparedStatement;
  22. import java.util.ArrayList;
  23. import java.util.List;
  24. import org.apache.commons.httpclient.methods.GetMethod;
  25. import org.apache.commons.httpclient.methods.PostMethod;
  26. import org.apache.commons.httpclient.methods.StringRequestEntity;
  27. import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
  28. import org.apache.http.HttpStatus;
  29. import org.apache.http.NameValuePair;
  30. import org.apache.http.client.utils.URLEncodedUtils;
  31. import org.apache.http.entity.FileEntity;
  32. import org.apache.http.message.BasicNameValuePair;
  33. import org.apache.http.protocol.HTTP;
  34. import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
  35. import org.json.JSONObject;
  36. import android.accounts.Account;
  37. import android.accounts.AccountManager;
  38. import android.annotation.SuppressLint;
  39. import android.app.Activity;
  40. import android.app.AlertDialog;
  41. import android.content.ActivityNotFoundException;
  42. import android.content.BroadcastReceiver;
  43. import android.content.ComponentName;
  44. import android.content.Context;
  45. import android.content.DialogInterface;
  46. import android.content.Intent;
  47. import android.content.IntentFilter;
  48. import android.content.ServiceConnection;
  49. import android.graphics.Bitmap;
  50. import android.graphics.BitmapFactory;
  51. import android.graphics.BitmapFactory.Options;
  52. import android.graphics.Point;
  53. import android.media.MediaPlayer;
  54. import android.media.MediaPlayer.OnCompletionListener;
  55. import android.media.MediaPlayer.OnErrorListener;
  56. import android.media.MediaPlayer.OnPreparedListener;
  57. import android.net.Uri;
  58. import android.os.AsyncTask;
  59. import android.os.Bundle;
  60. import android.os.Handler;
  61. import android.os.IBinder;
  62. import android.support.v4.app.DialogFragment;
  63. import android.support.v4.app.FragmentTransaction;
  64. import android.util.Log;
  65. import android.view.Display;
  66. import android.view.LayoutInflater;
  67. import android.view.MotionEvent;
  68. import android.view.View;
  69. import android.view.View.OnClickListener;
  70. import android.view.View.OnTouchListener;
  71. import android.view.ViewGroup;
  72. import android.webkit.MimeTypeMap;
  73. import android.widget.Button;
  74. import android.widget.CheckBox;
  75. import android.widget.ImageView;
  76. import android.widget.MediaController;
  77. import android.widget.TextView;
  78. import android.widget.Toast;
  79. import android.widget.VideoView;
  80. import android.widget.AdapterView.AdapterContextMenuInfo;
  81. import com.actionbarsherlock.app.SherlockFragment;
  82. import com.actionbarsherlock.view.Menu;
  83. import com.actionbarsherlock.view.MenuInflater;
  84. import com.actionbarsherlock.view.MenuItem;
  85. import com.owncloud.android.AccountUtils;
  86. import com.owncloud.android.DisplayUtils;
  87. import com.owncloud.android.authenticator.AccountAuthenticator;
  88. import com.owncloud.android.datamodel.FileDataStorageManager;
  89. import com.owncloud.android.datamodel.OCFile;
  90. import com.owncloud.android.files.services.FileDownloader;
  91. import com.owncloud.android.files.services.FileObserverService;
  92. import com.owncloud.android.files.services.FileUploader;
  93. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  94. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  95. import com.owncloud.android.media.MediaService;
  96. import com.owncloud.android.media.MediaServiceBinder;
  97. import com.owncloud.android.network.OwnCloudClientUtils;
  98. import com.owncloud.android.operations.OnRemoteOperationListener;
  99. import com.owncloud.android.operations.RemoteOperation;
  100. import com.owncloud.android.operations.RemoteOperationResult;
  101. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  102. import com.owncloud.android.operations.RemoveFileOperation;
  103. import com.owncloud.android.operations.RenameFileOperation;
  104. import com.owncloud.android.operations.SynchronizeFileOperation;
  105. import com.owncloud.android.ui.activity.ConflictsResolveActivity;
  106. import com.owncloud.android.ui.activity.FileDetailActivity;
  107. import com.owncloud.android.ui.activity.FileDisplayActivity;
  108. import com.owncloud.android.ui.OnSwipeTouchListener;
  109. import com.owncloud.android.ui.activity.TransferServiceGetter;
  110. import com.owncloud.android.ui.activity.VideoActivity;
  111. import com.owncloud.android.ui.dialog.EditNameDialog;
  112. import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
  113. import com.owncloud.android.utils.OwnCloudVersion;
  114. import com.owncloud.android.R;
  115. import eu.alefzero.webdav.WebdavClient;
  116. import eu.alefzero.webdav.WebdavUtils;
  117. /**
  118. * This fragment shows a preview of a downloaded file.
  119. *
  120. * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
  121. *
  122. * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
  123. *
  124. * @author David A. Velasco
  125. */
  126. public class FilePreviewFragment extends SherlockFragment implements
  127. /*OnClickListener,*/ OnTouchListener , FileFragment,
  128. ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener /*, EditNameDialogListener*/ {
  129. public static final String EXTRA_FILE = "FILE";
  130. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  131. private static final String EXTRA_PLAY_POSITION = "PLAY_POSITION";
  132. private View mView;
  133. private OCFile mFile;
  134. private Account mAccount;
  135. private FileDataStorageManager mStorageManager;
  136. private ImageView mImagePreview;
  137. public Bitmap mBitmap = null;
  138. private VideoView mVideoPreview;
  139. private int mSavedPlaybackPosition;
  140. //private DownloadFinishReceiver mDownloadFinishReceiver;
  141. //private UploadFinishReceiver mUploadFinishReceiver;
  142. private Handler mHandler;
  143. private RemoteOperation mLastRemoteOperation;
  144. private MediaServiceBinder mMediaServiceBinder = null;
  145. private MediaController mMediaController = null;
  146. private MediaServiceConnection mMediaServiceConnection = null;
  147. private VideoHelper mVideoHelper;
  148. private static final String TAG = FilePreviewFragment.class.getSimpleName();
  149. /**
  150. * Creates a fragment to preview a file.
  151. *
  152. * When 'fileToDetail' or 'ocAccount' are null
  153. *
  154. * @param fileToDetail An {@link OCFile} to preview in the fragment
  155. * @param ocAccount An ownCloud account; needed to start downloads
  156. */
  157. public FilePreviewFragment(OCFile fileToDetail, Account ocAccount) {
  158. mFile = fileToDetail;
  159. mAccount = ocAccount;
  160. mSavedPlaybackPosition = 0;
  161. mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
  162. }
  163. /**
  164. * Creates an empty fragment for previews.
  165. *
  166. * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
  167. *
  168. * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
  169. */
  170. public FilePreviewFragment() {
  171. mFile = null;
  172. mAccount = null;
  173. mSavedPlaybackPosition = 0;
  174. mStorageManager = null;
  175. }
  176. /**
  177. * {@inheritDoc}
  178. */
  179. @Override
  180. public void onCreate(Bundle savedInstanceState) {
  181. super.onCreate(savedInstanceState);
  182. mHandler = new Handler();
  183. setHasOptionsMenu(true);
  184. }
  185. /**
  186. * {@inheritDoc}
  187. */
  188. @Override
  189. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  190. Bundle savedInstanceState) {
  191. super.onCreateView(inflater, container, savedInstanceState);
  192. mView = inflater.inflate(R.layout.file_preview, container, false);
  193. //mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
  194. //mView.findViewById(R.id.fdRenameBtn).setOnClickListener(this);
  195. //mView.findViewById(R.id.fdDownloadBtn).setOnClickListener(this);
  196. //mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);
  197. //mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);
  198. mImagePreview = (ImageView)mView.findViewById(R.id.image_preview);
  199. mImagePreview.setOnTouchListener(this);
  200. mVideoPreview = (VideoView)mView.findViewById(R.id.video_preview);
  201. //updateFileDetails(false);
  202. return mView;
  203. }
  204. /**
  205. * {@inheritDoc}
  206. */
  207. @Override
  208. public void onAttach(Activity activity) {
  209. super.onAttach(activity);
  210. if (!(activity instanceof FileFragment.ContainerActivity))
  211. throw new ClassCastException(activity.toString() + " must implement " + FileFragment.ContainerActivity.class.getSimpleName());
  212. }
  213. /**
  214. * {@inheritDoc}
  215. */
  216. @Override
  217. public void onActivityCreated(Bundle savedInstanceState) {
  218. super.onActivityCreated(savedInstanceState);
  219. mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
  220. if (savedInstanceState != null) {
  221. mFile = savedInstanceState.getParcelable(FilePreviewFragment.EXTRA_FILE);
  222. mAccount = savedInstanceState.getParcelable(FilePreviewFragment.EXTRA_ACCOUNT);
  223. mSavedPlaybackPosition = savedInstanceState.getInt(FilePreviewFragment.EXTRA_PLAY_POSITION);
  224. }
  225. if (mFile == null) {
  226. throw new IllegalStateException("Instanced with a NULL OCFile");
  227. }
  228. if (mAccount == null) {
  229. throw new IllegalStateException("Instanced with a NULL ownCloud Account");
  230. }
  231. if (!mFile.isDown()) {
  232. throw new IllegalStateException("There is no local file to preview");
  233. }
  234. if (mFile.isVideo()) {
  235. mVideoPreview.setVisibility(View.VISIBLE);
  236. mImagePreview.setVisibility(View.GONE);
  237. prepareVideo();
  238. } else {
  239. mVideoPreview.setVisibility(View.GONE);
  240. mImagePreview.setVisibility(View.VISIBLE);
  241. }
  242. }
  243. /**
  244. * {@inheritDoc}
  245. */
  246. @Override
  247. public void onSaveInstanceState(Bundle outState) {
  248. super.onSaveInstanceState(outState);
  249. outState.putParcelable(FilePreviewFragment.EXTRA_FILE, mFile);
  250. outState.putParcelable(FilePreviewFragment.EXTRA_ACCOUNT, mAccount);
  251. if (mVideoPreview.isPlaying()) {
  252. outState.putInt(FilePreviewFragment.EXTRA_PLAY_POSITION , mVideoPreview.getCurrentPosition());
  253. }
  254. }
  255. @Override
  256. public void onStart() {
  257. super.onStart();
  258. if (mFile != null) {
  259. if (mFile.isAudio()) {
  260. bindMediaService();
  261. } else if (mFile.isImage()) {
  262. BitmapLoader bl = new BitmapLoader(mImagePreview);
  263. bl.execute(new String[]{mFile.getStoragePath()});
  264. } else if (mFile.isVideo()) {
  265. playVideo();
  266. }
  267. }
  268. }
  269. /**
  270. * {@inheritDoc}
  271. */
  272. @Override
  273. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  274. super.onCreateOptionsMenu(menu, inflater);
  275. inflater.inflate(R.menu.file_actions_menu, menu);
  276. List<Integer> toHide = new ArrayList<Integer>();
  277. MenuItem item = null;
  278. toHide.add(R.id.action_cancel_download);
  279. toHide.add(R.id.action_cancel_upload);
  280. toHide.add(R.id.action_download_file);
  281. toHide.add(R.id.action_rename_file); // by now
  282. for (int i : toHide) {
  283. item = menu.findItem(i);
  284. if (item != null) {
  285. item.setVisible(false);
  286. item.setEnabled(false);
  287. }
  288. }
  289. }
  290. /**
  291. * {@inheritDoc}
  292. */
  293. @Override
  294. public boolean onOptionsItemSelected(MenuItem item) {
  295. switch (item.getItemId()) {
  296. case R.id.action_open_file_with: {
  297. openFile();
  298. return true;
  299. }
  300. case R.id.action_remove_file: {
  301. removeFile();
  302. return true;
  303. }
  304. case R.id.action_see_details: {
  305. seeDetails();
  306. return true;
  307. }
  308. /*
  309. case R.id.action_toggle_keep_in_sync: {
  310. CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
  311. mFile.setKeepInSync(cb.isChecked());
  312. mStorageManager.saveFile(mFile);
  313. /// register the OCFile instance in the observer service to monitor local updates;
  314. /// if necessary, the file is download
  315. Intent intent = new Intent(getActivity().getApplicationContext(),
  316. FileObserverService.class);
  317. intent.putExtra(FileObserverService.KEY_FILE_CMD,
  318. (cb.isChecked()?
  319. FileObserverService.CMD_ADD_OBSERVED_FILE:
  320. FileObserverService.CMD_DEL_OBSERVED_FILE));
  321. intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
  322. intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
  323. Log.e(TAG, "starting observer service");
  324. getActivity().startService(intent);
  325. if (mFile.keepInSync()) {
  326. onClick(getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
  327. }
  328. break;
  329. }*/
  330. default:
  331. return false;
  332. }
  333. }
  334. private void seeDetails() {
  335. stopPreview(false);
  336. ((FileFragment.ContainerActivity)getActivity()).showFragmentWithDetails(mFile);
  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. private void playVideo() {
  346. // load the video file in the video player ; when done, VideoHelper#onPrepared() will be called
  347. mVideoPreview.setVideoPath(mFile.getStoragePath());
  348. // create and prepare control panel for the user
  349. mMediaController = new MediaController(getActivity());
  350. mMediaController.setMediaPlayer(mVideoPreview);
  351. mMediaController.setAnchorView(mVideoPreview);
  352. mVideoPreview.setMediaController(mMediaController);
  353. }
  354. private class VideoHelper implements OnCompletionListener, OnPreparedListener, OnErrorListener {
  355. /**
  356. * Called when the file is ready to be played.
  357. *
  358. * Just starts the playback.
  359. *
  360. * @param mp {@link MediaPlayer} instance performing the playback.
  361. */
  362. @Override
  363. public void onPrepared(MediaPlayer vp) {
  364. mVideoPreview.seekTo(mSavedPlaybackPosition);
  365. mVideoPreview.start();
  366. mMediaController.show(MediaService.MEDIA_CONTROL_SHORT_LIFE);
  367. }
  368. /**
  369. * Called when the file is finished playing.
  370. *
  371. * Finishes the activity.
  372. *
  373. * @param mp {@link MediaPlayer} instance performing the playback.
  374. */
  375. @Override
  376. public void onCompletion(MediaPlayer mp) {
  377. // nothing, right now
  378. }
  379. /**
  380. * Called when an error in playback occurs.
  381. *
  382. * @param mp {@link MediaPlayer} instance performing the playback.
  383. * @param what Type of error
  384. * @param extra Extra code specific to the error
  385. */
  386. @Override
  387. public boolean onError(MediaPlayer mp, int what, int extra) {
  388. Log.e(TAG, "Error in video playback, what = " + what + ", extra = " + extra);
  389. if (mMediaController != null) {
  390. mMediaController.hide();
  391. }
  392. if (mVideoPreview.getWindowToken() != null) {
  393. String message = MediaService.getMessageForMediaError(getActivity(), what, extra);
  394. new AlertDialog.Builder(getActivity())
  395. .setMessage(message)
  396. .setPositiveButton(android.R.string.VideoView_error_button,
  397. new DialogInterface.OnClickListener() {
  398. public void onClick(DialogInterface dialog, int whichButton) {
  399. dialog.dismiss();
  400. VideoHelper.this.onCompletion(null);
  401. }
  402. })
  403. .setCancelable(false)
  404. .show();
  405. }
  406. return true;
  407. }
  408. }
  409. @Override
  410. public void onResume() {
  411. super.onResume();
  412. /*
  413. mDownloadFinishReceiver = new DownloadFinishReceiver();
  414. IntentFilter filter = new IntentFilter(
  415. FileDownloader.DOWNLOAD_FINISH_MESSAGE);
  416. getActivity().registerReceiver(mDownloadFinishReceiver, filter);
  417. mUploadFinishReceiver = new UploadFinishReceiver();
  418. filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
  419. getActivity().registerReceiver(mUploadFinishReceiver, filter);
  420. */
  421. }
  422. @Override
  423. public void onPause() {
  424. super.onPause();
  425. /*
  426. if (mVideoPreview.getVisibility() == View.VISIBLE) {
  427. mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
  428. }*/
  429. /*
  430. getActivity().unregisterReceiver(mDownloadFinishReceiver);
  431. mDownloadFinishReceiver = null;
  432. getActivity().unregisterReceiver(mUploadFinishReceiver);
  433. mUploadFinishReceiver = null;
  434. */
  435. }
  436. @Override
  437. public void onStop() {
  438. super.onStop();
  439. if (mMediaServiceConnection != null) {
  440. Log.d(TAG, "Unbinding from MediaService ...");
  441. if (mMediaServiceBinder != null && mMediaController != null) {
  442. mMediaServiceBinder.unregisterMediaController(mMediaController);
  443. }
  444. getActivity().unbindService(mMediaServiceConnection);
  445. mMediaServiceConnection = null;
  446. mMediaServiceBinder = null;
  447. if (mMediaController != null) {
  448. mMediaController.hide();
  449. mMediaController = null;
  450. }
  451. }
  452. }
  453. @Override
  454. public void onDestroy() {
  455. super.onDestroy();
  456. if (mBitmap != null) {
  457. mBitmap.recycle();
  458. }
  459. }
  460. /*
  461. @Override
  462. public View getView() {
  463. return super.getView() == null ? mView : super.getView();
  464. }
  465. */
  466. /*
  467. @Override
  468. public void onClick(View v) {
  469. switch (v.getId()) {
  470. case R.id.fdDownloadBtn: {
  471. FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
  472. FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
  473. if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
  474. downloaderBinder.cancel(mAccount, mFile);
  475. if (mFile.isDown()) {
  476. setButtonsForDown();
  477. } else {
  478. setButtonsForRemote();
  479. }
  480. } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
  481. uploaderBinder.cancel(mAccount, mFile);
  482. if (!mFile.fileExists()) {
  483. // TODO make something better
  484. if (getActivity() instanceof FileDisplayActivity) {
  485. // double pane
  486. FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
  487. transaction.replace(R.id.file_details_container, new FilePreviewFragment(null, null), FTAG); // empty FileDetailFragment
  488. transaction.commit();
  489. mContainerActivity.onFileStateChanged();
  490. } else {
  491. getActivity().finish();
  492. }
  493. } else if (mFile.isDown()) {
  494. setButtonsForDown();
  495. } else {
  496. setButtonsForRemote();
  497. }
  498. } else {
  499. mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());
  500. WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
  501. mLastRemoteOperation.execute(wc, this, mHandler);
  502. // update ui
  503. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  504. getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  505. setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
  506. }
  507. break;
  508. }
  509. case R.id.fdKeepInSync: {
  510. CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
  511. mFile.setKeepInSync(cb.isChecked());
  512. mStorageManager.saveFile(mFile);
  513. /// register the OCFile instance in the observer service to monitor local updates;
  514. /// if necessary, the file is download
  515. Intent intent = new Intent(getActivity().getApplicationContext(),
  516. FileObserverService.class);
  517. intent.putExtra(FileObserverService.KEY_FILE_CMD,
  518. (cb.isChecked()?
  519. FileObserverService.CMD_ADD_OBSERVED_FILE:
  520. FileObserverService.CMD_DEL_OBSERVED_FILE));
  521. intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
  522. intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
  523. Log.e(TAG, "starting observer service");
  524. getActivity().startService(intent);
  525. if (mFile.keepInSync()) {
  526. onClick(getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
  527. }
  528. break;
  529. }
  530. case R.id.fdRenameBtn: {
  531. EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), mFile.getFileName(), this);
  532. dialog.show(getFragmentManager(), "nameeditdialog");
  533. break;
  534. }
  535. case R.id.fdRemoveBtn: {
  536. ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
  537. R.string.confirmation_remove_alert,
  538. new String[]{mFile.getFileName()},
  539. mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
  540. mFile.isDown() ? R.string.confirmation_remove_local : -1,
  541. R.string.common_cancel);
  542. confDialog.setOnConfirmationListener(this);
  543. mCurrentDialog = confDialog;
  544. mCurrentDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
  545. break;
  546. }
  547. case R.id.fdOpenBtn: {
  548. openFile();
  549. break;
  550. }
  551. default:
  552. Log.e(TAG, "Incorrect view clicked!");
  553. }
  554. }
  555. */
  556. @Override
  557. public boolean onTouch(View v, MotionEvent event) {
  558. if (event.getAction() == MotionEvent.ACTION_DOWN) {
  559. if (v == mImagePreview &&
  560. mMediaServiceBinder != null && mFile.isAudio() && mMediaServiceBinder.isPlaying(mFile)) {
  561. toggleMediaController(MediaService.MEDIA_CONTROL_PERMANENT);
  562. return true;
  563. } else if (v == mVideoPreview) {
  564. toggleMediaController(MediaService.MEDIA_CONTROL_SHORT_LIFE);
  565. return true;
  566. }
  567. }
  568. return false;
  569. }
  570. private void toggleMediaController(int time) {
  571. if (mMediaController.isShowing()) {
  572. mMediaController.hide();
  573. } else {
  574. mMediaController.show(time);
  575. }
  576. }
  577. private void playAudio() {
  578. if (!mMediaServiceBinder.isPlaying(mFile)) {
  579. Log.d(TAG, "starting playback of " + mFile.getStoragePath());
  580. mMediaServiceBinder.start(mAccount, mFile);
  581. } else {
  582. if (!mMediaServiceBinder.isPlaying()) {
  583. mMediaServiceBinder.start();
  584. }
  585. if (!mMediaController.isShowing() && isVisible()) {
  586. mMediaController.show(MediaService.MEDIA_CONTROL_PERMANENT);
  587. // TODO - fix strange bug; steps to trigger :
  588. // 1. remove the "isVisible()" control
  589. // 2. start the app and preview an audio file
  590. // 3. exit from the app (home button, for instance) while the audio file is still being played
  591. // 4. go to notification bar and click on the "ownCloud music app" notification
  592. // PUM!
  593. }
  594. }
  595. }
  596. private void bindMediaService() {
  597. Log.d(TAG, "Binding to MediaService...");
  598. if (mMediaServiceConnection == null) {
  599. mMediaServiceConnection = new MediaServiceConnection();
  600. }
  601. getActivity().bindService( new Intent(getActivity(),
  602. MediaService.class),
  603. mMediaServiceConnection,
  604. Context.BIND_AUTO_CREATE);
  605. // follow the flow in MediaServiceConnection#onServiceConnected(...)
  606. }
  607. /** Defines callbacks for service binding, passed to bindService() */
  608. private class MediaServiceConnection implements ServiceConnection {
  609. @Override
  610. public void onServiceConnected(ComponentName component, IBinder service) {
  611. if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
  612. Log.d(TAG, "Media service connected");
  613. mMediaServiceBinder = (MediaServiceBinder) service;
  614. if (mMediaServiceBinder != null) {
  615. if (mMediaController == null) {
  616. mMediaController = new MediaController(getSherlockActivity());
  617. }
  618. prepareMediaController();
  619. playAudio(); // do not wait for the touch of nobody to play audio
  620. Log.d(TAG, "Successfully bound to MediaService, MediaController ready");
  621. } else {
  622. Log.e(TAG, "Unexpected response from MediaService while binding");
  623. }
  624. }
  625. }
  626. private void prepareMediaController() {
  627. mMediaServiceBinder.registerMediaController(mMediaController);
  628. mMediaController.setMediaPlayer(mMediaServiceBinder);
  629. mMediaController.setAnchorView(getView());
  630. mMediaController.setEnabled(mMediaServiceBinder.isInPlaybackState());
  631. }
  632. @Override
  633. public void onServiceDisconnected(ComponentName component) {
  634. if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
  635. Log.e(TAG, "Media service suddenly disconnected");
  636. if (mMediaController != null) {
  637. mMediaController.hide();
  638. mMediaController.setMediaPlayer(null);
  639. mMediaController = null;
  640. }
  641. mMediaServiceBinder = null;
  642. mMediaServiceConnection = null;
  643. }
  644. }
  645. }
  646. /**
  647. * Opens the previewed file with an external application.
  648. *
  649. * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
  650. * we should get a list of available apps for MIME tpye in the server and join it with the list of
  651. * available apps for the MIME type known from the file extension, to let the user choose
  652. */
  653. private void openFile() {
  654. stopPreview(true);
  655. String storagePath = mFile.getStoragePath();
  656. String encodedStoragePath = WebdavUtils.encodePath(storagePath);
  657. try {
  658. Intent i = new Intent(Intent.ACTION_VIEW);
  659. i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
  660. i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  661. startActivity(i);
  662. } catch (Throwable t) {
  663. Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
  664. boolean toastIt = true;
  665. String mimeType = "";
  666. try {
  667. Intent i = new Intent(Intent.ACTION_VIEW);
  668. mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
  669. if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
  670. if (mimeType != null) {
  671. i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
  672. } else {
  673. // desperate try
  674. i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*-/*");
  675. }
  676. i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  677. startActivity(i);
  678. toastIt = false;
  679. }
  680. } catch (IndexOutOfBoundsException e) {
  681. Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
  682. } catch (ActivityNotFoundException e) {
  683. Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
  684. } catch (Throwable th) {
  685. Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
  686. } finally {
  687. if (toastIt) {
  688. Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
  689. }
  690. }
  691. }
  692. finish();
  693. }
  694. /**
  695. * Starts a the removal of the previewed file.
  696. *
  697. * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
  698. * depending upon the user selection in the dialog.
  699. */
  700. private void removeFile() {
  701. ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
  702. R.string.confirmation_remove_alert,
  703. new String[]{mFile.getFileName()},
  704. R.string.confirmation_remove_remote_and_local,
  705. R.string.confirmation_remove_local,
  706. R.string.common_cancel);
  707. confDialog.setOnConfirmationListener(this);
  708. confDialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
  709. }
  710. /**
  711. * Performs the removal of the previewed file, both locally and in the server.
  712. */
  713. @Override
  714. public void onConfirmation(String callerTag) {
  715. if (mStorageManager.getFileById(mFile.getFileId()) != null) { // check that the file is still there;
  716. stopPreview(true);
  717. mLastRemoteOperation = new RemoveFileOperation( mFile, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
  718. true,
  719. mStorageManager);
  720. WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
  721. mLastRemoteOperation.execute(wc, this, mHandler);
  722. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  723. getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  724. }
  725. }
  726. /**
  727. * Removes the file from local storage
  728. */
  729. @Override
  730. public void onNeutral(String callerTag) {
  731. // TODO this code should be made in a secondary thread,
  732. if (mFile.isDown()) { // checks it is still there
  733. stopPreview(true);
  734. File f = new File(mFile.getStoragePath());
  735. f.delete();
  736. mFile.setStoragePath(null);
  737. mStorageManager.saveFile(mFile);
  738. finish();
  739. }
  740. }
  741. /**
  742. * User cancelled the removal action.
  743. */
  744. @Override
  745. public void onCancel(String callerTag) {
  746. // nothing to do here
  747. }
  748. /**
  749. * {@inheritDoc}
  750. */
  751. public OCFile getFile(){
  752. return mFile;
  753. }
  754. /*
  755. /**
  756. * Use this method to signal this Activity that it shall update its view.
  757. *
  758. * @param file : An {@link OCFile}
  759. *-/
  760. public void updateFileDetails(OCFile file, Account ocAccount) {
  761. mFile = file;
  762. if (ocAccount != null && (
  763. mStorageManager == null ||
  764. (mAccount != null && !mAccount.equals(ocAccount))
  765. )) {
  766. mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
  767. }
  768. mAccount = ocAccount;
  769. updateFileDetails(false);
  770. }
  771. */
  772. /**
  773. * Interface to implement by any Activity that includes some instance of FileDetailFragment
  774. *
  775. * @author David A. Velasco
  776. */
  777. public interface ContainerActivity extends TransferServiceGetter {
  778. /**
  779. * Callback method invoked when the detail fragment wants to notice its container
  780. * activity about a relevant state the file shown by the fragment.
  781. *
  782. * Added to notify to FileDisplayActivity about the need of refresh the files list.
  783. *
  784. * Currently called when:
  785. * - a download is started;
  786. * - a rename is completed;
  787. * - a deletion is completed;
  788. * - the 'inSync' flag is changed;
  789. */
  790. public void onFileStateChanged();
  791. }
  792. /*
  793. public void onDismiss(EditNameDialog dialog) {
  794. if (dialog.getResult()) {
  795. String newFilename = dialog.getNewFilename();
  796. Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
  797. mLastRemoteOperation = new RenameFileOperation( mFile,
  798. mAccount,
  799. newFilename,
  800. new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
  801. WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
  802. mLastRemoteOperation.execute(wc, this, mHandler);
  803. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  804. getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  805. }
  806. }
  807. */
  808. private class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
  809. /**
  810. * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
  811. *
  812. * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
  813. */
  814. private final WeakReference<ImageView> mImageViewRef;
  815. /**
  816. * Constructor.
  817. *
  818. * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
  819. */
  820. public BitmapLoader(ImageView imageView) {
  821. mImageViewRef = new WeakReference<ImageView>(imageView);
  822. }
  823. @SuppressWarnings("deprecation")
  824. @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
  825. @Override
  826. protected Bitmap doInBackground(String... params) {
  827. Bitmap result = null;
  828. if (params.length != 1) return result;
  829. String storagePath = params[0];
  830. try {
  831. // set desired options that will affect the size of the bitmap
  832. BitmapFactory.Options options = new Options();
  833. options.inScaled = true;
  834. options.inPurgeable = true;
  835. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
  836. options.inPreferQualityOverSpeed = false;
  837. }
  838. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
  839. options.inMutable = false;
  840. }
  841. // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
  842. options.inJustDecodeBounds = true;
  843. BitmapFactory.decodeFile(storagePath, options);
  844. int width = options.outWidth;
  845. int height = options.outHeight;
  846. int scale = 1;
  847. if (width >= 2048 || height >= 2048) {
  848. // try to scale down the image to save memory
  849. scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.)));
  850. options.inSampleSize = scale;
  851. }
  852. Display display = getActivity().getWindowManager().getDefaultDisplay();
  853. Point size = new Point();
  854. int screenwidth;
  855. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
  856. display.getSize(size);
  857. screenwidth = size.x;
  858. } else {
  859. screenwidth = display.getWidth();
  860. }
  861. Log.d(TAG, "image width: " + width + ", screen width: " + screenwidth);
  862. if (width > screenwidth) {
  863. // second try to scale down the image , this time depending upon the screen size; WTF...
  864. scale = (int) Math.ceil((float)width / screenwidth);
  865. options.inSampleSize = scale;
  866. }
  867. // really load the bitmap
  868. options.inJustDecodeBounds = false; // the next decodeFile call will be real
  869. result = BitmapFactory.decodeFile(storagePath, options);
  870. Log.e(TAG, "loaded width: " + options.outWidth + ", loaded height: " + options.outHeight);
  871. } catch (OutOfMemoryError e) {
  872. result = null;
  873. Log.e(TAG, "Out of memory occured for file with size " + storagePath);
  874. } catch (NoSuchFieldError e) {
  875. result = null;
  876. Log.e(TAG, "Error from access to unexisting field despite protection " + storagePath);
  877. } catch (Throwable t) {
  878. result = null;
  879. Log.e(TAG, "Unexpected error while creating image preview " + storagePath, t);
  880. }
  881. return result;
  882. }
  883. @Override
  884. protected void onPostExecute(Bitmap result) {
  885. if (result != null && mImageViewRef != null) {
  886. final ImageView imageView = mImageViewRef.get();
  887. imageView.setImageBitmap(result);
  888. mBitmap = result;
  889. }
  890. }
  891. }
  892. /**
  893. * Helper method to test if an {@link OCFile} can be passed to a {@link FilePreviewFragment} to be previewed.
  894. *
  895. * @param file File to test if can be previewed.
  896. * @return 'True' if the file can be handled by the fragment.
  897. */
  898. public static boolean canBePreviewed(OCFile file) {
  899. return (file != null && (file.isAudio() || file.isVideo() || file.isImage()));
  900. }
  901. /**
  902. * {@inheritDoc}
  903. */
  904. @Override
  905. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  906. if (operation.equals(mLastRemoteOperation)) {
  907. if (operation instanceof RemoveFileOperation) {
  908. onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
  909. /*
  910. } else if (operation instanceof RenameFileOperation) {
  911. onRenameFileOperationFinish((RenameFileOperation)operation, result);
  912. } else if (operation instanceof SynchronizeFileOperation) {
  913. onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);*/
  914. }
  915. }
  916. }
  917. private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
  918. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  919. getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  920. if (result.isSuccess()) {
  921. Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
  922. msg.show();
  923. finish();
  924. } else {
  925. Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
  926. msg.show();
  927. if (result.isSslRecoverableException()) {
  928. // TODO show the SSL warning dialog
  929. }
  930. }
  931. }
  932. private void stopPreview(boolean stopAudio) {
  933. if (mMediaController != null) {
  934. mMediaController.hide();
  935. }
  936. if (mFile.isAudio() && stopAudio) {
  937. mMediaServiceBinder.pause();
  938. } else if (mFile.isVideo()) {
  939. mVideoPreview.stopPlayback();
  940. }
  941. }
  942. /**
  943. * Finishes the preview
  944. */
  945. private void finish() {
  946. Activity container = getActivity();
  947. if (container instanceof FileDisplayActivity) {
  948. // double pane
  949. FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
  950. transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
  951. transaction.commit();
  952. ((FileFragment.ContainerActivity)container).onFileStateChanged();
  953. } else {
  954. container.finish();
  955. }
  956. }
  957. /*
  958. private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
  959. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  960. getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  961. if (result.isSuccess()) {
  962. updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
  963. mContainerActivity.onFileStateChanged();
  964. } else {
  965. if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
  966. Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
  967. msg.show();
  968. // TODO throw again the new rename dialog
  969. } else {
  970. Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
  971. msg.show();
  972. if (result.isSslRecoverableException()) {
  973. // TODO show the SSL warning dialog
  974. }
  975. }
  976. }
  977. }
  978. private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
  979. boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
  980. getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
  981. if (!result.isSuccess()) {
  982. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  983. Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
  984. i.putExtra(ConflictsResolveActivity.EXTRA_FILE, mFile);
  985. i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
  986. startActivity(i);
  987. } else {
  988. Toast msg = Toast.makeText(getActivity(), R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
  989. msg.show();
  990. }
  991. if (mFile.isDown()) {
  992. setButtonsForDown();
  993. } else {
  994. setButtonsForRemote();
  995. }
  996. } else {
  997. if (operation.transferWasRequested()) {
  998. mContainerActivity.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
  999. // checking the service to see if the file is downloading results in FALSE
  1000. } else {
  1001. Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
  1002. msg.show();
  1003. if (mFile.isDown()) {
  1004. setButtonsForDown();
  1005. } else {
  1006. setButtonsForRemote();
  1007. }
  1008. }
  1009. }
  1010. }
  1011. */
  1012. }