Code refactored to 'open file' in a single point
[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.support.v4.app.FragmentTransaction;
34 import android.view.LayoutInflater;
35 import android.view.View;
36 import android.view.View.OnClickListener;
37 import android.view.ViewGroup;
38 import android.widget.CheckBox;
39 import android.widget.ImageView;
40 import android.widget.ProgressBar;
41 import android.widget.TextView;
42 import android.widget.Toast;
43
44 import com.actionbarsherlock.app.SherlockFragment;
45 import com.actionbarsherlock.view.Menu;
46 import com.actionbarsherlock.view.MenuInflater;
47 import com.actionbarsherlock.view.MenuItem;
48 import com.owncloud.android.DisplayUtils;
49 import com.owncloud.android.Log_OC;
50 import com.owncloud.android.datamodel.FileDataStorageManager;
51 import com.owncloud.android.datamodel.OCFile;
52 import com.owncloud.android.files.services.FileObserverService;
53 import com.owncloud.android.files.services.FileUploader;
54 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
55 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
56 import com.owncloud.android.operations.OnRemoteOperationListener;
57 import com.owncloud.android.operations.RemoteOperation;
58 import com.owncloud.android.operations.RemoteOperationResult;
59 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
60 import com.owncloud.android.operations.RemoveFileOperation;
61 import com.owncloud.android.operations.RenameFileOperation;
62 import com.owncloud.android.operations.SynchronizeFileOperation;
63 import com.owncloud.android.ui.activity.ConflictsResolveActivity;
64 import com.owncloud.android.ui.activity.FileActivity;
65 import com.owncloud.android.ui.activity.FileDetailActivity;
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
70 import com.owncloud.android.R;
71
72 import eu.alefzero.webdav.OnDatatransferProgressListener;
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 SherlockFragment implements
81 OnClickListener,
82 ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener, EditNameDialogListener,
83 FileFragment {
84
85 private FileFragment.ContainerActivity mContainerActivity;
86
87 private int mLayout;
88 private View mView;
89 private OCFile mFile;
90 private Account mAccount;
91 private FileDataStorageManager mStorageManager;
92
93 private UploadFinishReceiver mUploadFinishReceiver;
94 public ProgressListener mProgressListener;
95
96 private Handler mHandler;
97 private RemoteOperation mLastRemoteOperation;
98
99 private static final String TAG = FileDetailFragment.class.getSimpleName();
100 public static final String FTAG = "FileDetails";
101 public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
102
103
104 /**
105 * Creates an empty details fragment.
106 *
107 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
108 */
109 public FileDetailFragment() {
110 mFile = null;
111 mAccount = null;
112 mStorageManager = null;
113 mLayout = R.layout.file_details_empty;
114 mProgressListener = null;
115 }
116
117 /**
118 * Creates a details fragment.
119 *
120 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
121 *
122 * @param fileToDetail An {@link OCFile} to show in the fragment
123 * @param ocAccount An ownCloud account; needed to start downloads
124 */
125 public FileDetailFragment(OCFile fileToDetail, Account ocAccount) {
126 mFile = fileToDetail;
127 mAccount = ocAccount;
128 mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
129 mLayout = R.layout.file_details_empty;
130 mProgressListener = null;
131 }
132
133
134 @Override
135 public void onCreate(Bundle savedInstanceState) {
136 super.onCreate(savedInstanceState);
137 mHandler = new Handler();
138 setHasOptionsMenu(true);
139 }
140
141
142 @Override
143 public View onCreateView(LayoutInflater inflater, ViewGroup container,
144 Bundle savedInstanceState) {
145 super.onCreateView(inflater, container, savedInstanceState);
146
147 if (savedInstanceState != null) {
148 mFile = savedInstanceState.getParcelable(FileActivity.EXTRA_FILE);
149 mAccount = savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT);
150 }
151
152 if(mFile != null && mAccount != null) {
153 mLayout = R.layout.file_details_fragment;
154 }
155
156 View view = null;
157 view = inflater.inflate(mLayout, container, false);
158 mView = view;
159
160 if (mLayout == R.layout.file_details_fragment) {
161 mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
162 ProgressBar progressBar = (ProgressBar)mView.findViewById(R.id.fdProgressBar);
163 mProgressListener = new ProgressListener(progressBar);
164 mView.findViewById(R.id.fdCancelBtn).setOnClickListener(this);
165 }
166
167 updateFileDetails(false, false);
168 return view;
169 }
170
171 /**
172 * {@inheritDoc}
173 */
174 @Override
175 public void onAttach(Activity activity) {
176 super.onAttach(activity);
177 try {
178 mContainerActivity = (ContainerActivity) activity;
179
180 } catch (ClassCastException e) {
181 throw new ClassCastException(activity.toString() + " must implement " + FileDetailFragment.ContainerActivity.class.getSimpleName());
182 }
183 }
184
185
186 /**
187 * {@inheritDoc}
188 */
189 @Override
190 public void onActivityCreated(Bundle savedInstanceState) {
191 super.onActivityCreated(savedInstanceState);
192 if (mAccount != null) {
193 mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
194 }
195 }
196
197
198 @Override
199 public void onSaveInstanceState(Bundle outState) {
200 super.onSaveInstanceState(outState);
201 outState.putParcelable(FileActivity.EXTRA_FILE, mFile);
202 outState.putParcelable(FileActivity.EXTRA_ACCOUNT, mAccount);
203 }
204
205 @Override
206 public void onStart() {
207 super.onStart();
208 listenForTransferProgress();
209 }
210
211 @Override
212 public void onResume() {
213 super.onResume();
214 mUploadFinishReceiver = new UploadFinishReceiver();
215 IntentFilter filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
216 getActivity().registerReceiver(mUploadFinishReceiver, filter);
217
218 }
219
220
221 @Override
222 public void onPause() {
223 super.onPause();
224 if (mUploadFinishReceiver != null) {
225 getActivity().unregisterReceiver(mUploadFinishReceiver);
226 mUploadFinishReceiver = null;
227 }
228 }
229
230
231 @Override
232 public void onStop() {
233 super.onStop();
234 leaveTransferProgress();
235 }
236
237
238 @Override
239 public View getView() {
240 return super.getView() == null ? mView : super.getView();
241 }
242
243
244 /**
245 * {@inheritDoc}
246 */
247 @Override
248 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
249 super.onCreateOptionsMenu(menu, inflater);
250 inflater.inflate(R.menu.file_actions_menu, menu);
251 MenuItem item = menu.findItem(R.id.action_see_details);
252 if (item != null) {
253 item.setVisible(false);
254 item.setEnabled(false);
255 }
256 }
257
258
259 /**
260 * {@inheritDoc}
261 */
262 @Override
263 public void onPrepareOptionsMenu (Menu menu) {
264 super.onPrepareOptionsMenu(menu);
265
266 List<Integer> toHide = new ArrayList<Integer>();
267 List<Integer> toShow = new ArrayList<Integer>();
268
269 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
270 boolean downloading = downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile);
271 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
272 boolean uploading = uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile);
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 (mFile != null && mFile.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 (mFile != 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 MenuItem item = null;
319 for (int i : toHide) {
320 item = menu.findItem(i);
321 if (item != null) {
322 item.setVisible(false);
323 item.setEnabled(false);
324 }
325 }
326 for (int i : toShow) {
327 item = menu.findItem(i);
328 if (item != null) {
329 item.setVisible(true);
330 item.setEnabled(true);
331 }
332 }
333 }
334
335
336 /**
337 * {@inheritDoc}
338 */
339 @Override
340 public boolean onOptionsItemSelected(MenuItem item) {
341 switch (item.getItemId()) {
342 case R.id.action_open_file_with: {
343 mContainerActivity.openFile(mFile);
344 return true;
345 }
346 case R.id.action_remove_file: {
347 removeFile();
348 return true;
349 }
350 case R.id.action_rename_file: {
351 renameFile();
352 return true;
353 }
354 case R.id.action_download_file:
355 case R.id.action_cancel_download:
356 case R.id.action_cancel_upload:
357 case R.id.action_sync_file: {
358 synchronizeFile();
359 return true;
360 }
361 default:
362 return false;
363 }
364 }
365
366 @Override
367 public void onClick(View v) {
368 switch (v.getId()) {
369 case R.id.fdKeepInSync: {
370 toggleKeepInSync();
371 break;
372 }
373 case R.id.fdCancelBtn: {
374 synchronizeFile();
375 break;
376 }
377 default:
378 Log_OC.e(TAG, "Incorrect view clicked!");
379 }
380 }
381
382
383 private void toggleKeepInSync() {
384 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
385 mFile.setKeepInSync(cb.isChecked());
386 mStorageManager.saveFile(mFile);
387
388 /// register the OCFile instance in the observer service to monitor local updates;
389 /// if necessary, the file is download
390 Intent intent = new Intent(getActivity().getApplicationContext(),
391 FileObserverService.class);
392 intent.putExtra(FileObserverService.KEY_FILE_CMD,
393 (cb.isChecked()?
394 FileObserverService.CMD_ADD_OBSERVED_FILE:
395 FileObserverService.CMD_DEL_OBSERVED_FILE));
396 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
397 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
398 getActivity().startService(intent);
399
400 if (mFile.keepInSync()) {
401 synchronizeFile(); // force an immediate synchronization
402 }
403 }
404
405
406 private void removeFile() {
407 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
408 R.string.confirmation_remove_alert,
409 new String[]{mFile.getFileName()},
410 mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
411 mFile.isDown() ? R.string.confirmation_remove_local : -1,
412 R.string.common_cancel);
413 confDialog.setOnConfirmationListener(this);
414 confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
415 }
416
417
418 private void renameFile() {
419 String fileName = mFile.getFileName();
420 int extensionStart = mFile.isDirectory() ? -1 : fileName.lastIndexOf(".");
421 int selectionEnd = (extensionStart >= 0) ? extensionStart : fileName.length();
422 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), fileName, 0, selectionEnd, this);
423 dialog.show(getFragmentManager(), "nameeditdialog");
424 }
425
426 private void synchronizeFile() {
427 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
428 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
429 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
430 downloaderBinder.cancel(mAccount, mFile);
431 if (mFile.isDown()) {
432 setButtonsForDown();
433 } else {
434 setButtonsForRemote();
435 }
436
437 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
438 uploaderBinder.cancel(mAccount, mFile);
439 if (!mFile.fileExists()) {
440 // TODO make something better
441 if (getActivity() instanceof FileDisplayActivity) {
442 // double pane
443 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
444 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FTAG); // empty FileDetailFragment
445 transaction.commit();
446 mContainerActivity.onFileStateChanged();
447 } else {
448 getActivity().finish();
449 }
450
451 } else if (mFile.isDown()) {
452 setButtonsForDown();
453 } else {
454 setButtonsForRemote();
455 }
456
457 } else {
458 mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());
459 mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
460
461 // update ui
462 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
463 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
464
465 }
466 }
467
468 @Override
469 public void onConfirmation(String callerTag) {
470 if (callerTag.equals(FTAG_CONFIRMATION)) {
471 if (mStorageManager.getFileById(mFile.getFileId()) != null) {
472 mLastRemoteOperation = new RemoveFileOperation( mFile,
473 true,
474 mStorageManager);
475 mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
476
477 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
478 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
479 }
480 }
481 }
482
483 @Override
484 public void onNeutral(String callerTag) {
485 File f = null;
486 if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {
487 f.delete();
488 mFile.setStoragePath(null);
489 mStorageManager.saveFile(mFile);
490 updateFileDetails(mFile, 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 || mFile == null || mAccount == null);
507 }
508
509
510 /**
511 * {@inheritDoc}
512 */
513 public OCFile getFile(){
514 return mFile;
515 }
516
517 /**
518 * Use this method to signal this Activity that it shall update its view.
519 *
520 * @param file : An {@link OCFile}
521 */
522 public void updateFileDetails(OCFile file, Account ocAccount) {
523 mFile = file;
524 if (ocAccount != null && (
525 mStorageManager == null ||
526 (mAccount != null && !mAccount.equals(ocAccount))
527 )) {
528 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
529 }
530 mAccount = ocAccount;
531 updateFileDetails(false, false);
532 }
533
534 /**
535 * Updates the view with all relevant details about that file.
536 *
537 * TODO Remove parameter when the transferring state of files is kept in database.
538 *
539 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
540 *
541 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
542 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
543 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
544 *
545 * @param refresh If 'true', try to refresh the hold file from the database
546 */
547 public void updateFileDetails(boolean transferring, boolean refresh) {
548
549 if (readyToShow()) {
550
551 if (refresh && mStorageManager != null) {
552 mFile = mStorageManager.getFileByPath(mFile.getRemotePath());
553 }
554
555 // set file details
556 setFilename(mFile.getFileName());
557 setFiletype(mFile.getMimetype());
558 setFilesize(mFile.getFileLength());
559 if(ocVersionSupportsTimeCreated()){
560 setTimeCreated(mFile.getCreationTimestamp());
561 }
562
563 setTimeModified(mFile.getModificationTimestamp());
564
565 CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
566 cb.setChecked(mFile.keepInSync());
567
568 // configure UI for depending upon local state of the file
569 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
570 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
571 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
572 if (transferring || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile))) {
573 setButtonsForTransferring();
574
575 } else if (mFile.isDown()) {
576
577 setButtonsForDown();
578
579 } else {
580 // TODO load default preview image; when the local file is removed, the preview remains there
581 setButtonsForRemote();
582 }
583 }
584 getView().invalidate();
585 }
586
587 /**
588 * Checks if the fragment is ready to show details of a OCFile
589 *
590 * @return 'True' when the fragment is ready to show details of a file
591 */
592 private boolean readyToShow() {
593 return (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment);
594 }
595
596
597 /**
598 * Updates the filename in view
599 * @param filename to set
600 */
601 private void setFilename(String filename) {
602 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
603 if (tv != null)
604 tv.setText(filename);
605 }
606
607 /**
608 * Updates the MIME type in view
609 * @param mimetype to set
610 */
611 private void setFiletype(String mimetype) {
612 TextView tv = (TextView) getView().findViewById(R.id.fdType);
613 if (tv != null) {
614 String printableMimetype = DisplayUtils.convertMIMEtoPrettyPrint(mimetype);;
615 tv.setText(printableMimetype);
616 }
617 ImageView iv = (ImageView) getView().findViewById(R.id.fdIcon);
618 if (iv != null) {
619 iv.setImageResource(DisplayUtils.getResourceId(mimetype));
620 }
621 }
622
623 /**
624 * Updates the file size in view
625 * @param filesize in bytes to set
626 */
627 private void setFilesize(long filesize) {
628 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
629 if (tv != null)
630 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
631 }
632
633 /**
634 * Updates the time that the file was created in view
635 * @param milliseconds Unix time to set
636 */
637 private void setTimeCreated(long milliseconds){
638 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
639 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
640 if(tv != null){
641 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
642 tv.setVisibility(View.VISIBLE);
643 tvLabel.setVisibility(View.VISIBLE);
644 }
645 }
646
647 /**
648 * Updates the time that the file was last modified
649 * @param milliseconds Unix time to set
650 */
651 private void setTimeModified(long milliseconds){
652 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
653 if(tv != null){
654 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
655 }
656 }
657
658 /**
659 * Enables or disables buttons for a file being downloaded
660 */
661 private void setButtonsForTransferring() {
662 if (!isEmpty()) {
663 // let's protect the user from himself ;)
664 getView().findViewById(R.id.fdKeepInSync).setEnabled(false);
665
666 // show the progress bar for the transfer
667 getView().findViewById(R.id.fdProgressBlock).setVisibility(View.VISIBLE);
668 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
669 progressText.setVisibility(View.VISIBLE);
670 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
671 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
672 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
673 progressText.setText(R.string.downloader_download_in_progress_ticker);
674 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
675 progressText.setText(R.string.uploader_upload_in_progress_ticker);
676 }
677 }
678 }
679
680 /**
681 * Enables or disables buttons for a file locally available
682 */
683 private void setButtonsForDown() {
684 if (!isEmpty()) {
685 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
686
687 // hides the progress bar
688 getView().findViewById(R.id.fdProgressBlock).setVisibility(View.GONE);
689 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
690 progressText.setVisibility(View.GONE);
691 }
692 }
693
694 /**
695 * Enables or disables buttons for a file not locally available
696 */
697 private void setButtonsForRemote() {
698 if (!isEmpty()) {
699 getView().findViewById(R.id.fdKeepInSync).setEnabled(true);
700
701 // hides the progress bar
702 getView().findViewById(R.id.fdProgressBlock).setVisibility(View.GONE);
703 TextView progressText = (TextView)getView().findViewById(R.id.fdProgressText);
704 progressText.setVisibility(View.GONE);
705 }
706 }
707
708
709 /**
710 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
711 * the time that the file was created. There is a chance that this will
712 * be fixed in future versions. Use this method to check if this version of
713 * ownCloud has this fix.
714 * @return True, if ownCloud the ownCloud version is supporting creation time
715 */
716 private boolean ocVersionSupportsTimeCreated(){
717 /*if(mAccount != null){
718 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
719 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
720 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
721 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
722 return true;
723 }
724 }*/
725 return false;
726 }
727
728
729 /**
730 * Once the file upload has finished -> update view
731 *
732 * Being notified about the finish of an upload is necessary for the next sequence:
733 * 1. Upload a big file.
734 * 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
735 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
736 * 3. Click the file in the list to see its details.
737 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
738 */
739 private class UploadFinishReceiver extends BroadcastReceiver {
740 @Override
741 public void onReceive(Context context, Intent intent) {
742 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
743
744 if (!isEmpty() && accountName.equals(mAccount.name)) {
745 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
746 String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
747 boolean renamedInUpload = mFile.getRemotePath().equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
748 if (mFile.getRemotePath().equals(uploadRemotePath) ||
749 renamedInUpload) {
750 if (uploadWasFine) {
751 mFile = mStorageManager.getFileByPath(uploadRemotePath);
752 }
753 if (renamedInUpload) {
754 String newName = (new File(uploadRemotePath)).getName();
755 Toast msg = Toast.makeText(getActivity().getApplicationContext(), String.format(getString(R.string.filedetails_renamed_in_upload_msg), newName), Toast.LENGTH_LONG);
756 msg.show();
757 }
758 getSherlockActivity().removeStickyBroadcast(intent); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
759 updateFileDetails(false, false); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
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( mFile,
771 mAccount,
772 newFilename,
773 new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
774 mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
775 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
776 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
777 }
778 }
779
780
781 /**
782 * {@inheritDoc}
783 */
784 @Override
785 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
786 if (operation.equals(mLastRemoteOperation)) {
787 if (operation instanceof RemoveFileOperation) {
788 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
789
790 } else if (operation instanceof RenameFileOperation) {
791 onRenameFileOperationFinish((RenameFileOperation)operation, result);
792
793 } else if (operation instanceof SynchronizeFileOperation) {
794 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
795 }
796 }
797 }
798
799
800 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
801 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
802 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
803
804 if (result.isSuccess()) {
805 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
806 msg.show();
807 if (inDisplayActivity) {
808 // double pane
809 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
810 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
811 transaction.commit();
812 mContainerActivity.onFileStateChanged();
813 } else {
814 getActivity().finish();
815 }
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 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
828 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
829
830 if (result.isSuccess()) {
831 updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
832 mContainerActivity.onFileStateChanged();
833
834 } else {
835 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
836 Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
837 msg.show();
838 // TODO throw again the new rename dialog
839 } else {
840 Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
841 msg.show();
842 if (result.isSslRecoverableException()) {
843 // TODO show the SSL warning dialog
844 }
845 }
846 }
847 }
848
849 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
850 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
851 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
852
853 if (!result.isSuccess()) {
854 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
855 Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
856 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, mFile);
857 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
858 startActivity(i);
859
860 } else {
861 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
862 msg.show();
863 }
864
865 if (mFile.isDown()) {
866 setButtonsForDown();
867
868 } else {
869 setButtonsForRemote();
870 }
871
872 } else {
873 if (operation.transferWasRequested()) {
874 setButtonsForTransferring();
875 mContainerActivity.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
876 // checking the service to see if the file is downloading results in FALSE
877 } else {
878 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
879 msg.show();
880 if (mFile.isDown()) {
881 setButtonsForDown();
882
883 } else {
884 setButtonsForRemote();
885 }
886 }
887 }
888 }
889
890
891 public void listenForTransferProgress() {
892 if (mProgressListener != null) {
893 if (mContainerActivity.getFileDownloaderBinder() != null) {
894 mContainerActivity.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
895 }
896 if (mContainerActivity.getFileUploaderBinder() != null) {
897 mContainerActivity.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener, mAccount, mFile);
898 }
899 }
900 }
901
902
903 public void leaveTransferProgress() {
904 if (mProgressListener != null) {
905 if (mContainerActivity.getFileDownloaderBinder() != null) {
906 mContainerActivity.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
907 }
908 if (mContainerActivity.getFileUploaderBinder() != null) {
909 mContainerActivity.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener, mAccount, mFile);
910 }
911 }
912 }
913
914
915
916 /**
917 * Helper class responsible for updating the progress bar shown for file uploading or downloading
918 *
919 * @author David A. Velasco
920 */
921 private class ProgressListener implements OnDatatransferProgressListener {
922 int mLastPercent = 0;
923 WeakReference<ProgressBar> mProgressBar = null;
924
925 ProgressListener(ProgressBar progressBar) {
926 mProgressBar = new WeakReference<ProgressBar>(progressBar);
927 }
928
929 @Override
930 public void onTransferProgress(long progressRate) {
931 // old method, nothing here
932 };
933
934 @Override
935 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String filename) {
936 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
937 if (percent != mLastPercent) {
938 ProgressBar pb = mProgressBar.get();
939 if (pb != null) {
940 pb.setProgress(percent);
941 pb.postInvalidate();
942 }
943 }
944 mLastPercent = percent;
945 }
946
947 };
948
949 /*
950 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
951 @SuppressWarnings("unused")
952 private class ShareRunnable implements Runnable {
953 private String mPath;
954
955 public ShareRunnable(String path) {
956 mPath = path;
957 }
958
959 public void run() {
960 AccountManager am = AccountManager.get(getActivity());
961 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
962 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
963 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
964
965 Log_OC.d("share", "sharing for version " + ocv.toString());
966
967 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
968 String APPS_PATH = "/apps/files_sharing/";
969 String SHARE_PATH = "ajax/share.php";
970
971 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
972
973 final String WEBDAV_SCRIPT = "webdav.php";
974 final String WEBDAV_FILES_LOCATION = "/files/";
975
976 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
977 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
978 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
979
980 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
981 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
982
983 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
984
985 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
986 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
987 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
988 Log_OC.d("share", mPath+"");
989 formparams.add(new BasicNameValuePair("sources",mPath));
990 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
991 formparams.add(new BasicNameValuePair("permissions", "0"));
992 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
993
994 int status;
995 try {
996 PropFindMethod find = new PropFindMethod(url+"/");
997 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
998 Log_OC.d("sharer", ""+ url+"/");
999
1000 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
1001 Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
1002 }
1003
1004 int status2 = wc.executeMethod(find);
1005
1006 Log_OC.d("sharer", "propstatus "+status2);
1007
1008 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
1009 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
1010
1011 status2 = wc.executeMethod(get);
1012
1013 Log_OC.d("sharer", "getstatus "+status2);
1014 Log_OC.d("sharer", "" + get.getResponseBodyAsString());
1015
1016 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
1017 Log_OC.d("sharer", a.getName() + ":"+a.getValue());
1018 }
1019
1020 status = wc.executeMethod(post);
1021 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
1022 Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
1023 }
1024 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
1025 Log_OC.d("sharer", a.getName() + ":"+a.getValue());
1026 }
1027 String resp = post.getResponseBodyAsString();
1028 Log_OC.d("share", ""+post.getURI().toString());
1029 Log_OC.d("share", "returned status " + status);
1030 Log_OC.d("share", " " +resp);
1031
1032 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
1033 return;
1034 }
1035
1036 JSONObject jsonObject = new JSONObject (resp);
1037 String jsonStatus = jsonObject.getString("status");
1038 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
1039
1040 String token = jsonObject.getString("data");
1041 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
1042 Log_OC.d("Actions:shareFile ok", "url: " + uri);
1043
1044 } catch (Exception e) {
1045 e.printStackTrace();
1046 }
1047
1048 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
1049
1050 }
1051 }
1052 }
1053 */
1054
1055 }