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