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