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