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