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