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