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