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