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.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 //activity.showLoadingDialog();
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 mStorageManager.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(file, null, mStorageManager, mAccount, true, getActivity());
496 mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
497
498 // update ui
499 ((FileDisplayActivity) getActivity()).showLoadingDialog();
500
501 }
502 }
503
504 @Override
505 public void onConfirmation(String callerTag) {
506 OCFile file = getFile();
507 if (callerTag.equals(FTAG_CONFIRMATION)) {
508 if (mStorageManager.getFileById(file.getFileId()) != null) {
509 mLastRemoteOperation = new RemoveFileOperation( file,
510 true,
511 mStorageManager);
512 mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
513
514 ((FileDisplayActivity) getActivity()).showLoadingDialog();
515 }
516 }
517 }
518
519 @Override
520 public void onNeutral(String callerTag) {
521 OCFile file = getFile();
522 mStorageManager.removeFile(file, false, true); // TODO perform in background task / new thread
523 if (file.getStoragePath() != null) {
524 file.setStoragePath(null);
525 updateFileDetails(file, mAccount);
526 }
527 }
528
529 @Override
530 public void onCancel(String callerTag) {
531 Log_OC.d(TAG, "REMOVAL CANCELED");
532 }
533
534
535 /**
536 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
537 *
538 * @return True when the fragment was created with the empty layout.
539 */
540 public boolean isEmpty() {
541 return (mLayout == R.layout.file_details_empty || getFile() == null || mAccount == null);
542 }
543
544
545 /**
546 * Use this method to signal this Activity that it shall update its view.
547 *
548 * @param file : An {@link OCFile}
549 */
550 public void updateFileDetails(OCFile file, Account ocAccount) {
551 setFile(file);
552 if (ocAccount != null && (
553 mStorageManager == null ||
554 (mAccount != null && !mAccount.equals(ocAccount))
555 )) {
556 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
557 }
558 mAccount = ocAccount;
559 updateFileDetails(false, false);
560 }
561
562 /**
563 * Updates the view with all relevant details about that file.
564 *
565 * TODO Remove parameter when the transferring state of files is kept in database.
566 *
567 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
568 *
569 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
570 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
571 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
572 *
573 * @param refresh If 'true', try to refresh the hold file from the database
574 */
575 public void updateFileDetails(boolean transferring, boolean refresh) {
576
577 if (readyToShow()) {
578
579 if (refresh && mStorageManager != null) {
580 setFile(mStorageManager.getFileByPath(getFile().getRemotePath()));
581 }
582 OCFile file = getFile();
583
584 // set file details
585 setFilename(file.getFileName());
586 setFiletype(file.getMimetype());
587 setFilesize(file.getFileLength());
588 if(ocVersionSupportsTimeCreated()){
589 setTimeCreated(file.getCreationTimestamp());
590 }
591
592 setTimeModified(file.getModificationTimestamp());
593
594 CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
595 cb.setChecked(file.keepInSync());
596
597 // configure UI for depending upon local state of the file
598 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
599 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
600 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
601 if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file))) {
602 setButtonsForTransferring();
603
604 } else if (file.isDown()) {
605
606 setButtonsForDown();
607
608 } else {
609 // TODO load default preview image; when the local file is removed, the preview remains there
610 setButtonsForRemote();
611 }
612 }
613 getView().invalidate();
614 }
615
616 /**
617 * Checks if the fragment is ready to show details of a OCFile
618 *
619 * @return 'True' when the fragment is ready to show details of a file
620 */
621 private boolean readyToShow() {
622 return (getFile() != null && mAccount != null && mLayout == R.layout.file_details_fragment);
623 }
624
625
626 /**
627 * Updates the filename in view
628 * @param filename to set
629 */
630 private void setFilename(String filename) {
631 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
632 if (tv != null)
633 tv.setText(filename);
634 }
635
636 /**
637 * Updates the MIME type in view
638 * @param mimetype to set
639 */
640 private void setFiletype(String mimetype) {
641 TextView tv = (TextView) getView().findViewById(R.id.fdType);
642 if (tv != null) {
643 String printableMimetype = DisplayUtils.convertMIMEtoPrettyPrint(mimetype);;
644 tv.setText(printableMimetype);
645 }
646 ImageView iv = (ImageView) getView().findViewById(R.id.fdIcon);
647 if (iv != null) {
648 iv.setImageResource(DisplayUtils.getResourceId(mimetype));
649 }
650 }
651
652 /**
653 * Updates the file size in view
654 * @param filesize in bytes to set
655 */
656 private void setFilesize(long filesize) {
657 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
658 if (tv != null)
659 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
660 }
661
662 /**
663 * Updates the time that the file was created in view
664 * @param milliseconds Unix time to set
665 */
666 private void setTimeCreated(long milliseconds){
667 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
668 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
669 if(tv != null){
670 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
671 tv.setVisibility(View.VISIBLE);
672 tvLabel.setVisibility(View.VISIBLE);
673 }
674 }
675
676 /**
677 * Updates the time that the file was last modified
678 * @param milliseconds Unix time to set
679 */
680 private void setTimeModified(long milliseconds){
681 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
682 if(tv != null){
683 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
684 }
685 }
686
687 /**
688 * Enables or disables buttons for a file being downloaded
689 */
690 private void setButtonsForTransferring() {
691 if (!isEmpty()) {
692 // let's protect the user from himself ;)
693 getView().findViewById(R.id.fdKeepInSync).setEnabled(false);
694
695 // show the progress bar for the transfer
696 getView().findViewById(R.id.fdProgressBlock).setVisibility(View.VISIBLE);
697 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
698 progressText.setVisibility(View.VISIBLE);
699 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
700 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
701 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, getFile())) {
702 progressText.setText(R.string.downloader_download_in_progress_ticker);
703 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, getFile())) {
704 progressText.setText(R.string.uploader_upload_in_progress_ticker);
705 }
706 }
707 }
708
709 /**
710 * Enables or disables buttons for a file locally available
711 */
712 private void setButtonsForDown() {
713 if (!isEmpty()) {
714 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
715
716 // hides the progress bar
717 getView().findViewById(R.id.fdProgressBlock).setVisibility(View.GONE);
718 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
719 progressText.setVisibility(View.GONE);
720 }
721 }
722
723 /**
724 * Enables or disables buttons for a file not locally available
725 */
726 private void setButtonsForRemote() {
727 if (!isEmpty()) {
728 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
729
730 // hides the progress bar
731 getView().findViewById(R.id.fdProgressBlock).setVisibility(View.GONE);
732 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
733 progressText.setVisibility(View.GONE);
734 }
735 }
736
737
738 /**
739 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
740 * the time that the file was created. There is a chance that this will
741 * be fixed in future versions. Use this method to check if this version of
742 * ownCloud has this fix.
743 * @return True, if ownCloud the ownCloud version is supporting creation time
744 */
745 private boolean ocVersionSupportsTimeCreated(){
746 /*if(mAccount != null){
747 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
748 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
749 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
750 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
751 return true;
752 }
753 }*/
754 return false;
755 }
756
757
758 /**
759 * Once the file upload has finished -> update view
760 *
761 * Being notified about the finish of an upload is necessary for the next sequence:
762 * 1. Upload a big file.
763 * 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
764 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
765 * 3. Click the file in the list to see its details.
766 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
767 */
768 private class UploadFinishReceiver extends BroadcastReceiver {
769 @Override
770 public void onReceive(Context context, Intent intent) {
771 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
772
773 if (!isEmpty() && accountName.equals(mAccount.name)) {
774 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
775 String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
776 boolean renamedInUpload = getFile().getRemotePath().equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
777 if (getFile().getRemotePath().equals(uploadRemotePath) ||
778 renamedInUpload) {
779 if (uploadWasFine) {
780 setFile(mStorageManager.getFileByPath(uploadRemotePath));
781 }
782 if (renamedInUpload) {
783 String newName = (new File(uploadRemotePath)).getName();
784 Toast msg = Toast.makeText(getActivity().getApplicationContext(), String.format(getString(R.string.filedetails_renamed_in_upload_msg), newName), Toast.LENGTH_LONG);
785 msg.show();
786 }
787 getSherlockActivity().removeStickyBroadcast(intent); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
788
789 updateFileDetails(false, false); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
790
791 // Force the preview if the file is an image
792 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
793 ((FileDisplayActivity) mContainerActivity).startImagePreview(getFile());
794 }
795 }
796 }
797 }
798 }
799
800
801 public void onDismiss(EditNameDialog dialog) {
802 if (dialog.getResult()) {
803 String newFilename = dialog.getNewFilename();
804 Log_OC.d(TAG, "name edit dialog dismissed with new name " + newFilename);
805 mLastRemoteOperation = new RenameFileOperation( getFile(),
806 mAccount,
807 newFilename,
808 new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
809 mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
810 ((FileDisplayActivity) getActivity()).showLoadingDialog();
811 }
812 }
813
814
815 /**
816 * {@inheritDoc}
817 */
818 @Override
819 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
820 if (operation.equals(mLastRemoteOperation)) {
821 if (operation instanceof RemoveFileOperation) {
822 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
823
824 } else if (operation instanceof RenameFileOperation) {
825 onRenameFileOperationFinish((RenameFileOperation)operation, result);
826
827 } else if (operation instanceof SynchronizeFileOperation) {
828 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
829 }
830 }
831 }
832
833
834 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
835 ((FileDisplayActivity) getActivity()).dismissLoadingDialog();
836 if (result.isSuccess()) {
837 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
838 msg.show();
839 ((FileDisplayActivity)getActivity()).cleanSecondFragment();
840
841 } else {
842 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
843 msg.show();
844 if (result.isSslRecoverableException()) {
845 // TODO show the SSL warning dialog
846 }
847 }
848 }
849
850 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
851 ((FileDisplayActivity) getActivity()).dismissLoadingDialog();
852
853 if (result.isSuccess()) {
854 updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
855 mContainerActivity.onFileStateChanged();
856
857 } else {
858 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
859 Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
860 msg.show();
861 // TODO throw again the new rename dialog
862 } if (result.getCode().equals(ResultCode.INVALID_CHARACTER_IN_NAME)) {
863 Toast msg = Toast.makeText(getActivity(), R.string.filename_forbidden_characters, Toast.LENGTH_LONG);
864 msg.show();
865 } else {
866 Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
867 msg.show();
868 if (result.isSslRecoverableException()) {
869 // TODO show the SSL warning dialog
870 }
871 }
872 }
873 }
874
875 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
876 ((FileDisplayActivity) getActivity()).dismissLoadingDialog();
877 OCFile file = getFile();
878 if (!result.isSuccess()) {
879 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
880 Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
881 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, file);
882 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
883 startActivity(i);
884
885 }
886
887 if (file.isDown()) {
888 setButtonsForDown();
889
890 } else {
891 setButtonsForRemote();
892 }
893
894 } else {
895 if (operation.transferWasRequested()) {
896 setButtonsForTransferring();
897 mContainerActivity.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
898 // checking the service to see if the file is downloading results in FALSE
899 } else {
900 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
901 msg.show();
902 if (file.isDown()) {
903 setButtonsForDown();
904
905 } else {
906 setButtonsForRemote();
907 }
908 }
909 }
910 }
911
912
913 public void listenForTransferProgress() {
914 if (mProgressListener != null) {
915 if (mContainerActivity.getFileDownloaderBinder() != null) {
916 mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, getFile());
917 }
918 if (mContainerActivity.getFileUploaderBinder() != null) {
919 mContainerActivity.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, getFile());
920 }
921 }
922 }
923
924
925 public void leaveTransferProgress() {
926 if (mProgressListener != null) {
927 if (mContainerActivity.getFileDownloaderBinder() != null) {
928 mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, getFile());
929 }
930 if (mContainerActivity.getFileUploaderBinder() != null) {
931 mContainerActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, getFile());
932 }
933 }
934 }
935
936
937
938 /**
939 * Helper class responsible for updating the progress bar shown for file uploading or downloading
940 *
941 * @author David A. Velasco
942 */
943 private class ProgressListener implements OnDatatransferProgressListener {
944 int mLastPercent = 0;
945 WeakReference<ProgressBar> mProgressBar = null;
946
947 ProgressListener(ProgressBar progressBar) {
948 mProgressBar = new WeakReference<ProgressBar>(progressBar);
949 }
950
951 @Override
952 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename) {
953 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
954 if (percent != mLastPercent) {
955 ProgressBar pb = mProgressBar.get();
956 if (pb != null) {
957 pb.setProgress(percent);
958 pb.postInvalidate();
959 }
960 }
961 mLastPercent = percent;
962 }
963
964 };
965
966 }