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