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