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