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