Fixed regression after merge: removed 'about' entry in menu
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / fragment / FileDetailFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19 package com.owncloud.android.ui.fragment;
20
21 import java.io.File;
22 import java.lang.ref.WeakReference;
23 import java.util.ArrayList;
24 import java.util.List;
25
26 import org.apache.commons.httpclient.methods.GetMethod;
27 import org.apache.commons.httpclient.methods.PostMethod;
28 import org.apache.commons.httpclient.methods.StringRequestEntity;
29 import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
30 import org.apache.http.HttpStatus;
31 import org.apache.http.NameValuePair;
32 import org.apache.http.client.utils.URLEncodedUtils;
33 import org.apache.http.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.Context;
45 import android.content.Intent;
46 import android.content.IntentFilter;
47 import android.net.Uri;
48 import android.os.Bundle;
49 import android.os.Handler;
50 import android.support.v4.app.FragmentTransaction;
51 import android.util.Log;
52 import android.view.LayoutInflater;
53 import android.view.View;
54 import android.view.View.OnClickListener;
55 import android.view.ViewGroup;
56 import android.webkit.MimeTypeMap;
57 import android.widget.Button;
58 import android.widget.CheckBox;
59 import android.widget.ImageView;
60 import android.widget.ProgressBar;
61 import android.widget.TextView;
62 import android.widget.Toast;
63
64 import android.graphics.Bitmap;
65 import android.graphics.BitmapFactory;
66 import android.graphics.BitmapFactory.Options;
67 import android.graphics.Point;
68 import android.net.Uri;
69 import android.os.AsyncTask;
70 import android.os.Bundle;
71 import android.os.Handler;
72 import android.support.v4.app.DialogFragment;
73 import android.support.v4.app.FragmentTransaction;
74 import android.util.Log;
75 import android.view.Display;
76 import android.view.LayoutInflater;
77 import android.view.View;
78 import android.view.View.OnClickListener;
79 import android.view.ViewGroup;
80 import android.webkit.MimeTypeMap;
81 import android.widget.Button;
82 import android.widget.CheckBox;
83 import android.widget.ImageView;
84 import android.widget.TextView;
85 import android.widget.Toast;
86
87
88 import com.actionbarsherlock.app.SherlockFragment;
89 import com.owncloud.android.AccountUtils;
90 import com.owncloud.android.DisplayUtils;
91 import com.owncloud.android.Log_OC;
92 import com.owncloud.android.authenticator.AccountAuthenticator;
93 import com.owncloud.android.datamodel.FileDataStorageManager;
94 import com.owncloud.android.datamodel.OCFile;
95 import com.owncloud.android.files.services.FileObserverService;
96 import com.owncloud.android.files.services.FileUploader;
97 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
98 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
99 import com.owncloud.android.network.OwnCloudClientUtils;
100 import com.owncloud.android.operations.OnRemoteOperationListener;
101 import com.owncloud.android.operations.RemoteOperation;
102 import com.owncloud.android.operations.RemoteOperationResult;
103 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
104 import com.owncloud.android.operations.RemoveFileOperation;
105 import com.owncloud.android.operations.RenameFileOperation;
106 import com.owncloud.android.operations.SynchronizeFileOperation;
107 import com.owncloud.android.ui.activity.ConflictsResolveActivity;
108 import com.owncloud.android.ui.activity.FileDetailActivity;
109 import com.owncloud.android.ui.activity.FileDisplayActivity;
110 import com.owncloud.android.ui.dialog.EditNameDialog;
111 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
112 import com.owncloud.android.utils.OwnCloudVersion;
113
114 import com.owncloud.android.R;
115
116 import eu.alefzero.webdav.OnDatatransferProgressListener;
117 import eu.alefzero.webdav.WebdavClient;
118 import eu.alefzero.webdav.WebdavUtils;
119
120
121 /**
122 * This Fragment is used to display the details about a file.
123 *
124 * @author Bartek Przybylski
125 * @author David A. Velasco
126 */
127 public class FileDetailFragment extends SherlockFragment implements
128 OnClickListener,
129 ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener, EditNameDialogListener,
130 FileFragment {
131
132 public static final String EXTRA_FILE = "FILE";
133 public static final String EXTRA_ACCOUNT = "ACCOUNT";
134
135 private FileFragment.ContainerActivity mContainerActivity;
136
137 private int mLayout;
138 private View mView;
139 private OCFile mFile;
140 private Account mAccount;
141 private FileDataStorageManager mStorageManager;
142
143 private UploadFinishReceiver mUploadFinishReceiver;
144 public ProgressListener mProgressListener;
145
146 private Handler mHandler;
147 private RemoteOperation mLastRemoteOperation;
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, 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 }
250 }
251
252
253 @Override
254 public void onSaveInstanceState(Bundle outState) {
255 super.onSaveInstanceState(outState);
256 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mFile);
257 outState.putParcelable(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
258 }
259
260 @Override
261 public void onStart() {
262 super.onStart();
263 listenForTransferProgress();
264 }
265
266 @Override
267 public void onResume() {
268 super.onResume();
269 mUploadFinishReceiver = new UploadFinishReceiver();
270 IntentFilter filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
271 getActivity().registerReceiver(mUploadFinishReceiver, filter);
272
273 }
274
275
276 @Override
277 public void onPause() {
278 super.onPause();
279 if (mUploadFinishReceiver != null) {
280 getActivity().unregisterReceiver(mUploadFinishReceiver);
281 mUploadFinishReceiver = null;
282 }
283 }
284
285
286 @Override
287 public void onStop() {
288 super.onStop();
289 leaveTransferProgress();
290 }
291
292
293 @Override
294 public View getView() {
295 return super.getView() == null ? mView : super.getView();
296 }
297
298 @Override
299 public void onClick(View v) {
300 switch (v.getId()) {
301 case R.id.fdDownloadBtn: {
302 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
303 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
304 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
305 downloaderBinder.cancel(mAccount, mFile);
306 if (mFile.isDown()) {
307 setButtonsForDown();
308 } else {
309 setButtonsForRemote();
310 }
311
312 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
313 uploaderBinder.cancel(mAccount, mFile);
314 if (!mFile.fileExists()) {
315 // TODO make something better
316 if (getActivity() instanceof FileDisplayActivity) {
317 // double pane
318 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
319 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FTAG); // empty FileDetailFragment
320 transaction.commit();
321 mContainerActivity.onFileStateChanged();
322 } else {
323 getActivity().finish();
324 }
325
326 } else if (mFile.isDown()) {
327 setButtonsForDown();
328 } else {
329 setButtonsForRemote();
330 }
331
332 } else {
333 mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());
334 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
335 mLastRemoteOperation.execute(wc, this, mHandler);
336
337 // update ui
338 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
339 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
340
341 }
342 break;
343 }
344 case R.id.fdKeepInSync: {
345 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
346 mFile.setKeepInSync(cb.isChecked());
347 mStorageManager.saveFile(mFile);
348
349 /// register the OCFile instance in the observer service to monitor local updates;
350 /// if necessary, the file is download
351 Intent intent = new Intent(getActivity().getApplicationContext(),
352 FileObserverService.class);
353 intent.putExtra(FileObserverService.KEY_FILE_CMD,
354 (cb.isChecked()?
355 FileObserverService.CMD_ADD_OBSERVED_FILE:
356 FileObserverService.CMD_DEL_OBSERVED_FILE));
357 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
358 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
359 getActivity().startService(intent);
360
361 if (mFile.keepInSync()) {
362 onClick(getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
363 }
364 break;
365 }
366 case R.id.fdRenameBtn: {
367 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), mFile.getFileName(), this);
368 dialog.show(getFragmentManager(), "nameeditdialog");
369 break;
370 }
371 case R.id.fdRemoveBtn: {
372 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
373 R.string.confirmation_remove_alert,
374 new String[]{mFile.getFileName()},
375 mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
376 mFile.isDown() ? R.string.confirmation_remove_local : -1,
377 R.string.common_cancel);
378 confDialog.setOnConfirmationListener(this);
379 confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
380 break;
381 }
382 case R.id.fdOpenBtn: {
383 openFile();
384 break;
385 }
386 default:
387 Log_OC.e(TAG, "Incorrect view clicked!");
388 }
389
390 /* else if (v.getId() == R.id.fdShareBtn) {
391 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
392 t.start();
393 }*/
394 }
395
396
397 /**
398 * Opens mFile.
399 */
400 private void openFile() {
401
402 String storagePath = mFile.getStoragePath();
403 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
404 try {
405 Intent i = new Intent(Intent.ACTION_VIEW);
406 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
407 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
408 startActivity(i);
409
410 } catch (Throwable t) {
411 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
412 boolean toastIt = true;
413 String mimeType = "";
414 try {
415 Intent i = new Intent(Intent.ACTION_VIEW);
416 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
417 if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
418 if (mimeType != null) {
419 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
420 } else {
421 // desperate try
422 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*/*");
423 }
424 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
425 startActivity(i);
426 toastIt = false;
427 }
428
429 } catch (IndexOutOfBoundsException e) {
430 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
431
432 } catch (ActivityNotFoundException e) {
433 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
434
435 } catch (Throwable th) {
436 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
437
438 } finally {
439 if (toastIt) {
440 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
441 }
442 }
443
444 }
445 }
446
447
448 @Override
449 public void onConfirmation(String callerTag) {
450 if (callerTag.equals(FTAG_CONFIRMATION)) {
451 if (mStorageManager.getFileById(mFile.getFileId()) != null) {
452 mLastRemoteOperation = new RemoveFileOperation( mFile,
453 true,
454 mStorageManager);
455 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
456 mLastRemoteOperation.execute(wc, this, mHandler);
457
458 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
459 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
460 }
461 }
462 }
463
464 @Override
465 public void onNeutral(String callerTag) {
466 File f = null;
467 if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {
468 f.delete();
469 mFile.setStoragePath(null);
470 mStorageManager.saveFile(mFile);
471 updateFileDetails(mFile, mAccount);
472 }
473 }
474
475 @Override
476 public void onCancel(String callerTag) {
477 Log.d(TAG, "REMOVAL CANCELED");
478 }
479
480
481 /**
482 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
483 *
484 * @return True when the fragment was created with the empty layout.
485 */
486 public boolean isEmpty() {
487 return (mLayout == R.layout.file_details_empty || mFile == null || mAccount == null);
488 }
489
490
491 /**
492 * {@inheritDoc}
493 */
494 public OCFile getFile(){
495 return mFile;
496 }
497
498 /**
499 * Use this method to signal this Activity that it shall update its view.
500 *
501 * @param file : An {@link OCFile}
502 */
503 public void updateFileDetails(OCFile file, Account ocAccount) {
504 mFile = file;
505 if (ocAccount != null && (
506 mStorageManager == null ||
507 (mAccount != null && !mAccount.equals(ocAccount))
508 )) {
509 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
510 }
511 mAccount = ocAccount;
512 updateFileDetails(false, false);
513 }
514
515 /**
516 * Updates the view with all relevant details about that file.
517 *
518 * TODO Remove parameter when the transferring state of files is kept in database.
519 *
520 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
521 *
522 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
523 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
524 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
525 *
526 * @param refresh If 'true', try to refresh the hold file from the database
527 */
528 public void updateFileDetails(boolean transferring, boolean refresh) {
529
530 if (readyToShow()) {
531
532 if (refresh && mStorageManager != null) {
533 mFile = mStorageManager.getFileByPath(mFile.getRemotePath());
534 }
535
536 // set file details
537 setFilename(mFile.getFileName());
538 setFiletype(mFile.getMimetype());
539 setFilesize(mFile.getFileLength());
540 if(ocVersionSupportsTimeCreated()){
541 setTimeCreated(mFile.getCreationTimestamp());
542 }
543
544 setTimeModified(mFile.getModificationTimestamp());
545
546 CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
547 cb.setChecked(mFile.keepInSync());
548
549 // configure UI for depending upon local state of the file
550 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
551 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
552 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
553 if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile))) {
554 setButtonsForTransferring();
555
556 } else if (mFile.isDown()) {
557
558 setButtonsForDown();
559
560 } else {
561 // TODO load default preview image; when the local file is removed, the preview remains there
562 setButtonsForRemote();
563 }
564 }
565 getView().invalidate();
566 }
567
568
569 /**
570 * Checks if the fragment is ready to show details of a OCFile
571 *
572 * @return 'True' when the fragment is ready to show details of a file
573 */
574 private boolean readyToShow() {
575 return (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment);
576 }
577
578
579 /**
580 * Updates the filename in view
581 * @param filename to set
582 */
583 private void setFilename(String filename) {
584 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
585 if (tv != null)
586 tv.setText(filename);
587 }
588
589 /**
590 * Updates the MIME type in view
591 * @param mimetype to set
592 */
593 private void setFiletype(String mimetype) {
594 TextView tv = (TextView) getView().findViewById(R.id.fdType);
595 if (tv != null) {
596 String printableMimetype = DisplayUtils.convertMIMEtoPrettyPrint(mimetype);;
597 tv.setText(printableMimetype);
598 }
599 ImageView iv = (ImageView) getView().findViewById(R.id.fdIcon);
600 if (iv != null) {
601 iv.setImageResource(DisplayUtils.getResourceId(mimetype));
602 }
603 }
604
605 /**
606 * Updates the file size in view
607 * @param filesize in bytes to set
608 */
609 private void setFilesize(long filesize) {
610 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
611 if (tv != null)
612 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
613 }
614
615 /**
616 * Updates the time that the file was created in view
617 * @param milliseconds Unix time to set
618 */
619 private void setTimeCreated(long milliseconds){
620 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
621 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
622 if(tv != null){
623 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
624 tv.setVisibility(View.VISIBLE);
625 tvLabel.setVisibility(View.VISIBLE);
626 }
627 }
628
629 /**
630 * Updates the time that the file was last modified
631 * @param milliseconds Unix time to set
632 */
633 private void setTimeModified(long milliseconds){
634 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
635 if(tv != null){
636 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
637 }
638 }
639
640 /**
641 * Enables or disables buttons for a file being downloaded
642 */
643 private void setButtonsForTransferring() {
644 if (!isEmpty()) {
645 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
646 downloadButton.setText(R.string.common_cancel);
647 //downloadButton.setEnabled(false);
648
649 // let's protect the user from himself ;)
650 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
651 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(false);
652 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(false);
653 getView().findViewById(R.id.fdKeepInSync).setEnabled(false);
654
655 // show the progress bar for the transfer
656 ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
657 progressBar.setVisibility(View.VISIBLE);
658 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
659 progressText.setVisibility(View.VISIBLE);
660 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
661 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
662 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
663 progressText.setText(R.string.downloader_download_in_progress_ticker);
664 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
665 progressText.setText(R.string.uploader_upload_in_progress_ticker);
666 }
667 }
668 }
669
670 /**
671 * Enables or disables buttons for a file locally available
672 */
673 private void setButtonsForDown() {
674 if (!isEmpty()) {
675 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
676 downloadButton.setText(R.string.filedetails_sync_file);
677
678 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(true);
679 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
680 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
681 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
682
683 // hides the progress bar
684 ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
685 progressBar.setVisibility(View.GONE);
686 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
687 progressText.setVisibility(View.GONE);
688 }
689 }
690
691 /**
692 * Enables or disables buttons for a file not locally available
693 */
694 private void setButtonsForRemote() {
695 if (!isEmpty()) {
696 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
697 downloadButton.setText(R.string.filedetails_download);
698
699 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
700 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
701 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
702 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
703
704 // hides the progress bar
705 ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
706 progressBar.setVisibility(View.GONE);
707 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
708 progressText.setVisibility(View.GONE);
709 }
710 }
711
712
713 /**
714 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
715 * the time that the file was created. There is a chance that this will
716 * be fixed in future versions. Use this method to check if this version of
717 * ownCloud has this fix.
718 * @return True, if ownCloud the ownCloud version is supporting creation time
719 */
720 private boolean ocVersionSupportsTimeCreated(){
721 /*if(mAccount != null){
722 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
723 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
724 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
725 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
726 return true;
727 }
728 }*/
729 return false;
730 }
731
732
733 /**
734 * Once the file upload has finished -> update view
735 *
736 * Being notified about the finish of an upload is necessary for the next sequence:
737 * 1. Upload a big file.
738 * 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
739 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
740 * 3. Click the file in the list to see its details.
741 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
742 */
743 private class UploadFinishReceiver extends BroadcastReceiver {
744 @Override
745 public void onReceive(Context context, Intent intent) {
746 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
747
748 if (!isEmpty() && accountName.equals(mAccount.name)) {
749 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
750 String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
751 boolean renamedInUpload = mFile.getRemotePath().equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
752 if (mFile.getRemotePath().equals(uploadRemotePath) ||
753 renamedInUpload) {
754 if (uploadWasFine) {
755 mFile = mStorageManager.getFileByPath(uploadRemotePath);
756 }
757 if (renamedInUpload) {
758 String newName = (new File(uploadRemotePath)).getName();
759 Toast msg = Toast.makeText(getActivity().getApplicationContext(), String.format(getString(R.string.filedetails_renamed_in_upload_msg), newName), Toast.LENGTH_LONG);
760 msg.show();
761 }
762 getSherlockActivity().removeStickyBroadcast(intent); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
763 updateFileDetails(false, false); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
764 }
765 }
766 }
767 }
768
769
770 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
771 @SuppressWarnings("unused")
772 private class ShareRunnable implements Runnable {
773 private String mPath;
774
775 public ShareRunnable(String path) {
776 mPath = path;
777 }
778
779 public void run() {
780 AccountManager am = AccountManager.get(getActivity());
781 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
782 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
783 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
784
785 Log.d("share", "sharing for version " + ocv.toString());
786
787 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
788 String APPS_PATH = "/apps/files_sharing/";
789 String SHARE_PATH = "ajax/share.php";
790
791 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
792
793 final String WEBDAV_SCRIPT = "webdav.php";
794 final String WEBDAV_FILES_LOCATION = "/files/";
795
796 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
797 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
798 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
799
800 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
801 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
802
803 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
804
805 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
806 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
807 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
808 Log.d("share", mPath+"");
809 formparams.add(new BasicNameValuePair("sources",mPath));
810 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
811 formparams.add(new BasicNameValuePair("permissions", "0"));
812 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
813
814 int status;
815 try {
816 PropFindMethod find = new PropFindMethod(url+"/");
817 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
818 Log.d("sharer", ""+ url+"/");
819
820 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
821 Log.d("sharer-h", a.getName() + ":"+a.getValue());
822 }
823
824 int status2 = wc.executeMethod(find);
825
826 Log.d("sharer", "propstatus "+status2);
827
828 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
829 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
830
831 status2 = wc.executeMethod(get);
832
833 Log.d("sharer", "getstatus "+status2);
834 Log.d("sharer", "" + get.getResponseBodyAsString());
835
836 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
837 Log.d("sharer", a.getName() + ":"+a.getValue());
838 }
839
840 status = wc.executeMethod(post);
841 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
842 Log.d("sharer-h", a.getName() + ":"+a.getValue());
843 }
844 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
845 Log.d("sharer", a.getName() + ":"+a.getValue());
846 }
847 String resp = post.getResponseBodyAsString();
848 Log.d("share", ""+post.getURI().toString());
849 Log.d("share", "returned status " + status);
850 Log.d("share", " " +resp);
851
852 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
853 return;
854 }
855
856 JSONObject jsonObject = new JSONObject (resp);
857 String jsonStatus = jsonObject.getString("status");
858 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
859
860 String token = jsonObject.getString("data");
861 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
862 Log.d("Actions:shareFile ok", "url: " + uri);
863
864 } catch (Exception e) {
865 e.printStackTrace();
866 }
867
868 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
869
870 }
871 }
872 }
873
874 public void onDismiss(EditNameDialog dialog) {
875 if (dialog.getResult()) {
876 String newFilename = dialog.getNewFilename();
877 Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
878 mLastRemoteOperation = new RenameFileOperation( mFile,
879 mAccount,
880 newFilename,
881 new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
882 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
883 mLastRemoteOperation.execute(wc, this, mHandler);
884 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
885 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
886 }
887 }
888
889
890 /**
891 * {@inheritDoc}
892 */
893 @Override
894 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
895 if (operation.equals(mLastRemoteOperation)) {
896 if (operation instanceof RemoveFileOperation) {
897 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
898
899 } else if (operation instanceof RenameFileOperation) {
900 onRenameFileOperationFinish((RenameFileOperation)operation, result);
901
902 } else if (operation instanceof SynchronizeFileOperation) {
903 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
904 }
905 }
906 }
907
908
909 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
910 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
911 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
912
913 if (result.isSuccess()) {
914 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
915 msg.show();
916 if (inDisplayActivity) {
917 // double pane
918 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
919 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
920 transaction.commit();
921 mContainerActivity.onFileStateChanged();
922 } else {
923 getActivity().finish();
924 }
925
926 } else {
927 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
928 msg.show();
929 if (result.isSslRecoverableException()) {
930 // TODO show the SSL warning dialog
931 }
932 }
933 }
934
935 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
936 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
937 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
938
939 if (result.isSuccess()) {
940 updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
941 mContainerActivity.onFileStateChanged();
942
943 } else {
944 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
945 Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
946 msg.show();
947 // TODO throw again the new rename dialog
948 } else {
949 Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
950 msg.show();
951 if (result.isSslRecoverableException()) {
952 // TODO show the SSL warning dialog
953 }
954 }
955 }
956 }
957
958 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
959 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
960 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
961
962 if (!result.isSuccess()) {
963 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
964 Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
965 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, mFile);
966 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
967 startActivity(i);
968
969 } else {
970 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
971 msg.show();
972 }
973
974 if (mFile.isDown()) {
975 setButtonsForDown();
976
977 } else {
978 setButtonsForRemote();
979 }
980
981 } else {
982 if (operation.transferWasRequested()) {
983 setButtonsForTransferring();
984 mContainerActivity.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
985 // checking the service to see if the file is downloading results in FALSE
986 } else {
987 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
988 msg.show();
989 if (mFile.isDown()) {
990 setButtonsForDown();
991
992 } else {
993 setButtonsForRemote();
994 }
995 }
996 }
997 }
998
999
1000 public void listenForTransferProgress() {
1001 if (mProgressListener != null) {
1002 if (mContainerActivity.getFileDownloaderBinder() != null) {
1003 mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
1004 }
1005 if (mContainerActivity.getFileUploaderBinder() != null) {
1006 mContainerActivity.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
1007 }
1008 }
1009 }
1010
1011
1012 public void leaveTransferProgress() {
1013 if (mProgressListener != null) {
1014 if (mContainerActivity.getFileDownloaderBinder() != null) {
1015 mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
1016 }
1017 if (mContainerActivity.getFileUploaderBinder() != null) {
1018 mContainerActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
1019 }
1020 }
1021 }
1022
1023
1024
1025 /**
1026 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1027 *
1028 * @author David A. Velasco
1029 */
1030 private class ProgressListener implements OnDatatransferProgressListener {
1031 int mLastPercent = 0;
1032 WeakReference<ProgressBar> mProgressBar = null;
1033
1034 ProgressListener(ProgressBar progressBar) {
1035 mProgressBar = new WeakReference<ProgressBar>(progressBar);
1036 }
1037
1038 @Override
1039 public void onTransferProgress(long progressRate) {
1040 // old method, nothing here
1041 };
1042
1043 @Override
1044 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename) {
1045 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
1046 if (percent != mLastPercent) {
1047 ProgressBar pb = mProgressBar.get();
1048 if (pb != null) {
1049 pb.setProgress(percent);
1050 pb.postInvalidate();
1051 }
1052 }
1053 mLastPercent = percent;
1054 }
1055
1056 };
1057
1058 }