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