d08aace852965c2b2a7463f0e0fc487e79bf0145
[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 String fileName = mFile.getFileName();
368 int extensionStart = mFile.isDirectory() ? -1 : fileName.lastIndexOf(".");
369 int selectionEnd = (extensionStart >= 0) ? extensionStart : fileName.length();
370 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), fileName, 0, selectionEnd, this);
371 dialog.show(getFragmentManager(), "nameeditdialog");
372 break;
373 }
374 case R.id.fdRemoveBtn: {
375 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
376 R.string.confirmation_remove_alert,
377 new String[]{mFile.getFileName()},
378 mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
379 mFile.isDown() ? R.string.confirmation_remove_local : -1,
380 R.string.common_cancel);
381 confDialog.setOnConfirmationListener(this);
382 confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
383 break;
384 }
385 case R.id.fdOpenBtn: {
386 openFile();
387 break;
388 }
389 default:
390 Log_OC.e(TAG, "Incorrect view clicked!");
391 }
392
393 /* else if (v.getId() == R.id.fdShareBtn) {
394 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
395 t.start();
396 }*/
397 }
398
399
400 /**
401 * Opens mFile.
402 */
403 private void openFile() {
404
405 String storagePath = mFile.getStoragePath();
406 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
407 try {
408 Intent i = new Intent(Intent.ACTION_VIEW);
409 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
410 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
411 startActivity(i);
412
413 } catch (Throwable t) {
414 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
415 boolean toastIt = true;
416 String mimeType = "";
417 try {
418 Intent i = new Intent(Intent.ACTION_VIEW);
419 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
420 if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
421 if (mimeType != null) {
422 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
423 } else {
424 // desperate try
425 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*/*");
426 }
427 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
428 startActivity(i);
429 toastIt = false;
430 }
431
432 } catch (IndexOutOfBoundsException e) {
433 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
434
435 } catch (ActivityNotFoundException e) {
436 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
437
438 } catch (Throwable th) {
439 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
440
441 } finally {
442 if (toastIt) {
443 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
444 }
445 }
446
447 }
448 }
449
450
451 @Override
452 public void onConfirmation(String callerTag) {
453 if (callerTag.equals(FTAG_CONFIRMATION)) {
454 if (mStorageManager.getFileById(mFile.getFileId()) != null) {
455 mLastRemoteOperation = new RemoveFileOperation( mFile,
456 true,
457 mStorageManager);
458 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
459 mLastRemoteOperation.execute(wc, this, mHandler);
460
461 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
462 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
463 }
464 }
465 }
466
467 @Override
468 public void onNeutral(String callerTag) {
469 File f = null;
470 if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {
471 f.delete();
472 mFile.setStoragePath(null);
473 mStorageManager.saveFile(mFile);
474 updateFileDetails(mFile, mAccount);
475 }
476 }
477
478 @Override
479 public void onCancel(String callerTag) {
480 Log.d(TAG, "REMOVAL CANCELED");
481 }
482
483
484 /**
485 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
486 *
487 * @return True when the fragment was created with the empty layout.
488 */
489 public boolean isEmpty() {
490 return (mLayout == R.layout.file_details_empty || mFile == null || mAccount == null);
491 }
492
493
494 /**
495 * {@inheritDoc}
496 */
497 public OCFile getFile(){
498 return mFile;
499 }
500
501 /**
502 * Use this method to signal this Activity that it shall update its view.
503 *
504 * @param file : An {@link OCFile}
505 */
506 public void updateFileDetails(OCFile file, Account ocAccount) {
507 mFile = file;
508 if (ocAccount != null && (
509 mStorageManager == null ||
510 (mAccount != null && !mAccount.equals(ocAccount))
511 )) {
512 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
513 }
514 mAccount = ocAccount;
515 updateFileDetails(false, false);
516 }
517
518 /**
519 * Updates the view with all relevant details about that file.
520 *
521 * TODO Remove parameter when the transferring state of files is kept in database.
522 *
523 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
524 *
525 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
526 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
527 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
528 *
529 * @param refresh If 'true', try to refresh the hold file from the database
530 */
531 public void updateFileDetails(boolean transferring, boolean refresh) {
532
533 if (readyToShow()) {
534
535 if (refresh && mStorageManager != null) {
536 mFile = mStorageManager.getFileByPath(mFile.getRemotePath());
537 }
538
539 // set file details
540 setFilename(mFile.getFileName());
541 setFiletype(mFile.getMimetype());
542 setFilesize(mFile.getFileLength());
543 if(ocVersionSupportsTimeCreated()){
544 setTimeCreated(mFile.getCreationTimestamp());
545 }
546
547 setTimeModified(mFile.getModificationTimestamp());
548
549 CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
550 cb.setChecked(mFile.keepInSync());
551
552 // configure UI for depending upon local state of the file
553 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
554 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
555 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
556 if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile))) {
557 setButtonsForTransferring();
558
559 } else if (mFile.isDown()) {
560
561 setButtonsForDown();
562
563 } else {
564 // TODO load default preview image; when the local file is removed, the preview remains there
565 setButtonsForRemote();
566 }
567 }
568 getView().invalidate();
569 }
570
571
572 /**
573 * Checks if the fragment is ready to show details of a OCFile
574 *
575 * @return 'True' when the fragment is ready to show details of a file
576 */
577 private boolean readyToShow() {
578 return (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment);
579 }
580
581
582 /**
583 * Updates the filename in view
584 * @param filename to set
585 */
586 private void setFilename(String filename) {
587 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
588 if (tv != null)
589 tv.setText(filename);
590 }
591
592 /**
593 * Updates the MIME type in view
594 * @param mimetype to set
595 */
596 private void setFiletype(String mimetype) {
597 TextView tv = (TextView) getView().findViewById(R.id.fdType);
598 if (tv != null) {
599 String printableMimetype = DisplayUtils.convertMIMEtoPrettyPrint(mimetype);;
600 tv.setText(printableMimetype);
601 }
602 ImageView iv = (ImageView) getView().findViewById(R.id.fdIcon);
603 if (iv != null) {
604 iv.setImageResource(DisplayUtils.getResourceId(mimetype));
605 }
606 }
607
608 /**
609 * Updates the file size in view
610 * @param filesize in bytes to set
611 */
612 private void setFilesize(long filesize) {
613 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
614 if (tv != null)
615 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
616 }
617
618 /**
619 * Updates the time that the file was created in view
620 * @param milliseconds Unix time to set
621 */
622 private void setTimeCreated(long milliseconds){
623 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
624 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
625 if(tv != null){
626 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
627 tv.setVisibility(View.VISIBLE);
628 tvLabel.setVisibility(View.VISIBLE);
629 }
630 }
631
632 /**
633 * Updates the time that the file was last modified
634 * @param milliseconds Unix time to set
635 */
636 private void setTimeModified(long milliseconds){
637 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
638 if(tv != null){
639 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
640 }
641 }
642
643 /**
644 * Enables or disables buttons for a file being downloaded
645 */
646 private void setButtonsForTransferring() {
647 if (!isEmpty()) {
648 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
649 downloadButton.setText(R.string.common_cancel);
650 //downloadButton.setEnabled(false);
651
652 // let's protect the user from himself ;)
653 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
654 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(false);
655 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(false);
656 getView().findViewById(R.id.fdKeepInSync).setEnabled(false);
657
658 // show the progress bar for the transfer
659 ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
660 progressBar.setVisibility(View.VISIBLE);
661 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
662 progressText.setVisibility(View.VISIBLE);
663 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
664 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
665 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
666 progressText.setText(R.string.downloader_download_in_progress_ticker);
667 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
668 progressText.setText(R.string.uploader_upload_in_progress_ticker);
669 }
670 }
671 }
672
673 /**
674 * Enables or disables buttons for a file locally available
675 */
676 private void setButtonsForDown() {
677 if (!isEmpty()) {
678 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
679 downloadButton.setText(R.string.filedetails_sync_file);
680
681 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(true);
682 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
683 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
684 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
685
686 // hides the progress bar
687 ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
688 progressBar.setVisibility(View.GONE);
689 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
690 progressText.setVisibility(View.GONE);
691 }
692 }
693
694 /**
695 * Enables or disables buttons for a file not locally available
696 */
697 private void setButtonsForRemote() {
698 if (!isEmpty()) {
699 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
700 downloadButton.setText(R.string.filedetails_download);
701
702 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
703 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
704 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
705 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
706
707 // hides the progress bar
708 ProgressBar progressBar = (ProgressBar)getView().findViewById(R.id.fdProgressBar);
709 progressBar.setVisibility(View.GONE);
710 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
711 progressText.setVisibility(View.GONE);
712 }
713 }
714
715
716 /**
717 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
718 * the time that the file was created. There is a chance that this will
719 * be fixed in future versions. Use this method to check if this version of
720 * ownCloud has this fix.
721 * @return True, if ownCloud the ownCloud version is supporting creation time
722 */
723 private boolean ocVersionSupportsTimeCreated(){
724 /*if(mAccount != null){
725 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
726 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
727 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
728 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
729 return true;
730 }
731 }*/
732 return false;
733 }
734
735
736 /**
737 * Once the file upload has finished -> update view
738 *
739 * Being notified about the finish of an upload is necessary for the next sequence:
740 * 1. Upload a big file.
741 * 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
742 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
743 * 3. Click the file in the list to see its details.
744 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
745 */
746 private class UploadFinishReceiver extends BroadcastReceiver {
747 @Override
748 public void onReceive(Context context, Intent intent) {
749 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
750
751 if (!isEmpty() && accountName.equals(mAccount.name)) {
752 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
753 String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
754 boolean renamedInUpload = mFile.getRemotePath().equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
755 if (mFile.getRemotePath().equals(uploadRemotePath) ||
756 renamedInUpload) {
757 if (uploadWasFine) {
758 mFile = mStorageManager.getFileByPath(uploadRemotePath);
759 }
760 if (renamedInUpload) {
761 String newName = (new File(uploadRemotePath)).getName();
762 Toast msg = Toast.makeText(getActivity().getApplicationContext(), String.format(getString(R.string.filedetails_renamed_in_upload_msg), newName), Toast.LENGTH_LONG);
763 msg.show();
764 }
765 getSherlockActivity().removeStickyBroadcast(intent); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
766 updateFileDetails(false, false); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
767 }
768 }
769 }
770 }
771
772
773 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
774 @SuppressWarnings("unused")
775 private class ShareRunnable implements Runnable {
776 private String mPath;
777
778 public ShareRunnable(String path) {
779 mPath = path;
780 }
781
782 public void run() {
783 AccountManager am = AccountManager.get(getActivity());
784 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
785 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
786 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
787
788 Log.d("share", "sharing for version " + ocv.toString());
789
790 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
791 String APPS_PATH = "/apps/files_sharing/";
792 String SHARE_PATH = "ajax/share.php";
793
794 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
795
796 final String WEBDAV_SCRIPT = "webdav.php";
797 final String WEBDAV_FILES_LOCATION = "/files/";
798
799 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
800 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
801 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
802
803 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
804 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
805
806 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
807
808 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
809 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
810 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
811 Log.d("share", mPath+"");
812 formparams.add(new BasicNameValuePair("sources",mPath));
813 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
814 formparams.add(new BasicNameValuePair("permissions", "0"));
815 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
816
817 int status;
818 try {
819 PropFindMethod find = new PropFindMethod(url+"/");
820 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
821 Log.d("sharer", ""+ url+"/");
822
823 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
824 Log.d("sharer-h", a.getName() + ":"+a.getValue());
825 }
826
827 int status2 = wc.executeMethod(find);
828
829 Log.d("sharer", "propstatus "+status2);
830
831 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
832 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
833
834 status2 = wc.executeMethod(get);
835
836 Log.d("sharer", "getstatus "+status2);
837 Log.d("sharer", "" + get.getResponseBodyAsString());
838
839 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
840 Log.d("sharer", a.getName() + ":"+a.getValue());
841 }
842
843 status = wc.executeMethod(post);
844 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
845 Log.d("sharer-h", a.getName() + ":"+a.getValue());
846 }
847 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
848 Log.d("sharer", a.getName() + ":"+a.getValue());
849 }
850 String resp = post.getResponseBodyAsString();
851 Log.d("share", ""+post.getURI().toString());
852 Log.d("share", "returned status " + status);
853 Log.d("share", " " +resp);
854
855 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
856 return;
857 }
858
859 JSONObject jsonObject = new JSONObject (resp);
860 String jsonStatus = jsonObject.getString("status");
861 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
862
863 String token = jsonObject.getString("data");
864 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
865 Log.d("Actions:shareFile ok", "url: " + uri);
866
867 } catch (Exception e) {
868 e.printStackTrace();
869 }
870
871 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
872
873 }
874 }
875 }
876
877 public void onDismiss(EditNameDialog dialog) {
878 if (dialog.getResult()) {
879 String newFilename = dialog.getNewFilename();
880 Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
881 mLastRemoteOperation = new RenameFileOperation( mFile,
882 mAccount,
883 newFilename,
884 new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
885 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
886 mLastRemoteOperation.execute(wc, this, mHandler);
887 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
888 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
889 }
890 }
891
892
893 /**
894 * {@inheritDoc}
895 */
896 @Override
897 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
898 if (operation.equals(mLastRemoteOperation)) {
899 if (operation instanceof RemoveFileOperation) {
900 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
901
902 } else if (operation instanceof RenameFileOperation) {
903 onRenameFileOperationFinish((RenameFileOperation)operation, result);
904
905 } else if (operation instanceof SynchronizeFileOperation) {
906 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
907 }
908 }
909 }
910
911
912 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
913 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
914 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
915
916 if (result.isSuccess()) {
917 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
918 msg.show();
919 if (inDisplayActivity) {
920 // double pane
921 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
922 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
923 transaction.commit();
924 mContainerActivity.onFileStateChanged();
925 } else {
926 getActivity().finish();
927 }
928
929 } else {
930 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
931 msg.show();
932 if (result.isSslRecoverableException()) {
933 // TODO show the SSL warning dialog
934 }
935 }
936 }
937
938 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
939 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
940 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
941
942 if (result.isSuccess()) {
943 updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
944 mContainerActivity.onFileStateChanged();
945
946 } else {
947 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
948 Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
949 msg.show();
950 // TODO throw again the new rename dialog
951 } else {
952 Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
953 msg.show();
954 if (result.isSslRecoverableException()) {
955 // TODO show the SSL warning dialog
956 }
957 }
958 }
959 }
960
961 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
962 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
963 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
964
965 if (!result.isSuccess()) {
966 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
967 Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
968 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, mFile);
969 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
970 startActivity(i);
971
972 } else {
973 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
974 msg.show();
975 }
976
977 if (mFile.isDown()) {
978 setButtonsForDown();
979
980 } else {
981 setButtonsForRemote();
982 }
983
984 } else {
985 if (operation.transferWasRequested()) {
986 setButtonsForTransferring();
987 mContainerActivity.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
988 // checking the service to see if the file is downloading results in FALSE
989 } else {
990 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
991 msg.show();
992 if (mFile.isDown()) {
993 setButtonsForDown();
994
995 } else {
996 setButtonsForRemote();
997 }
998 }
999 }
1000 }
1001
1002
1003 public void listenForTransferProgress() {
1004 if (mProgressListener != null) {
1005 if (mContainerActivity.getFileDownloaderBinder() != null) {
1006 mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
1007 }
1008 if (mContainerActivity.getFileUploaderBinder() != null) {
1009 mContainerActivity.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
1010 }
1011 }
1012 }
1013
1014
1015 public void leaveTransferProgress() {
1016 if (mProgressListener != null) {
1017 if (mContainerActivity.getFileDownloaderBinder() != null) {
1018 mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
1019 }
1020 if (mContainerActivity.getFileUploaderBinder() != null) {
1021 mContainerActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
1022 }
1023 }
1024 }
1025
1026
1027
1028 /**
1029 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1030 *
1031 * @author David A. Velasco
1032 */
1033 private class ProgressListener implements OnDatatransferProgressListener {
1034 int mLastPercent = 0;
1035 WeakReference<ProgressBar> mProgressBar = null;
1036
1037 ProgressListener(ProgressBar progressBar) {
1038 mProgressBar = new WeakReference<ProgressBar>(progressBar);
1039 }
1040
1041 @Override
1042 public void onTransferProgress(long progressRate) {
1043 // old method, nothing here
1044 };
1045
1046 @Override
1047 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename) {
1048 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
1049 if (percent != mLastPercent) {
1050 ProgressBar pb = mProgressBar.get();
1051 if (pb != null) {
1052 pb.setProgress(percent);
1053 pb.postInvalidate();
1054 }
1055 }
1056 mLastPercent = percent;
1057 }
1058
1059 };
1060
1061 }