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