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