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