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