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 version 2,
7 * as published by the Free Software Foundation.
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.
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/>.
18 package com
.owncloud
.android
.ui
.fragment
;
21 import java
.lang
.ref
.WeakReference
;
23 import android
.accounts
.Account
;
24 import android
.app
.Activity
;
25 import android
.content
.ActivityNotFoundException
;
26 import android
.content
.BroadcastReceiver
;
27 import android
.content
.Context
;
28 import android
.content
.Intent
;
29 import android
.content
.IntentFilter
;
30 import android
.net
.Uri
;
31 import android
.os
.Bundle
;
32 import android
.os
.Handler
;
33 import android
.support
.v4
.app
.FragmentTransaction
;
34 import android
.view
.LayoutInflater
;
35 import android
.view
.View
;
36 import android
.view
.View
.OnClickListener
;
37 import android
.view
.ViewGroup
;
38 import android
.webkit
.MimeTypeMap
;
39 import android
.widget
.Button
;
40 import android
.widget
.CheckBox
;
41 import android
.widget
.ImageView
;
42 import android
.widget
.ProgressBar
;
43 import android
.widget
.TextView
;
44 import android
.widget
.Toast
;
46 import com
.actionbarsherlock
.app
.SherlockFragment
;
47 import com
.owncloud
.android
.DisplayUtils
;
48 import com
.owncloud
.android
.Log_OC
;
49 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
50 import com
.owncloud
.android
.datamodel
.OCFile
;
51 import com
.owncloud
.android
.files
.services
.FileObserverService
;
52 import com
.owncloud
.android
.files
.services
.FileUploader
;
53 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
54 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
55 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
56 import com
.owncloud
.android
.operations
.RemoteOperation
;
57 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
58 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
59 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
60 import com
.owncloud
.android
.operations
.RenameFileOperation
;
61 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
62 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
63 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
64 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
65 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
66 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
68 import com
.owncloud
.android
.R
;
70 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
71 import eu
.alefzero
.webdav
.WebdavUtils
;
74 * This Fragment is used to display the details about a file.
76 * @author Bartek Przybylski
77 * @author David A. Velasco
79 public class FileDetailFragment
extends SherlockFragment
implements
81 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
84 public static final String EXTRA_FILE
= "FILE";
85 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
87 private FileFragment
.ContainerActivity mContainerActivity
;
92 private Account mAccount
;
93 private FileDataStorageManager mStorageManager
;
95 private UploadFinishReceiver mUploadFinishReceiver
;
96 public ProgressListener mProgressListener
;
98 private Handler mHandler
;
99 private RemoteOperation mLastRemoteOperation
;
101 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
102 public static final String FTAG
= "FileDetails";
103 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
107 * Creates an empty details fragment.
109 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
111 public FileDetailFragment() {
114 mStorageManager
= null
;
115 mLayout
= R
.layout
.file_details_empty
;
116 mProgressListener
= null
;
120 * Creates a details fragment.
122 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
124 * @param fileToDetail An {@link OCFile} to show in the fragment
125 * @param ocAccount An ownCloud account; needed to start downloads
127 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
128 mFile
= fileToDetail
;
129 mAccount
= ocAccount
;
130 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
131 mLayout
= R
.layout
.file_details_empty
;
132 mProgressListener
= null
;
137 public void onCreate(Bundle savedInstanceState
) {
138 super.onCreate(savedInstanceState
);
139 mHandler
= new Handler();
144 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
145 Bundle savedInstanceState
) {
146 super.onCreateView(inflater
, container
, savedInstanceState
);
148 if (savedInstanceState
!= null
) {
149 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
150 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
153 if(mFile
!= null
&& mAccount
!= null
) {
154 mLayout
= R
.layout
.file_details_fragment
;
158 view
= inflater
.inflate(mLayout
, container
, false
);
161 if (mLayout
== R
.layout
.file_details_fragment
) {
162 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
163 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
164 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
165 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
166 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
167 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
168 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
169 mProgressListener
= new ProgressListener(progressBar
);
172 updateFileDetails(false
, false
);
181 public void onAttach(Activity activity
) {
182 super.onAttach(activity
);
184 mContainerActivity
= (ContainerActivity
) activity
;
186 } catch (ClassCastException e
) {
187 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
196 public void onActivityCreated(Bundle savedInstanceState
) {
197 super.onActivityCreated(savedInstanceState
);
198 if (mAccount
!= null
) {
199 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
205 public void onSaveInstanceState(Bundle outState
) {
206 super.onSaveInstanceState(outState
);
207 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
208 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
212 public void onStart() {
214 listenForTransferProgress();
218 public void onResume() {
220 mUploadFinishReceiver
= new UploadFinishReceiver();
221 IntentFilter filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
222 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
228 public void onPause() {
230 if (mUploadFinishReceiver
!= null
) {
231 getActivity().unregisterReceiver(mUploadFinishReceiver
);
232 mUploadFinishReceiver
= null
;
238 public void onStop() {
240 leaveTransferProgress();
245 public View
getView() {
246 return super.getView() == null ? mView
: super.getView();
251 public void onClick(View v
) {
253 case R
.id
.fdDownloadBtn
: {
254 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
255 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
256 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
257 downloaderBinder
.cancel(mAccount
, mFile
);
258 if (mFile
.isDown()) {
261 setButtonsForRemote();
264 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
265 uploaderBinder
.cancel(mAccount
, mFile
);
266 if (!mFile
.fileExists()) {
267 // TODO make something better
268 if (getActivity() instanceof FileDisplayActivity
) {
270 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
271 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
272 transaction
.commit();
273 mContainerActivity
.onFileStateChanged();
275 getActivity().finish();
278 } else if (mFile
.isDown()) {
281 setButtonsForRemote();
285 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
286 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
289 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
290 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
291 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
296 case R
.id
.fdKeepInSync
: {
297 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
298 mFile
.setKeepInSync(cb
.isChecked());
299 mStorageManager
.saveFile(mFile
);
301 /// register the OCFile instance in the observer service to monitor local updates;
302 /// if necessary, the file is download
303 Intent intent
= new Intent(getActivity().getApplicationContext(),
304 FileObserverService
.class);
305 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
307 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
308 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
309 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
310 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
311 getActivity().startService(intent
);
313 if (mFile
.keepInSync()) {
314 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
318 case R
.id
.fdRenameBtn
: {
319 String fileName
= mFile
.getFileName();
320 int extensionStart
= mFile
.isDirectory() ?
-1 : fileName
.lastIndexOf(".");
321 int selectionEnd
= (extensionStart
>= 0) ? extensionStart
: fileName
.length();
322 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), fileName
, 0, selectionEnd
, this);
323 dialog
.show(getFragmentManager(), "nameeditdialog");
326 case R
.id
.fdRemoveBtn
: {
327 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
328 R
.string
.confirmation_remove_alert
,
329 new String
[]{mFile
.getFileName()},
330 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
331 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
332 R
.string
.common_cancel
);
333 confDialog
.setOnConfirmationListener(this);
334 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
337 case R
.id
.fdOpenBtn
: {
342 Log_OC
.e(TAG
, "Incorrect view clicked!");
350 private void openFile() {
352 String storagePath
= mFile
.getStoragePath();
353 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
355 Intent i
= new Intent(Intent
.ACTION_VIEW
);
356 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
357 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
360 } catch (Throwable t
) {
361 Log_OC
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
362 boolean toastIt
= true
;
363 String mimeType
= "";
365 Intent i
= new Intent(Intent
.ACTION_VIEW
);
366 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
367 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
368 if (mimeType
!= null
) {
369 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
372 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
374 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
379 } catch (IndexOutOfBoundsException e
) {
380 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
382 } catch (ActivityNotFoundException e
) {
383 Log_OC
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
385 } catch (Throwable th
) {
386 Log_OC
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
390 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
398 public void onConfirmation(String callerTag
) {
399 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
400 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
401 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
404 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
406 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
407 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
413 public void onNeutral(String callerTag
) {
415 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
417 mFile
.setStoragePath(null
);
418 mStorageManager
.saveFile(mFile
);
419 updateFileDetails(mFile
, mAccount
);
424 public void onCancel(String callerTag
) {
425 Log_OC
.d(TAG
, "REMOVAL CANCELED");
430 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
432 * @return True when the fragment was created with the empty layout.
434 public boolean isEmpty() {
435 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
442 public OCFile
getFile(){
447 * Use this method to signal this Activity that it shall update its view.
449 * @param file : An {@link OCFile}
451 public void updateFileDetails(OCFile file
, Account ocAccount
) {
453 if (ocAccount
!= null
&& (
454 mStorageManager
== null
||
455 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
457 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
459 mAccount
= ocAccount
;
460 updateFileDetails(false
, false
);
464 * Updates the view with all relevant details about that file.
466 * TODO Remove parameter when the transferring state of files is kept in database.
468 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
470 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
471 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
472 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
474 * @param refresh If 'true', try to refresh the hold file from the database
476 public void updateFileDetails(boolean transferring
, boolean refresh
) {
480 if (refresh
&& mStorageManager
!= null
) {
481 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
485 setFilename(mFile
.getFileName());
486 setFiletype(mFile
.getMimetype());
487 setFilesize(mFile
.getFileLength());
488 if(ocVersionSupportsTimeCreated()){
489 setTimeCreated(mFile
.getCreationTimestamp());
492 setTimeModified(mFile
.getModificationTimestamp());
494 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
495 cb
.setChecked(mFile
.keepInSync());
497 // configure UI for depending upon local state of the file
498 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
499 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
500 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
501 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
502 setButtonsForTransferring();
504 } else if (mFile
.isDown()) {
509 // TODO load default preview image; when the local file is removed, the preview remains there
510 setButtonsForRemote();
513 getView().invalidate();
517 * Checks if the fragment is ready to show details of a OCFile
519 * @return 'True' when the fragment is ready to show details of a file
521 private boolean readyToShow() {
522 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
527 * Updates the filename in view
528 * @param filename to set
530 private void setFilename(String filename
) {
531 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
533 tv
.setText(filename
);
537 * Updates the MIME type in view
538 * @param mimetype to set
540 private void setFiletype(String mimetype
) {
541 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
543 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
544 tv
.setText(printableMimetype
);
546 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
548 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
553 * Updates the file size in view
554 * @param filesize in bytes to set
556 private void setFilesize(long filesize
) {
557 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
559 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
563 * Updates the time that the file was created in view
564 * @param milliseconds Unix time to set
566 private void setTimeCreated(long milliseconds
){
567 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
568 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
570 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
571 tv
.setVisibility(View
.VISIBLE
);
572 tvLabel
.setVisibility(View
.VISIBLE
);
577 * Updates the time that the file was last modified
578 * @param milliseconds Unix time to set
580 private void setTimeModified(long milliseconds
){
581 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
583 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
588 * Enables or disables buttons for a file being downloaded
590 private void setButtonsForTransferring() {
592 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
593 downloadButton
.setText(R
.string
.common_cancel
);
594 //downloadButton.setEnabled(false);
596 // let's protect the user from himself ;)
597 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
598 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
599 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
600 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
602 // show the progress bar for the transfer
603 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
604 progressBar
.setVisibility(View
.VISIBLE
);
605 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
606 progressText
.setVisibility(View
.VISIBLE
);
607 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
608 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
609 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
610 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
611 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
612 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
618 * Enables or disables buttons for a file locally available
620 private void setButtonsForDown() {
622 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
623 downloadButton
.setText(R
.string
.filedetails_sync_file
);
625 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
626 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
627 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
628 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
630 // hides the progress bar
631 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
632 progressBar
.setVisibility(View
.GONE
);
633 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
634 progressText
.setVisibility(View
.GONE
);
639 * Enables or disables buttons for a file not locally available
641 private void setButtonsForRemote() {
643 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
644 downloadButton
.setText(R
.string
.filedetails_download
);
646 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
647 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
648 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
649 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
651 // hides the progress bar
652 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
653 progressBar
.setVisibility(View
.GONE
);
654 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
655 progressText
.setVisibility(View
.GONE
);
661 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
662 * the time that the file was created. There is a chance that this will
663 * be fixed in future versions. Use this method to check if this version of
664 * ownCloud has this fix.
665 * @return True, if ownCloud the ownCloud version is supporting creation time
667 private boolean ocVersionSupportsTimeCreated(){
668 /*if(mAccount != null){
669 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
670 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
671 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
672 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
681 * Once the file upload has finished -> update view
683 * Being notified about the finish of an upload is necessary for the next sequence:
684 * 1. Upload a big file.
685 * 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
686 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
687 * 3. Click the file in the list to see its details.
688 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
690 private class UploadFinishReceiver
extends BroadcastReceiver
{
692 public void onReceive(Context context
, Intent intent
) {
693 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
695 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
696 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
697 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
698 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
699 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
702 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
704 if (renamedInUpload
) {
705 String newName
= (new File(uploadRemotePath
)).getName();
706 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
709 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
710 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
717 public void onDismiss(EditNameDialog dialog
) {
718 if (dialog
.getResult()) {
719 String newFilename
= dialog
.getNewFilename();
720 Log_OC
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
721 mLastRemoteOperation
= new RenameFileOperation( mFile
,
724 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
725 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
726 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
727 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
736 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
737 if (operation
.equals(mLastRemoteOperation
)) {
738 if (operation
instanceof RemoveFileOperation
) {
739 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
741 } else if (operation
instanceof RenameFileOperation
) {
742 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
744 } else if (operation
instanceof SynchronizeFileOperation
) {
745 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
751 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
752 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
753 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
755 if (result
.isSuccess()) {
756 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
758 if (inDisplayActivity
) {
760 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
761 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
762 transaction
.commit();
763 mContainerActivity
.onFileStateChanged();
765 getActivity().finish();
769 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
771 if (result
.isSslRecoverableException()) {
772 // TODO show the SSL warning dialog
777 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
778 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
779 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
781 if (result
.isSuccess()) {
782 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
783 mContainerActivity
.onFileStateChanged();
786 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
787 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
789 // TODO throw again the new rename dialog
791 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
793 if (result
.isSslRecoverableException()) {
794 // TODO show the SSL warning dialog
800 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
801 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
802 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
804 if (!result
.isSuccess()) {
805 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
806 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
807 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
808 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
812 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
816 if (mFile
.isDown()) {
820 setButtonsForRemote();
824 if (operation
.transferWasRequested()) {
825 setButtonsForTransferring();
826 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
827 // checking the service to see if the file is downloading results in FALSE
829 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
831 if (mFile
.isDown()) {
835 setButtonsForRemote();
842 public void listenForTransferProgress() {
843 if (mProgressListener
!= null
) {
844 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
845 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
847 if (mContainerActivity
.getFileUploaderBinder() != null
) {
848 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
854 public void leaveTransferProgress() {
855 if (mProgressListener
!= null
) {
856 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
857 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
859 if (mContainerActivity
.getFileUploaderBinder() != null
) {
860 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
868 * Helper class responsible for updating the progress bar shown for file uploading or downloading
870 * @author David A. Velasco
872 private class ProgressListener
implements OnDatatransferProgressListener
{
873 int mLastPercent
= 0;
874 WeakReference
<ProgressBar
> mProgressBar
= null
;
876 ProgressListener(ProgressBar progressBar
) {
877 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
881 public void onTransferProgress(long progressRate
) {
882 // old method, nothing here
886 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
887 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
888 if (percent
!= mLastPercent
) {
889 ProgressBar pb
= mProgressBar
.get();
891 pb
.setProgress(percent
);
895 mLastPercent
= percent
;
901 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
902 @SuppressWarnings("unused")
903 private class ShareRunnable implements Runnable {
904 private String mPath;
906 public ShareRunnable(String path) {
911 AccountManager am = AccountManager.get(getActivity());
912 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
913 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
914 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
916 Log_OC.d("share", "sharing for version " + ocv.toString());
918 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
919 String APPS_PATH = "/apps/files_sharing/";
920 String SHARE_PATH = "ajax/share.php";
922 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
924 final String WEBDAV_SCRIPT = "webdav.php";
925 final String WEBDAV_FILES_LOCATION = "/files/";
927 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
928 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
929 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
931 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
932 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
934 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
936 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
937 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
938 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
939 Log_OC.d("share", mPath+"");
940 formparams.add(new BasicNameValuePair("sources",mPath));
941 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
942 formparams.add(new BasicNameValuePair("permissions", "0"));
943 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
947 PropFindMethod find = new PropFindMethod(url+"/");
948 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
949 Log_OC.d("sharer", ""+ url+"/");
951 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
952 Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
955 int status2 = wc.executeMethod(find);
957 Log_OC.d("sharer", "propstatus "+status2);
959 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
960 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
962 status2 = wc.executeMethod(get);
964 Log_OC.d("sharer", "getstatus "+status2);
965 Log_OC.d("sharer", "" + get.getResponseBodyAsString());
967 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
968 Log_OC.d("sharer", a.getName() + ":"+a.getValue());
971 status = wc.executeMethod(post);
972 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
973 Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
975 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
976 Log_OC.d("sharer", a.getName() + ":"+a.getValue());
978 String resp = post.getResponseBodyAsString();
979 Log_OC.d("share", ""+post.getURI().toString());
980 Log_OC.d("share", "returned status " + status);
981 Log_OC.d("share", " " +resp);
983 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
987 JSONObject jsonObject = new JSONObject (resp);
988 String jsonStatus = jsonObject.getString("status");
989 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
991 String token = jsonObject.getString("data");
992 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
993 Log_OC.d("Actions:shareFile ok", "url: " + uri);
995 } catch (Exception e) {
999 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {