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