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