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