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