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