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