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