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