Added MediaController user interface to handle audio files in the MediaService
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / fragment / FileDetailFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
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 3 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.util.ArrayList;
22 import java.util.List;
23
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
37 import android.accounts.Account;
38 import android.accounts.AccountManager;
39 import android.annotation.SuppressLint;
40 import android.app.Activity;
41 import android.content.ActivityNotFoundException;
42 import android.content.BroadcastReceiver;
43 import android.content.ComponentName;
44 import android.content.Context;
45 import android.content.Intent;
46 import android.content.IntentFilter;
47 import android.content.ServiceConnection;
48 import android.graphics.Bitmap;
49 import android.graphics.BitmapFactory;
50 import android.graphics.BitmapFactory.Options;
51 import android.graphics.Point;
52 import android.net.Uri;
53 import android.os.AsyncTask;
54 import android.os.Bundle;
55 import android.os.Handler;
56 import android.os.IBinder;
57 import android.support.v4.app.DialogFragment;
58 import android.support.v4.app.FragmentTransaction;
59 import android.util.Log;
60 import android.view.Display;
61 import android.view.LayoutInflater;
62 import android.view.MotionEvent;
63 import android.view.View;
64 import android.view.View.OnClickListener;
65 import android.view.View.OnTouchListener;
66 import android.view.ViewGroup;
67 import android.webkit.MimeTypeMap;
68 import android.widget.Button;
69 import android.widget.CheckBox;
70 import android.widget.ImageView;
71 import android.widget.MediaController;
72 import android.widget.TextView;
73 import android.widget.Toast;
74
75 import com.actionbarsherlock.app.SherlockFragment;
76 import com.owncloud.android.AccountUtils;
77 import com.owncloud.android.DisplayUtils;
78 import com.owncloud.android.authenticator.AccountAuthenticator;
79 import com.owncloud.android.datamodel.FileDataStorageManager;
80 import com.owncloud.android.datamodel.OCFile;
81 import com.owncloud.android.files.services.FileDownloader;
82 import com.owncloud.android.files.services.FileObserverService;
83 import com.owncloud.android.files.services.FileUploader;
84 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
85 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
86 import com.owncloud.android.media.MediaService;
87 import com.owncloud.android.media.MediaServiceBinder;
88 import com.owncloud.android.network.OwnCloudClientUtils;
89 import com.owncloud.android.operations.OnRemoteOperationListener;
90 import com.owncloud.android.operations.RemoteOperation;
91 import com.owncloud.android.operations.RemoteOperationResult;
92 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
93 import com.owncloud.android.operations.RemoveFileOperation;
94 import com.owncloud.android.operations.RenameFileOperation;
95 import com.owncloud.android.operations.SynchronizeFileOperation;
96 import com.owncloud.android.ui.activity.ConflictsResolveActivity;
97 import com.owncloud.android.ui.activity.FileDetailActivity;
98 import com.owncloud.android.ui.activity.FileDisplayActivity;
99 import com.owncloud.android.ui.activity.TransferServiceGetter;
100 import com.owncloud.android.ui.dialog.EditNameDialog;
101 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
102 import com.owncloud.android.utils.OwnCloudVersion;
103
104 import com.owncloud.android.R;
105 import eu.alefzero.webdav.WebdavClient;
106 import eu.alefzero.webdav.WebdavUtils;
107
108 /**
109 * This Fragment is used to display the details about a file.
110 *
111 * @author Bartek Przybylski
112 *
113 */
114 public class FileDetailFragment extends SherlockFragment implements
115 OnClickListener, OnTouchListener,
116 ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener, EditNameDialogListener {
117
118 public static final String EXTRA_FILE = "FILE";
119 public static final String EXTRA_ACCOUNT = "ACCOUNT";
120
121 private FileDetailFragment.ContainerActivity mContainerActivity;
122
123 private int mLayout;
124 private View mView;
125 private OCFile mFile;
126 private Account mAccount;
127 private FileDataStorageManager mStorageManager;
128 private ImageView mPreview;
129
130 private DownloadFinishReceiver mDownloadFinishReceiver;
131 private UploadFinishReceiver mUploadFinishReceiver;
132
133 private Handler mHandler;
134 private RemoteOperation mLastRemoteOperation;
135 private DialogFragment mCurrentDialog;
136 private MediaServiceBinder mMediaServiceBinder = null;
137 private MediaController mMediaController = null;
138 private MediaServiceConnection mMediaServiceConnection = null;
139
140 private static final String TAG = FileDetailFragment.class.getSimpleName();
141 public static final String FTAG = "FileDetails";
142 public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
143
144
145 /**
146 * Creates an empty details fragment.
147 *
148 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
149 */
150 public FileDetailFragment() {
151 mFile = null;
152 mAccount = null;
153 mStorageManager = null;
154 mLayout = R.layout.file_details_empty;
155 }
156
157
158 /**
159 * Creates a details fragment.
160 *
161 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
162 *
163 * @param fileToDetail An {@link OCFile} to show in the fragment
164 * @param ocAccount An ownCloud account; needed to start downloads
165 */
166 public FileDetailFragment(OCFile fileToDetail, Account ocAccount) {
167 mFile = fileToDetail;
168 mAccount = ocAccount;
169 mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
170 mLayout = R.layout.file_details_empty;
171 }
172
173
174 @Override
175 public void onCreate(Bundle savedInstanceState) {
176 super.onCreate(savedInstanceState);
177 mHandler = new Handler();
178 }
179
180
181 @Override
182 public View onCreateView(LayoutInflater inflater, ViewGroup container,
183 Bundle savedInstanceState) {
184 super.onCreateView(inflater, container, savedInstanceState);
185
186 if (savedInstanceState != null) {
187 mFile = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
188 mAccount = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_ACCOUNT);
189 }
190
191 if(mFile != null && mAccount != null) {
192 mLayout = R.layout.file_details_fragment;
193 }
194
195 View view = null;
196 view = inflater.inflate(mLayout, container, false);
197 mView = view;
198
199 if (mLayout == R.layout.file_details_fragment) {
200 mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
201 mView.findViewById(R.id.fdRenameBtn).setOnClickListener(this);
202 mView.findViewById(R.id.fdDownloadBtn).setOnClickListener(this);
203 mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);
204 mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);
205 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
206 mPreview = (ImageView)mView.findViewById(R.id.fdPreview);
207 mPreview.setOnTouchListener(this);
208 }
209
210 updateFileDetails(false);
211 return view;
212 }
213
214
215 /**
216 * {@inheritDoc}
217 */
218 @Override
219 public void onAttach(Activity activity) {
220 super.onAttach(activity);
221 try {
222 mContainerActivity = (ContainerActivity) activity;
223 } catch (ClassCastException e) {
224 throw new ClassCastException(activity.toString() + " must implement " + FileDetailFragment.ContainerActivity.class.getSimpleName());
225 }
226 }
227
228
229 /**
230 * {@inheritDoc}
231 */
232 @Override
233 public void onActivityCreated(Bundle savedInstanceState) {
234 super.onActivityCreated(savedInstanceState);
235 if (mAccount != null) {
236 mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());;
237 }
238 }
239
240
241 @Override
242 public void onSaveInstanceState(Bundle outState) {
243 Log.i(getClass().toString(), "onSaveInstanceState() start");
244 super.onSaveInstanceState(outState);
245 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mFile);
246 outState.putParcelable(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
247 Log.i(getClass().toString(), "onSaveInstanceState() end");
248 }
249
250 @Override
251 public void onStart() {
252 super.onStart();
253 if (mFile != null && mFile.isAudio()) {
254 bindMediaService();
255 }
256 }
257
258 @Override
259 public void onResume() {
260 super.onResume();
261
262 mDownloadFinishReceiver = new DownloadFinishReceiver();
263 IntentFilter filter = new IntentFilter(
264 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
265 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
266
267 mUploadFinishReceiver = new UploadFinishReceiver();
268 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
269 getActivity().registerReceiver(mUploadFinishReceiver, filter);
270
271 mPreview = (ImageView)mView.findViewById(R.id.fdPreview); // this is here just because it is nullified in onPause()
272
273 if (mMediaController != null) {
274 mMediaController.show();
275 }
276 }
277
278
279 @Override
280 public void onPause() {
281 super.onPause();
282
283 getActivity().unregisterReceiver(mDownloadFinishReceiver);
284 mDownloadFinishReceiver = null;
285
286 getActivity().unregisterReceiver(mUploadFinishReceiver);
287 mUploadFinishReceiver = null;
288
289 if (mPreview != null) { // why?
290 mPreview = null;
291 }
292
293 if (mMediaController != null) {
294 mMediaController.hide();
295 }
296 }
297
298
299 @Override
300 public void onStop() {
301 super.onStop();
302 if (mMediaServiceConnection != null) {
303 Log.d(TAG, "Unbinding from MediaService ...");
304 getActivity().unbindService(mMediaServiceConnection);
305 mMediaServiceBinder = null;
306 mMediaController = null;
307 }
308 }
309
310
311 @Override
312 public View getView() {
313 return super.getView() == null ? mView : super.getView();
314 }
315
316
317 @Override
318 public void onClick(View v) {
319 switch (v.getId()) {
320 case R.id.fdDownloadBtn: {
321 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
322 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
323 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
324 downloaderBinder.cancel(mAccount, mFile);
325 if (mFile.isDown()) {
326 setButtonsForDown();
327 } else {
328 setButtonsForRemote();
329 }
330
331 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
332 uploaderBinder.cancel(mAccount, mFile);
333 if (!mFile.fileExists()) {
334 // TODO make something better
335 if (getActivity() instanceof FileDisplayActivity) {
336 // double pane
337 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
338 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FTAG); // empty FileDetailFragment
339 transaction.commit();
340 mContainerActivity.onFileStateChanged();
341 } else {
342 getActivity().finish();
343 }
344
345 } else if (mFile.isDown()) {
346 setButtonsForDown();
347 } else {
348 setButtonsForRemote();
349 }
350
351 } else {
352 mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());
353 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
354 mLastRemoteOperation.execute(wc, this, mHandler);
355
356 // update ui
357 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
358 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
359 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
360
361 }
362 break;
363 }
364 case R.id.fdKeepInSync: {
365 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
366 mFile.setKeepInSync(cb.isChecked());
367 mStorageManager.saveFile(mFile);
368
369 /// register the OCFile instance in the observer service to monitor local updates;
370 /// if necessary, the file is download
371 Intent intent = new Intent(getActivity().getApplicationContext(),
372 FileObserverService.class);
373 intent.putExtra(FileObserverService.KEY_FILE_CMD,
374 (cb.isChecked()?
375 FileObserverService.CMD_ADD_OBSERVED_FILE:
376 FileObserverService.CMD_DEL_OBSERVED_FILE));
377 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
378 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
379 Log.e(TAG, "starting observer service");
380 getActivity().startService(intent);
381
382 if (mFile.keepInSync()) {
383 onClick(getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
384 }
385 break;
386 }
387 case R.id.fdRenameBtn: {
388 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), mFile.getFileName(), this);
389 dialog.show(getFragmentManager(), "nameeditdialog");
390 break;
391 }
392 case R.id.fdRemoveBtn: {
393 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
394 R.string.confirmation_remove_alert,
395 new String[]{mFile.getFileName()},
396 mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
397 mFile.isDown() ? R.string.confirmation_remove_local : -1,
398 R.string.common_cancel);
399 confDialog.setOnConfirmationListener(this);
400 mCurrentDialog = confDialog;
401 mCurrentDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
402 break;
403 }
404 case R.id.fdOpenBtn: {
405 openFile();
406 break;
407 }
408 default:
409 Log.e(TAG, "Incorrect view clicked!");
410 }
411
412 /* else if (v.getId() == R.id.fdShareBtn) {
413 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
414 t.start();
415 }*/
416 }
417
418
419 @Override
420 public boolean onTouch(View v, MotionEvent event) {
421 if (v == mPreview && event.getAction() == MotionEvent.ACTION_DOWN && mFile != null && mFile.isDown() && mFile.isAudio()) {
422 if (!mMediaServiceBinder.isPlaying(mFile)) {
423 Log.d(TAG, "starting playback of " + mFile.getStoragePath());
424 mMediaServiceBinder.start(mAccount, mFile);
425 // this is a patch; need to synchronize this with the onPrepared() coming from MediaPlayer in the MediaService
426 mMediaController.postDelayed(new Runnable() {
427 @Override
428 public void run() {
429 mMediaController.show(0);
430 }
431 } , 300);
432 } else {
433 mMediaController.show(0);
434 }
435 }
436 return false;
437 }
438
439
440 private void bindMediaService() {
441 Log.d(TAG, "Binding to MediaService...");
442 if (mMediaServiceConnection == null) {
443 mMediaServiceConnection = new MediaServiceConnection();
444 }
445 getActivity().bindService( new Intent(getActivity(),
446 MediaService.class),
447 mMediaServiceConnection,
448 Context.BIND_AUTO_CREATE);
449 }
450
451 /** Defines callbacks for service binding, passed to bindService() */
452 private class MediaServiceConnection implements ServiceConnection {
453
454 @Override
455 public void onServiceConnected(ComponentName component, IBinder service) {
456 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
457 Log.d(TAG, "Media service connected");
458 mMediaServiceBinder = (MediaServiceBinder) service;
459 if (mMediaServiceBinder != null) {
460 if (mMediaController == null) {
461 mMediaController = new MediaController(getSherlockActivity());
462 }
463 mMediaController.setMediaPlayer(mMediaServiceBinder);
464 mMediaController.setAnchorView(mPreview);
465 mMediaController.setEnabled(true);
466
467 Log.d(TAG, "Successfully bound to MediaService, MediaController ready");
468
469 } else {
470 Log.e(TAG, "Unexpected response from MediaService while binding");
471 }
472 }
473 }
474
475 @Override
476 public void onServiceDisconnected(ComponentName component) {
477 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
478 Log.d(TAG, "Media service suddenly disconnected");
479 if (mMediaController != null) {
480 mMediaController.hide();
481 mMediaController.setMediaPlayer(null); // TODO check this is not an error
482 mMediaController = null;
483 }
484 mMediaServiceBinder = null;
485 mMediaServiceConnection = null;
486 }
487 }
488 }
489
490
491 /**
492 * Opens mFile.
493 */
494 private void openFile() {
495
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
504 } catch (Throwable t) {
505 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
506 boolean toastIt = true;
507 String mimeType = "";
508 try {
509 Intent i = new Intent(Intent.ACTION_VIEW);
510 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
511 if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
512 if (mimeType != null) {
513 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
514 } else {
515 // desperate try
516 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*/*");
517 }
518 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
519 startActivity(i);
520 toastIt = false;
521 }
522
523 } catch (IndexOutOfBoundsException e) {
524 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
525
526 } catch (ActivityNotFoundException e) {
527 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
528
529 } catch (Throwable th) {
530 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
531
532 } finally {
533 if (toastIt) {
534 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
535 }
536 }
537
538 }
539 }
540
541
542 @Override
543 public void onConfirmation(String callerTag) {
544 if (callerTag.equals(FTAG_CONFIRMATION)) {
545 if (mStorageManager.getFileById(mFile.getFileId()) != null) {
546 mLastRemoteOperation = new RemoveFileOperation( mFile,
547 true,
548 mStorageManager);
549 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
550 mLastRemoteOperation.execute(wc, this, mHandler);
551
552 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
553 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
554 }
555 }
556 mCurrentDialog.dismiss();
557 mCurrentDialog = null;
558 }
559
560 @Override
561 public void onNeutral(String callerTag) {
562 File f = null;
563 if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {
564 f.delete();
565 mFile.setStoragePath(null);
566 mStorageManager.saveFile(mFile);
567 updateFileDetails(mFile, mAccount);
568 }
569 mCurrentDialog.dismiss();
570 mCurrentDialog = null;
571 }
572
573 @Override
574 public void onCancel(String callerTag) {
575 Log.d(TAG, "REMOVAL CANCELED");
576 mCurrentDialog.dismiss();
577 mCurrentDialog = null;
578 }
579
580
581 /**
582 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
583 *
584 * @return True when the fragment was created with the empty layout.
585 */
586 public boolean isEmpty() {
587 return (mLayout == R.layout.file_details_empty || mFile == null || mAccount == null);
588 }
589
590
591 /**
592 * Can be used to get the file that is currently being displayed.
593 * @return The file on the screen.
594 */
595 public OCFile getDisplayedFile(){
596 return mFile;
597 }
598
599 /**
600 * Use this method to signal this Activity that it shall update its view.
601 *
602 * @param file : An {@link OCFile}
603 */
604 public void updateFileDetails(OCFile file, Account ocAccount) {
605 mFile = file;
606 if (ocAccount != null && (
607 mStorageManager == null ||
608 (mAccount != null && !mAccount.equals(ocAccount))
609 )) {
610 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
611 }
612 mAccount = ocAccount;
613 updateFileDetails(false);
614 }
615
616
617 /**
618 * Updates the view with all relevant details about that file.
619 *
620 * TODO Remove parameter when the transferring state of files is kept in database.
621 *
622 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
623 *
624 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
625 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
626 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
627 *
628 */
629 public void updateFileDetails(boolean transferring) {
630
631 if (readyToShow()) {
632
633 // set file details
634 setFilename(mFile.getFileName());
635 setFiletype(mFile.getMimetype());
636 setFilesize(mFile.getFileLength());
637 if(ocVersionSupportsTimeCreated()){
638 setTimeCreated(mFile.getCreationTimestamp());
639 }
640
641 setTimeModified(mFile.getModificationTimestamp());
642
643 CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
644 cb.setChecked(mFile.keepInSync());
645
646 // configure UI for depending upon local state of the file
647 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
648 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
649 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
650 if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile))) {
651 setButtonsForTransferring();
652
653 } else if (mFile.isDown()) {
654 // Update preview
655 if (mFile.getMimetype().startsWith("image/")) {
656 BitmapLoader bl = new BitmapLoader();
657 bl.execute(new String[]{mFile.getStoragePath()});
658 }
659
660 setButtonsForDown();
661
662 } else {
663 // TODO load default preview image; when the local file is removed, the preview remains there
664 setButtonsForRemote();
665 }
666 }
667 getView().invalidate();
668 }
669
670
671 /**
672 * Checks if the fragment is ready to show details of a OCFile
673 *
674 * @return 'True' when the fragment is ready to show details of a file
675 */
676 private boolean readyToShow() {
677 return (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment);
678 }
679
680
681
682 /**
683 * Updates the filename in view
684 * @param filename to set
685 */
686 private void setFilename(String filename) {
687 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
688 if (tv != null)
689 tv.setText(filename);
690 }
691
692 /**
693 * Updates the MIME type in view
694 * @param mimetype to set
695 */
696 private void setFiletype(String mimetype) {
697 TextView tv = (TextView) getView().findViewById(R.id.fdType);
698 if (tv != null) {
699 String printableMimetype = DisplayUtils.convertMIMEtoPrettyPrint(mimetype);;
700 tv.setText(printableMimetype);
701 }
702 ImageView iv = (ImageView) getView().findViewById(R.id.fdIcon);
703 if (iv != null) {
704 iv.setImageResource(DisplayUtils.getResourceId(mimetype));
705 }
706 }
707
708 /**
709 * Updates the file size in view
710 * @param filesize in bytes to set
711 */
712 private void setFilesize(long filesize) {
713 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
714 if (tv != null)
715 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
716 }
717
718 /**
719 * Updates the time that the file was created in view
720 * @param milliseconds Unix time to set
721 */
722 private void setTimeCreated(long milliseconds){
723 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
724 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
725 if(tv != null){
726 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
727 tv.setVisibility(View.VISIBLE);
728 tvLabel.setVisibility(View.VISIBLE);
729 }
730 }
731
732 /**
733 * Updates the time that the file was last modified
734 * @param milliseconds Unix time to set
735 */
736 private void setTimeModified(long milliseconds){
737 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
738 if(tv != null){
739 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
740 }
741 }
742
743 /**
744 * Enables or disables buttons for a file being downloaded
745 */
746 private void setButtonsForTransferring() {
747 if (!isEmpty()) {
748 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
749 downloadButton.setText(R.string.common_cancel);
750 //downloadButton.setEnabled(false);
751
752 // let's protect the user from himself ;)
753 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
754 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(false);
755 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(false);
756 getView().findViewById(R.id.fdKeepInSync).setEnabled(false);
757 }
758 }
759
760 /**
761 * Enables or disables buttons for a file locally available
762 */
763 private void setButtonsForDown() {
764 if (!isEmpty()) {
765 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
766 downloadButton.setText(R.string.filedetails_sync_file);
767
768 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(true);
769 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
770 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
771 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
772 }
773 }
774
775 /**
776 * Enables or disables buttons for a file not locally available
777 */
778 private void setButtonsForRemote() {
779 if (!isEmpty()) {
780 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
781 downloadButton.setText(R.string.filedetails_download);
782
783 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
784 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
785 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
786 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
787 }
788 }
789
790
791 /**
792 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
793 * the time that the file was created. There is a chance that this will
794 * be fixed in future versions. Use this method to check if this version of
795 * ownCloud has this fix.
796 * @return True, if ownCloud the ownCloud version is supporting creation time
797 */
798 private boolean ocVersionSupportsTimeCreated(){
799 /*if(mAccount != null){
800 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
801 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
802 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
803 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
804 return true;
805 }
806 }*/
807 return false;
808 }
809
810
811 /**
812 * Interface to implement by any Activity that includes some instance of FileDetailFragment
813 *
814 * @author David A. Velasco
815 */
816 public interface ContainerActivity extends TransferServiceGetter {
817
818 /**
819 * Callback method invoked when the detail fragment wants to notice its container
820 * activity about a relevant state the file shown by the fragment.
821 *
822 * Added to notify to FileDisplayActivity about the need of refresh the files list.
823 *
824 * Currently called when:
825 * - a download is started;
826 * - a rename is completed;
827 * - a deletion is completed;
828 * - the 'inSync' flag is changed;
829 */
830 public void onFileStateChanged();
831
832 }
833
834
835 /**
836 * Once the file download has finished -> update view
837 * @author Bartek Przybylski
838 */
839 private class DownloadFinishReceiver extends BroadcastReceiver {
840 @Override
841 public void onReceive(Context context, Intent intent) {
842 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
843
844 if (!isEmpty() && accountName.equals(mAccount.name)) {
845 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
846 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
847 if (mFile.getRemotePath().equals(downloadedRemotePath)) {
848 if (downloadWasFine) {
849 mFile = mStorageManager.getFileByPath(downloadedRemotePath);
850 }
851 updateFileDetails(false); // it updates the buttons; must be called although !downloadWasFine
852 }
853 }
854 }
855 }
856
857
858 /**
859 * Once the file upload has finished -> update view
860 *
861 * Being notified about the finish of an upload is necessary for the next sequence:
862 * 1. Upload a big file.
863 * 2. Force a synchronization; if it finished before the upload, the file in transfer will be included in the local database and in the file list
864 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
865 * 3. Click the file in the list to see its details.
866 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
867 */
868 private class UploadFinishReceiver extends BroadcastReceiver {
869 @Override
870 public void onReceive(Context context, Intent intent) {
871 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
872
873 if (!isEmpty() && accountName.equals(mAccount.name)) {
874 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
875 String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
876 boolean renamedInUpload = mFile.getRemotePath().equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
877 if (mFile.getRemotePath().equals(uploadRemotePath) ||
878 renamedInUpload) {
879 if (uploadWasFine) {
880 mFile = mStorageManager.getFileByPath(uploadRemotePath);
881 }
882 if (renamedInUpload) {
883 String newName = (new File(uploadRemotePath)).getName();
884 Toast msg = Toast.makeText(getActivity().getApplicationContext(), String.format(getString(R.string.filedetails_renamed_in_upload_msg), newName), Toast.LENGTH_LONG);
885 msg.show();
886 }
887 getSherlockActivity().removeStickyBroadcast(intent); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
888 updateFileDetails(false); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
889 }
890 }
891 }
892 }
893
894
895 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
896 @SuppressWarnings("unused")
897 private class ShareRunnable implements Runnable {
898 private String mPath;
899
900 public ShareRunnable(String path) {
901 mPath = path;
902 }
903
904 public void run() {
905 AccountManager am = AccountManager.get(getActivity());
906 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
907 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
908 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
909
910 Log.d("share", "sharing for version " + ocv.toString());
911
912 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
913 String APPS_PATH = "/apps/files_sharing/";
914 String SHARE_PATH = "ajax/share.php";
915
916 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
917
918 final String WEBDAV_SCRIPT = "webdav.php";
919 final String WEBDAV_FILES_LOCATION = "/files/";
920
921 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
922 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
923 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
924
925 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
926 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
927
928 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
929
930 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
931 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
932 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
933 Log.d("share", mPath+"");
934 formparams.add(new BasicNameValuePair("sources",mPath));
935 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
936 formparams.add(new BasicNameValuePair("permissions", "0"));
937 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
938
939 int status;
940 try {
941 PropFindMethod find = new PropFindMethod(url+"/");
942 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
943 Log.d("sharer", ""+ url+"/");
944
945 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
946 Log.d("sharer-h", a.getName() + ":"+a.getValue());
947 }
948
949 int status2 = wc.executeMethod(find);
950
951 Log.d("sharer", "propstatus "+status2);
952
953 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
954 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
955
956 status2 = wc.executeMethod(get);
957
958 Log.d("sharer", "getstatus "+status2);
959 Log.d("sharer", "" + get.getResponseBodyAsString());
960
961 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
962 Log.d("sharer", a.getName() + ":"+a.getValue());
963 }
964
965 status = wc.executeMethod(post);
966 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
967 Log.d("sharer-h", a.getName() + ":"+a.getValue());
968 }
969 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
970 Log.d("sharer", a.getName() + ":"+a.getValue());
971 }
972 String resp = post.getResponseBodyAsString();
973 Log.d("share", ""+post.getURI().toString());
974 Log.d("share", "returned status " + status);
975 Log.d("share", " " +resp);
976
977 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
978 return;
979 }
980
981 JSONObject jsonObject = new JSONObject (resp);
982 String jsonStatus = jsonObject.getString("status");
983 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
984
985 String token = jsonObject.getString("data");
986 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
987 Log.d("Actions:shareFile ok", "url: " + uri);
988
989 } catch (Exception e) {
990 e.printStackTrace();
991 }
992
993 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
994
995 }
996 }
997 }
998
999 public void onDismiss(EditNameDialog dialog) {
1000 if (dialog.getResult()) {
1001 String newFilename = dialog.getNewFilename();
1002 Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
1003 mLastRemoteOperation = new RenameFileOperation( mFile,
1004 mAccount,
1005 newFilename,
1006 new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
1007 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
1008 mLastRemoteOperation.execute(wc, this, mHandler);
1009 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1010 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1011 }
1012 }
1013
1014
1015 class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
1016 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1017 @Override
1018 protected Bitmap doInBackground(String... params) {
1019 Bitmap result = null;
1020 if (params.length != 1) return result;
1021 String storagePath = params[0];
1022 try {
1023
1024 BitmapFactory.Options options = new Options();
1025 options.inScaled = true;
1026 options.inPurgeable = true;
1027 options.inJustDecodeBounds = true;
1028 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
1029 options.inPreferQualityOverSpeed = false;
1030 }
1031 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1032 options.inMutable = false;
1033 }
1034
1035 result = BitmapFactory.decodeFile(storagePath, options);
1036 options.inJustDecodeBounds = false;
1037
1038 int width = options.outWidth;
1039 int height = options.outHeight;
1040 int scale = 1;
1041 if (width >= 2048 || height >= 2048) {
1042 scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.)));
1043 options.inSampleSize = scale;
1044 }
1045 Display display = getActivity().getWindowManager().getDefaultDisplay();
1046 Point size = new Point();
1047 int screenwidth;
1048 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
1049 display.getSize(size);
1050 screenwidth = size.x;
1051 } else {
1052 screenwidth = display.getWidth();
1053 }
1054
1055 Log.e("ASD", "W " + width + " SW " + screenwidth);
1056
1057 if (width > screenwidth) {
1058 scale = (int) Math.ceil((float)width / screenwidth);
1059 options.inSampleSize = scale;
1060 }
1061
1062 result = BitmapFactory.decodeFile(storagePath, options);
1063
1064 Log.e("ASD", "W " + options.outWidth + " SW " + options.outHeight);
1065
1066 } catch (OutOfMemoryError e) {
1067 result = null;
1068 Log.e(TAG, "Out of memory occured for file with size " + storagePath);
1069
1070 } catch (NoSuchFieldError e) {
1071 result = null;
1072 Log.e(TAG, "Error from access to unexisting field despite protection " + storagePath);
1073
1074 } catch (Throwable t) {
1075 result = null;
1076 Log.e(TAG, "Unexpected error while creating image preview " + storagePath, t);
1077 }
1078 return result;
1079 }
1080 @Override
1081 protected void onPostExecute(Bitmap result) {
1082 if (result != null && mPreview != null) {
1083 mPreview.setImageBitmap(result);
1084 }
1085 }
1086
1087 }
1088
1089 /**
1090 * {@inheritDoc}
1091 */
1092 @Override
1093 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1094 if (operation.equals(mLastRemoteOperation)) {
1095 if (operation instanceof RemoveFileOperation) {
1096 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1097
1098 } else if (operation instanceof RenameFileOperation) {
1099 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1100
1101 } else if (operation instanceof SynchronizeFileOperation) {
1102 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1103 }
1104 }
1105 }
1106
1107
1108 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1109 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1110 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1111
1112 if (result.isSuccess()) {
1113 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
1114 msg.show();
1115 if (inDisplayActivity) {
1116 // double pane
1117 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
1118 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
1119 transaction.commit();
1120 mContainerActivity.onFileStateChanged();
1121 } else {
1122 getActivity().finish();
1123 }
1124
1125 } else {
1126 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
1127 msg.show();
1128 if (result.isSslRecoverableException()) {
1129 // TODO show the SSL warning dialog
1130 }
1131 }
1132 }
1133
1134 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1135 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1136 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1137
1138 if (result.isSuccess()) {
1139 updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
1140 mContainerActivity.onFileStateChanged();
1141
1142 } else {
1143 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1144 Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1145 msg.show();
1146 // TODO throw again the new rename dialog
1147 } else {
1148 Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1149 msg.show();
1150 if (result.isSslRecoverableException()) {
1151 // TODO show the SSL warning dialog
1152 }
1153 }
1154 }
1155 }
1156
1157 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1158 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1159 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1160
1161 if (!result.isSuccess()) {
1162 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1163 Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
1164 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, mFile);
1165 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
1166 startActivity(i);
1167
1168 } else {
1169 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1170 msg.show();
1171 }
1172
1173 if (mFile.isDown()) {
1174 setButtonsForDown();
1175
1176 } else {
1177 setButtonsForRemote();
1178 }
1179
1180 } else {
1181 if (operation.transferWasRequested()) {
1182 mContainerActivity.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1183 // checking the service to see if the file is downloading results in FALSE
1184 } else {
1185 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1186 msg.show();
1187 if (mFile.isDown()) {
1188 setButtonsForDown();
1189
1190 } else {
1191 setButtonsForRemote();
1192 }
1193 }
1194 }
1195 }
1196
1197
1198 }