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