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