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