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