1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.fragment
;
22 import java
.lang
.ref
.WeakReference
;
23 import java
.util
.ArrayList
;
24 import java
.util
.List
;
26 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
27 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
28 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
29 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
30 import org
.apache
.http
.HttpStatus
;
31 import org
.apache
.http
.NameValuePair
;
32 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
33 import org
.apache
.http
.message
.BasicNameValuePair
;
34 import org
.apache
.http
.protocol
.HTTP
;
35 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
36 import org
.json
.JSONObject
;
38 import android
.accounts
.Account
;
39 import android
.accounts
.AccountManager
;
40 //import android.annotation.SuppressLint;
41 import android
.app
.Activity
;
42 import android
.content
.ActivityNotFoundException
;
43 import android
.content
.BroadcastReceiver
;
44 import android
.content
.Context
;
45 import android
.content
.Intent
;
46 import android
.content
.IntentFilter
;
47 import android
.net
.Uri
;
48 import android
.os
.Bundle
;
49 import android
.os
.Handler
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.util
.Log
;
52 import android
.view
.LayoutInflater
;
53 import android
.view
.View
;
54 import android
.view
.View
.OnClickListener
;
55 import android
.view
.ViewGroup
;
56 import android
.webkit
.MimeTypeMap
;
57 import android
.widget
.Button
;
58 import android
.widget
.CheckBox
;
59 import android
.widget
.ImageView
;
60 import android
.widget
.ProgressBar
;
61 import android
.widget
.TextView
;
62 import android
.widget
.Toast
;
64 import android
.graphics
.Bitmap
;
65 import android
.graphics
.BitmapFactory
;
66 import android
.graphics
.BitmapFactory
.Options
;
67 import android
.graphics
.Point
;
68 import android
.net
.Uri
;
69 import android
.os
.AsyncTask
;
70 import android
.os
.Bundle
;
71 import android
.os
.Handler
;
72 import android
.support
.v4
.app
.DialogFragment
;
73 import android
.support
.v4
.app
.FragmentTransaction
;
74 import android
.util
.Log
;
75 import android
.view
.Display
;
76 import android
.view
.LayoutInflater
;
77 import android
.view
.View
;
78 import android
.view
.View
.OnClickListener
;
79 import android
.view
.ViewGroup
;
80 import android
.webkit
.MimeTypeMap
;
81 import android
.widget
.Button
;
82 import android
.widget
.CheckBox
;
83 import android
.widget
.ImageView
;
84 import android
.widget
.TextView
;
85 import android
.widget
.Toast
;
88 import com
.actionbarsherlock
.app
.SherlockFragment
;
89 import com
.owncloud
.android
.AccountUtils
;
90 import com
.owncloud
.android
.DisplayUtils
;
91 import com
.owncloud
.android
.Log_OC
;
92 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
93 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
94 import com
.owncloud
.android
.datamodel
.OCFile
;
95 import com
.owncloud
.android
.files
.services
.FileObserverService
;
96 import com
.owncloud
.android
.files
.services
.FileUploader
;
97 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
98 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
99 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
100 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
101 import com
.owncloud
.android
.operations
.RemoteOperation
;
102 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
103 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
104 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
105 import com
.owncloud
.android
.operations
.RenameFileOperation
;
106 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
107 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
108 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
109 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
110 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
111 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
112 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
114 import com
.owncloud
.android
.R
;
116 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
117 import eu
.alefzero
.webdav
.WebdavClient
;
118 import eu
.alefzero
.webdav
.WebdavUtils
;
122 * This Fragment is used to display the details about a file.
124 * @author Bartek Przybylski
125 * @author David A. Velasco
127 public class FileDetailFragment
extends SherlockFragment
implements
129 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
132 public static final String EXTRA_FILE
= "FILE";
133 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
135 private FileFragment
.ContainerActivity mContainerActivity
;
139 private OCFile mFile
;
140 private Account mAccount
;
141 private FileDataStorageManager mStorageManager
;
143 private UploadFinishReceiver mUploadFinishReceiver
;
144 public ProgressListener mProgressListener
;
146 private Handler mHandler
;
147 private RemoteOperation mLastRemoteOperation
;
149 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
150 public static final String FTAG
= "FileDetails";
151 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
155 * Creates an empty details fragment.
157 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
159 public FileDetailFragment() {
162 mStorageManager
= null
;
163 mLayout
= R
.layout
.file_details_empty
;
164 mProgressListener
= null
;
169 * Creates a details fragment.
171 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
173 * @param fileToDetail An {@link OCFile} to show in the fragment
174 * @param ocAccount An ownCloud account; needed to start downloads
176 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
177 mFile
= fileToDetail
;
178 mAccount
= ocAccount
;
179 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
180 mLayout
= R
.layout
.file_details_empty
;
181 mProgressListener
= null
;
186 public void onCreate(Bundle savedInstanceState
) {
187 super.onCreate(savedInstanceState
);
188 mHandler
= new Handler();
193 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
194 Bundle savedInstanceState
) {
195 super.onCreateView(inflater
, container
, savedInstanceState
);
197 if (savedInstanceState
!= null
) {
198 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
199 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
202 if(mFile
!= null
&& mAccount
!= null
) {
203 mLayout
= R
.layout
.file_details_fragment
;
207 view
= inflater
.inflate(mLayout
, container
, false
);
210 if (mLayout
== R
.layout
.file_details_fragment
) {
211 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
212 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
213 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
214 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
215 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
216 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
217 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
218 mProgressListener
= new ProgressListener(progressBar
);
221 updateFileDetails(false
, false
);
230 public void onAttach(Activity activity
) {
231 super.onAttach(activity
);
233 mContainerActivity
= (ContainerActivity
) activity
;
235 } catch (ClassCastException e
) {
236 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
245 public void onActivityCreated(Bundle savedInstanceState
) {
246 super.onActivityCreated(savedInstanceState
);
247 if (mAccount
!= null
) {
248 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
254 public void onSaveInstanceState(Bundle outState
) {
255 super.onSaveInstanceState(outState
);
256 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
257 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
261 public void onStart() {
263 listenForTransferProgress();
267 public void onResume() {
269 mUploadFinishReceiver
= new UploadFinishReceiver();
270 IntentFilter filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
271 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
277 public void onPause() {
279 if (mUploadFinishReceiver
!= null
) {
280 getActivity().unregisterReceiver(mUploadFinishReceiver
);
281 mUploadFinishReceiver
= null
;
287 public void onStop() {
289 leaveTransferProgress();
294 public View
getView() {
295 return super.getView() == null ? mView
: super.getView();
299 public void onClick(View v
) {
301 case R
.id
.fdDownloadBtn
: {
302 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
303 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
304 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
305 downloaderBinder
.cancel(mAccount
, mFile
);
306 if (mFile
.isDown()) {
309 setButtonsForRemote();
312 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
313 uploaderBinder
.cancel(mAccount
, mFile
);
314 if (!mFile
.fileExists()) {
315 // TODO make something better
316 if (getActivity() instanceof FileDisplayActivity
) {
318 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
319 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
320 transaction
.commit();
321 mContainerActivity
.onFileStateChanged();
323 getActivity().finish();
326 } else if (mFile
.isDown()) {
329 setButtonsForRemote();
333 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
334 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
335 mLastRemoteOperation
.execute(wc
, this, mHandler
);
338 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
339 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
344 case R
.id
.fdKeepInSync
: {
345 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
346 mFile
.setKeepInSync(cb
.isChecked());
347 mStorageManager
.saveFile(mFile
);
349 /// register the OCFile instance in the observer service to monitor local updates;
350 /// if necessary, the file is download
351 Intent intent
= new Intent(getActivity().getApplicationContext(),
352 FileObserverService
.class);
353 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
355 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
356 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
357 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
358 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
359 getActivity().startService(intent
);
361 if (mFile
.keepInSync()) {
362 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
366 case R
.id
.fdRenameBtn
: {
367 String fileName
= mFile
.getFileName();
368 int extensionStart
= mFile
.isDirectory() ?
-1 : fileName
.lastIndexOf(".");
369 int selectionEnd
= (extensionStart
>= 0) ? extensionStart
: fileName
.length();
370 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), fileName
, 0, selectionEnd
, this);
371 dialog
.show(getFragmentManager(), "nameeditdialog");
374 case R
.id
.fdRemoveBtn
: {
375 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
376 R
.string
.confirmation_remove_alert
,
377 new String
[]{mFile
.getFileName()},
378 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
379 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
380 R
.string
.common_cancel
);
381 confDialog
.setOnConfirmationListener(this);
382 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
385 case R
.id
.fdOpenBtn
: {
390 Log_OC
.e(TAG
, "Incorrect view clicked!");
393 /* else if (v.getId() == R.id.fdShareBtn) {
394 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
403 private void openFile() {
405 String storagePath
= mFile
.getStoragePath();
406 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
408 Intent i
= new Intent(Intent
.ACTION_VIEW
);
409 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
410 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
413 } catch (Throwable t
) {
414 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
415 boolean toastIt
= true
;
416 String mimeType
= "";
418 Intent i
= new Intent(Intent
.ACTION_VIEW
);
419 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
420 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
421 if (mimeType
!= null
) {
422 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
425 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
427 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
432 } catch (IndexOutOfBoundsException e
) {
433 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
435 } catch (ActivityNotFoundException e
) {
436 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
438 } catch (Throwable th
) {
439 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
443 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
452 public void onConfirmation(String callerTag
) {
453 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
454 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
455 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
458 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
459 mLastRemoteOperation
.execute(wc
, this, mHandler
);
461 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
462 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
468 public void onNeutral(String callerTag
) {
470 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
472 mFile
.setStoragePath(null
);
473 mStorageManager
.saveFile(mFile
);
474 updateFileDetails(mFile
, mAccount
);
479 public void onCancel(String callerTag
) {
480 Log
.d(TAG
, "REMOVAL CANCELED");
485 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
487 * @return True when the fragment was created with the empty layout.
489 public boolean isEmpty() {
490 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
497 public OCFile
getFile(){
502 * Use this method to signal this Activity that it shall update its view.
504 * @param file : An {@link OCFile}
506 public void updateFileDetails(OCFile file
, Account ocAccount
) {
508 if (ocAccount
!= null
&& (
509 mStorageManager
== null
||
510 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
512 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
514 mAccount
= ocAccount
;
515 updateFileDetails(false
, false
);
519 * Updates the view with all relevant details about that file.
521 * TODO Remove parameter when the transferring state of files is kept in database.
523 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
525 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
526 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
527 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
529 * @param refresh If 'true', try to refresh the hold file from the database
531 public void updateFileDetails(boolean transferring
, boolean refresh
) {
535 if (refresh
&& mStorageManager
!= null
) {
536 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
540 setFilename(mFile
.getFileName());
541 setFiletype(mFile
.getMimetype());
542 setFilesize(mFile
.getFileLength());
543 if(ocVersionSupportsTimeCreated()){
544 setTimeCreated(mFile
.getCreationTimestamp());
547 setTimeModified(mFile
.getModificationTimestamp());
549 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
550 cb
.setChecked(mFile
.keepInSync());
552 // configure UI for depending upon local state of the file
553 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
554 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
555 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
556 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
557 setButtonsForTransferring();
559 } else if (mFile
.isDown()) {
564 // TODO load default preview image; when the local file is removed, the preview remains there
565 setButtonsForRemote();
568 getView().invalidate();
573 * Checks if the fragment is ready to show details of a OCFile
575 * @return 'True' when the fragment is ready to show details of a file
577 private boolean readyToShow() {
578 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
583 * Updates the filename in view
584 * @param filename to set
586 private void setFilename(String filename
) {
587 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
589 tv
.setText(filename
);
593 * Updates the MIME type in view
594 * @param mimetype to set
596 private void setFiletype(String mimetype
) {
597 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
599 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
600 tv
.setText(printableMimetype
);
602 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
604 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
609 * Updates the file size in view
610 * @param filesize in bytes to set
612 private void setFilesize(long filesize
) {
613 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
615 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
619 * Updates the time that the file was created in view
620 * @param milliseconds Unix time to set
622 private void setTimeCreated(long milliseconds
){
623 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
624 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
626 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
627 tv
.setVisibility(View
.VISIBLE
);
628 tvLabel
.setVisibility(View
.VISIBLE
);
633 * Updates the time that the file was last modified
634 * @param milliseconds Unix time to set
636 private void setTimeModified(long milliseconds
){
637 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
639 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
644 * Enables or disables buttons for a file being downloaded
646 private void setButtonsForTransferring() {
648 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
649 downloadButton
.setText(R
.string
.common_cancel
);
650 //downloadButton.setEnabled(false);
652 // let's protect the user from himself ;)
653 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
654 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
655 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
656 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
658 // show the progress bar for the transfer
659 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
660 progressBar
.setVisibility(View
.VISIBLE
);
661 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
662 progressText
.setVisibility(View
.VISIBLE
);
663 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
664 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
665 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
666 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
667 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
668 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
674 * Enables or disables buttons for a file locally available
676 private void setButtonsForDown() {
678 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
679 downloadButton
.setText(R
.string
.filedetails_sync_file
);
681 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
682 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
683 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
684 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
686 // hides the progress bar
687 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
688 progressBar
.setVisibility(View
.GONE
);
689 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
690 progressText
.setVisibility(View
.GONE
);
695 * Enables or disables buttons for a file not locally available
697 private void setButtonsForRemote() {
699 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
700 downloadButton
.setText(R
.string
.filedetails_download
);
702 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
703 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
704 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
705 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
707 // hides the progress bar
708 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
709 progressBar
.setVisibility(View
.GONE
);
710 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
711 progressText
.setVisibility(View
.GONE
);
717 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
718 * the time that the file was created. There is a chance that this will
719 * be fixed in future versions. Use this method to check if this version of
720 * ownCloud has this fix.
721 * @return True, if ownCloud the ownCloud version is supporting creation time
723 private boolean ocVersionSupportsTimeCreated(){
724 /*if(mAccount != null){
725 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
726 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
727 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
728 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
737 * Once the file upload has finished -> update view
739 * Being notified about the finish of an upload is necessary for the next sequence:
740 * 1. Upload a big file.
741 * 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
742 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
743 * 3. Click the file in the list to see its details.
744 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
746 private class UploadFinishReceiver
extends BroadcastReceiver
{
748 public void onReceive(Context context
, Intent intent
) {
749 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
751 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
752 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
753 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
754 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
755 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
758 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
760 if (renamedInUpload
) {
761 String newName
= (new File(uploadRemotePath
)).getName();
762 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
765 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
766 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
773 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
774 @SuppressWarnings("unused")
775 private class ShareRunnable
implements Runnable
{
776 private String mPath
;
778 public ShareRunnable(String path
) {
783 AccountManager am
= AccountManager
.get(getActivity());
784 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
785 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
786 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
788 Log
.d("share", "sharing for version " + ocv
.toString());
790 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
791 String APPS_PATH
= "/apps/files_sharing/";
792 String SHARE_PATH
= "ajax/share.php";
794 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
796 final String WEBDAV_SCRIPT
= "webdav.php";
797 final String WEBDAV_FILES_LOCATION
= "/files/";
799 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
800 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
801 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
803 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
804 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
806 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
808 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
809 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
810 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
811 Log
.d("share", mPath
+"");
812 formparams
.add(new BasicNameValuePair("sources",mPath
));
813 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
814 formparams
.add(new BasicNameValuePair("permissions", "0"));
815 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
819 PropFindMethod find
= new PropFindMethod(url
+"/");
820 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
821 Log
.d("sharer", ""+ url
+"/");
823 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
824 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
827 int status2
= wc
.executeMethod(find
);
829 Log
.d("sharer", "propstatus "+status2
);
831 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
832 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
834 status2
= wc
.executeMethod(get
);
836 Log
.d("sharer", "getstatus "+status2
);
837 Log
.d("sharer", "" + get
.getResponseBodyAsString());
839 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
840 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
843 status
= wc
.executeMethod(post
);
844 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
845 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
847 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
848 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
850 String resp
= post
.getResponseBodyAsString();
851 Log
.d("share", ""+post
.getURI().toString());
852 Log
.d("share", "returned status " + status
);
853 Log
.d("share", " " +resp
);
855 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
859 JSONObject jsonObject
= new JSONObject (resp
);
860 String jsonStatus
= jsonObject
.getString("status");
861 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
863 String token
= jsonObject
.getString("data");
864 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
865 Log
.d("Actions:shareFile ok", "url: " + uri
);
867 } catch (Exception e
) {
871 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
877 public void onDismiss(EditNameDialog dialog
) {
878 if (dialog
.getResult()) {
879 String newFilename
= dialog
.getNewFilename();
880 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
881 mLastRemoteOperation
= new RenameFileOperation( mFile
,
884 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
885 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
886 mLastRemoteOperation
.execute(wc
, this, mHandler
);
887 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
888 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
897 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
898 if (operation
.equals(mLastRemoteOperation
)) {
899 if (operation
instanceof RemoveFileOperation
) {
900 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
902 } else if (operation
instanceof RenameFileOperation
) {
903 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
905 } else if (operation
instanceof SynchronizeFileOperation
) {
906 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
912 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
913 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
914 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
916 if (result
.isSuccess()) {
917 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
919 if (inDisplayActivity
) {
921 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
922 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
923 transaction
.commit();
924 mContainerActivity
.onFileStateChanged();
926 getActivity().finish();
930 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
932 if (result
.isSslRecoverableException()) {
933 // TODO show the SSL warning dialog
938 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
939 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
940 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
942 if (result
.isSuccess()) {
943 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
944 mContainerActivity
.onFileStateChanged();
947 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
948 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
950 // TODO throw again the new rename dialog
952 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
954 if (result
.isSslRecoverableException()) {
955 // TODO show the SSL warning dialog
961 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
962 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
963 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
965 if (!result
.isSuccess()) {
966 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
967 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
968 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
969 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
973 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
977 if (mFile
.isDown()) {
981 setButtonsForRemote();
985 if (operation
.transferWasRequested()) {
986 setButtonsForTransferring();
987 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
988 // checking the service to see if the file is downloading results in FALSE
990 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
992 if (mFile
.isDown()) {
996 setButtonsForRemote();
1003 public void listenForTransferProgress() {
1004 if (mProgressListener
!= null
) {
1005 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1006 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1008 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1009 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1015 public void leaveTransferProgress() {
1016 if (mProgressListener
!= null
) {
1017 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1018 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1020 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1021 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1029 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1031 * @author David A. Velasco
1033 private class ProgressListener
implements OnDatatransferProgressListener
{
1034 int mLastPercent
= 0;
1035 WeakReference
<ProgressBar
> mProgressBar
= null
;
1037 ProgressListener(ProgressBar progressBar
) {
1038 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
1042 public void onTransferProgress(long progressRate
) {
1043 // old method, nothing here
1047 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
1048 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
1049 if (percent
!= mLastPercent
) {
1050 ProgressBar pb
= mProgressBar
.get();
1052 pb
.setProgress(percent
);
1053 pb
.postInvalidate();
1056 mLastPercent
= percent
;