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
;
22 import java
.util
.ArrayList
;
23 import java
.util
.List
;
25 import android
.accounts
.Account
;
26 import android
.app
.Activity
;
27 import android
.content
.BroadcastReceiver
;
28 import android
.content
.Context
;
29 import android
.content
.Intent
;
30 import android
.content
.IntentFilter
;
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
.widget
.CheckBox
;
39 import android
.widget
.ImageView
;
40 import android
.widget
.ProgressBar
;
41 import android
.widget
.TextView
;
42 import android
.widget
.Toast
;
44 import com
.actionbarsherlock
.app
.SherlockFragment
;
45 import com
.actionbarsherlock
.view
.Menu
;
46 import com
.actionbarsherlock
.view
.MenuInflater
;
47 import com
.actionbarsherlock
.view
.MenuItem
;
48 import com
.owncloud
.android
.DisplayUtils
;
49 import com
.owncloud
.android
.Log_OC
;
50 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
51 import com
.owncloud
.android
.datamodel
.OCFile
;
52 import com
.owncloud
.android
.files
.services
.FileObserverService
;
53 import com
.owncloud
.android
.files
.services
.FileUploader
;
54 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
55 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
56 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
57 import com
.owncloud
.android
.operations
.RemoteOperation
;
58 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
59 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
60 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
61 import com
.owncloud
.android
.operations
.RenameFileOperation
;
62 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
63 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
64 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
65 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
66 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
67 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
68 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
70 import com
.owncloud
.android
.R
;
72 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
75 * This Fragment is used to display the details about a file.
77 * @author Bartek Przybylski
78 * @author David A. Velasco
80 public class FileDetailFragment
extends SherlockFragment
implements
82 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
85 private FileFragment
.ContainerActivity mContainerActivity
;
90 private Account mAccount
;
91 private FileDataStorageManager mStorageManager
;
93 private UploadFinishReceiver mUploadFinishReceiver
;
94 public ProgressListener mProgressListener
;
96 private Handler mHandler
;
97 private RemoteOperation mLastRemoteOperation
;
99 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
100 public static final String FTAG
= "FileDetails";
101 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
105 * Creates an empty details fragment.
107 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
109 public FileDetailFragment() {
112 mStorageManager
= null
;
113 mLayout
= R
.layout
.file_details_empty
;
114 mProgressListener
= null
;
118 * Creates a details fragment.
120 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
122 * @param fileToDetail An {@link OCFile} to show in the fragment
123 * @param ocAccount An ownCloud account; needed to start downloads
125 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
126 mFile
= fileToDetail
;
127 mAccount
= ocAccount
;
128 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
129 mLayout
= R
.layout
.file_details_empty
;
130 mProgressListener
= null
;
135 public void onCreate(Bundle savedInstanceState
) {
136 super.onCreate(savedInstanceState
);
137 mHandler
= new Handler();
138 setHasOptionsMenu(true
);
143 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
144 Bundle savedInstanceState
) {
145 super.onCreateView(inflater
, container
, savedInstanceState
);
147 if (savedInstanceState
!= null
) {
148 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
149 mAccount
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
152 if(mFile
!= null
&& mAccount
!= null
) {
153 mLayout
= R
.layout
.file_details_fragment
;
157 view
= inflater
.inflate(mLayout
, container
, false
);
160 if (mLayout
== R
.layout
.file_details_fragment
) {
161 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
162 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
163 mProgressListener
= new ProgressListener(progressBar
);
164 mView
.findViewById(R
.id
.fdCancelBtn
).setOnClickListener(this);
167 updateFileDetails(false
, false
);
175 public void onAttach(Activity activity
) {
176 super.onAttach(activity
);
178 mContainerActivity
= (ContainerActivity
) activity
;
180 } catch (ClassCastException e
) {
181 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
190 public void onActivityCreated(Bundle savedInstanceState
) {
191 super.onActivityCreated(savedInstanceState
);
192 if (mAccount
!= null
) {
193 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
199 public void onSaveInstanceState(Bundle outState
) {
200 super.onSaveInstanceState(outState
);
201 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
202 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
206 public void onStart() {
208 listenForTransferProgress();
212 public void onResume() {
214 mUploadFinishReceiver
= new UploadFinishReceiver();
215 IntentFilter filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
216 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
222 public void onPause() {
224 if (mUploadFinishReceiver
!= null
) {
225 getActivity().unregisterReceiver(mUploadFinishReceiver
);
226 mUploadFinishReceiver
= null
;
232 public void onStop() {
234 leaveTransferProgress();
239 public View
getView() {
240 return super.getView() == null ? mView
: super.getView();
248 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
249 super.onCreateOptionsMenu(menu
, inflater
);
250 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
251 MenuItem item
= menu
.findItem(R
.id
.action_see_details
);
253 item
.setVisible(false
);
254 item
.setEnabled(false
);
263 public void onPrepareOptionsMenu (Menu menu
) {
264 super.onPrepareOptionsMenu(menu
);
266 List
<Integer
> toHide
= new ArrayList
<Integer
>();
267 List
<Integer
> toShow
= new ArrayList
<Integer
>();
269 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
270 boolean downloading
= downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
);
271 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
272 boolean uploading
= uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
);
274 if (downloading
|| uploading
) {
275 toHide
.add(R
.id
.action_download_file
);
276 toHide
.add(R
.id
.action_rename_file
);
277 toHide
.add(R
.id
.action_remove_file
);
278 toHide
.add(R
.id
.action_open_file_with
);
280 toHide
.add(R
.id
.action_cancel_download
);
281 toShow
.add(R
.id
.action_cancel_upload
);
283 toHide
.add(R
.id
.action_cancel_upload
);
284 toShow
.add(R
.id
.action_cancel_download
);
287 } else if (mFile
!= null
&& mFile
.isDown()) {
288 toHide
.add(R
.id
.action_download_file
);
289 toHide
.add(R
.id
.action_cancel_download
);
290 toHide
.add(R
.id
.action_cancel_upload
);
292 toShow
.add(R
.id
.action_rename_file
);
293 toShow
.add(R
.id
.action_remove_file
);
294 toShow
.add(R
.id
.action_open_file_with
);
295 toShow
.add(R
.id
.action_sync_file
);
297 } else if (mFile
!= null
) {
298 toHide
.add(R
.id
.action_open_file_with
);
299 toHide
.add(R
.id
.action_cancel_download
);
300 toHide
.add(R
.id
.action_cancel_upload
);
301 toHide
.add(R
.id
.action_sync_file
);
303 toShow
.add(R
.id
.action_rename_file
);
304 toShow
.add(R
.id
.action_remove_file
);
305 toShow
.add(R
.id
.action_download_file
);
308 toHide
.add(R
.id
.action_open_file_with
);
309 toHide
.add(R
.id
.action_cancel_download
);
310 toHide
.add(R
.id
.action_cancel_upload
);
311 toHide
.add(R
.id
.action_sync_file
);
312 toHide
.add(R
.id
.action_download_file
);
313 toHide
.add(R
.id
.action_rename_file
);
314 toHide
.add(R
.id
.action_remove_file
);
318 MenuItem item
= null
;
319 for (int i
: toHide
) {
320 item
= menu
.findItem(i
);
322 item
.setVisible(false
);
323 item
.setEnabled(false
);
326 for (int i
: toShow
) {
327 item
= menu
.findItem(i
);
329 item
.setVisible(true
);
330 item
.setEnabled(true
);
340 public boolean onOptionsItemSelected(MenuItem item
) {
341 switch (item
.getItemId()) {
342 case R
.id
.action_open_file_with
: {
343 mContainerActivity
.openFile(mFile
);
346 case R
.id
.action_remove_file
: {
350 case R
.id
.action_rename_file
: {
354 case R
.id
.action_download_file
:
355 case R
.id
.action_cancel_download
:
356 case R
.id
.action_cancel_upload
:
357 case R
.id
.action_sync_file
: {
367 public void onClick(View v
) {
369 case R
.id
.fdKeepInSync
: {
373 case R
.id
.fdCancelBtn
: {
378 Log_OC
.e(TAG
, "Incorrect view clicked!");
383 private void toggleKeepInSync() {
384 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
385 mFile
.setKeepInSync(cb
.isChecked());
386 mStorageManager
.saveFile(mFile
);
388 /// register the OCFile instance in the observer service to monitor local updates;
389 /// if necessary, the file is download
390 Intent intent
= new Intent(getActivity().getApplicationContext(),
391 FileObserverService
.class);
392 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
394 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
395 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
396 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
397 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
398 getActivity().startService(intent
);
400 if (mFile
.keepInSync()) {
401 synchronizeFile(); // force an immediate synchronization
406 private void removeFile() {
407 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
408 R
.string
.confirmation_remove_alert
,
409 new String
[]{mFile
.getFileName()},
410 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
411 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
412 R
.string
.common_cancel
);
413 confDialog
.setOnConfirmationListener(this);
414 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
418 private void renameFile() {
419 String fileName
= mFile
.getFileName();
420 int extensionStart
= mFile
.isDirectory() ?
-1 : fileName
.lastIndexOf(".");
421 int selectionEnd
= (extensionStart
>= 0) ? extensionStart
: fileName
.length();
422 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), fileName
, 0, selectionEnd
, this);
423 dialog
.show(getFragmentManager(), "nameeditdialog");
426 private void synchronizeFile() {
427 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
428 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
429 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
430 downloaderBinder
.cancel(mAccount
, mFile
);
431 if (mFile
.isDown()) {
434 setButtonsForRemote();
437 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
438 uploaderBinder
.cancel(mAccount
, mFile
);
439 if (!mFile
.fileExists()) {
440 // TODO make something better
441 if (getActivity() instanceof FileDisplayActivity
) {
443 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
444 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
445 transaction
.commit();
446 mContainerActivity
.onFileStateChanged();
448 getActivity().finish();
451 } else if (mFile
.isDown()) {
454 setButtonsForRemote();
458 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
459 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
462 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
463 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
469 public void onConfirmation(String callerTag
) {
470 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
471 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
472 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
475 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
477 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
478 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
484 public void onNeutral(String callerTag
) {
486 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
488 mFile
.setStoragePath(null
);
489 mStorageManager
.saveFile(mFile
);
490 updateFileDetails(mFile
, mAccount
);
495 public void onCancel(String callerTag
) {
496 Log_OC
.d(TAG
, "REMOVAL CANCELED");
501 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
503 * @return True when the fragment was created with the empty layout.
505 public boolean isEmpty() {
506 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
513 public OCFile
getFile(){
518 * Use this method to signal this Activity that it shall update its view.
520 * @param file : An {@link OCFile}
522 public void updateFileDetails(OCFile file
, Account ocAccount
) {
524 if (ocAccount
!= null
&& (
525 mStorageManager
== null
||
526 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
528 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
530 mAccount
= ocAccount
;
531 updateFileDetails(false
, false
);
535 * Updates the view with all relevant details about that file.
537 * TODO Remove parameter when the transferring state of files is kept in database.
539 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
541 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
542 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
543 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
545 * @param refresh If 'true', try to refresh the hold file from the database
547 public void updateFileDetails(boolean transferring
, boolean refresh
) {
551 if (refresh
&& mStorageManager
!= null
) {
552 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
556 setFilename(mFile
.getFileName());
557 setFiletype(mFile
.getMimetype());
558 setFilesize(mFile
.getFileLength());
559 if(ocVersionSupportsTimeCreated()){
560 setTimeCreated(mFile
.getCreationTimestamp());
563 setTimeModified(mFile
.getModificationTimestamp());
565 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
566 cb
.setChecked(mFile
.keepInSync());
568 // configure UI for depending upon local state of the file
569 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
570 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
571 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
572 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
573 setButtonsForTransferring();
575 } else if (mFile
.isDown()) {
580 // TODO load default preview image; when the local file is removed, the preview remains there
581 setButtonsForRemote();
584 getView().invalidate();
588 * Checks if the fragment is ready to show details of a OCFile
590 * @return 'True' when the fragment is ready to show details of a file
592 private boolean readyToShow() {
593 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
598 * Updates the filename in view
599 * @param filename to set
601 private void setFilename(String filename
) {
602 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
604 tv
.setText(filename
);
608 * Updates the MIME type in view
609 * @param mimetype to set
611 private void setFiletype(String mimetype
) {
612 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
614 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
615 tv
.setText(printableMimetype
);
617 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
619 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
624 * Updates the file size in view
625 * @param filesize in bytes to set
627 private void setFilesize(long filesize
) {
628 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
630 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
634 * Updates the time that the file was created in view
635 * @param milliseconds Unix time to set
637 private void setTimeCreated(long milliseconds
){
638 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
639 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
641 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
642 tv
.setVisibility(View
.VISIBLE
);
643 tvLabel
.setVisibility(View
.VISIBLE
);
648 * Updates the time that the file was last modified
649 * @param milliseconds Unix time to set
651 private void setTimeModified(long milliseconds
){
652 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
654 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
659 * Enables or disables buttons for a file being downloaded
661 private void setButtonsForTransferring() {
663 // let's protect the user from himself ;)
664 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
666 // show the progress bar for the transfer
667 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.VISIBLE
);
668 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
669 progressText
.setVisibility(View
.VISIBLE
);
670 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
671 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
672 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
673 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
674 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
675 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
681 * Enables or disables buttons for a file locally available
683 private void setButtonsForDown() {
685 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
687 // hides the progress bar
688 getView().findViewById(R
.id
.fdProgressBlock
).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 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
701 // hides the progress bar
702 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.GONE
);
703 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
704 progressText
.setVisibility(View
.GONE
);
710 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
711 * the time that the file was created. There is a chance that this will
712 * be fixed in future versions. Use this method to check if this version of
713 * ownCloud has this fix.
714 * @return True, if ownCloud the ownCloud version is supporting creation time
716 private boolean ocVersionSupportsTimeCreated(){
717 /*if(mAccount != null){
718 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
719 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
720 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
721 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
730 * Once the file upload has finished -> update view
732 * Being notified about the finish of an upload is necessary for the next sequence:
733 * 1. Upload a big file.
734 * 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
735 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
736 * 3. Click the file in the list to see its details.
737 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
739 private class UploadFinishReceiver
extends BroadcastReceiver
{
741 public void onReceive(Context context
, Intent intent
) {
742 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
744 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
745 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
746 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
747 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
748 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
751 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
753 if (renamedInUpload
) {
754 String newName
= (new File(uploadRemotePath
)).getName();
755 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
758 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
759 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
766 public void onDismiss(EditNameDialog dialog
) {
767 if (dialog
.getResult()) {
768 String newFilename
= dialog
.getNewFilename();
769 Log_OC
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
770 mLastRemoteOperation
= new RenameFileOperation( mFile
,
773 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
774 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
775 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
776 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
785 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
786 if (operation
.equals(mLastRemoteOperation
)) {
787 if (operation
instanceof RemoveFileOperation
) {
788 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
790 } else if (operation
instanceof RenameFileOperation
) {
791 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
793 } else if (operation
instanceof SynchronizeFileOperation
) {
794 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
800 private void onRemoveFileOperationFinish(RemoveFileOperation 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 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
807 if (inDisplayActivity
) {
809 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
810 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
811 transaction
.commit();
812 mContainerActivity
.onFileStateChanged();
814 getActivity().finish();
818 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
820 if (result
.isSslRecoverableException()) {
821 // TODO show the SSL warning dialog
826 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
827 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
828 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
830 if (result
.isSuccess()) {
831 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
832 mContainerActivity
.onFileStateChanged();
835 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
836 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
838 // TODO throw again the new rename dialog
840 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
842 if (result
.isSslRecoverableException()) {
843 // TODO show the SSL warning dialog
849 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
850 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
851 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
853 if (!result
.isSuccess()) {
854 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
855 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
856 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
857 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
861 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
865 if (mFile
.isDown()) {
869 setButtonsForRemote();
873 if (operation
.transferWasRequested()) {
874 setButtonsForTransferring();
875 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
876 // checking the service to see if the file is downloading results in FALSE
878 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
880 if (mFile
.isDown()) {
884 setButtonsForRemote();
891 public void listenForTransferProgress() {
892 if (mProgressListener
!= null
) {
893 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
894 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
896 if (mContainerActivity
.getFileUploaderBinder() != null
) {
897 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
903 public void leaveTransferProgress() {
904 if (mProgressListener
!= null
) {
905 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
906 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
908 if (mContainerActivity
.getFileUploaderBinder() != null
) {
909 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
917 * Helper class responsible for updating the progress bar shown for file uploading or downloading
919 * @author David A. Velasco
921 private class ProgressListener
implements OnDatatransferProgressListener
{
922 int mLastPercent
= 0;
923 WeakReference
<ProgressBar
> mProgressBar
= null
;
925 ProgressListener(ProgressBar progressBar
) {
926 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
930 public void onTransferProgress(long progressRate
) {
931 // old method, nothing here
935 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
936 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
937 if (percent
!= mLastPercent
) {
938 ProgressBar pb
= mProgressBar
.get();
940 pb
.setProgress(percent
);
944 mLastPercent
= percent
;
950 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
951 @SuppressWarnings("unused")
952 private class ShareRunnable implements Runnable {
953 private String mPath;
955 public ShareRunnable(String path) {
960 AccountManager am = AccountManager.get(getActivity());
961 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
962 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
963 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
965 Log_OC.d("share", "sharing for version " + ocv.toString());
967 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
968 String APPS_PATH = "/apps/files_sharing/";
969 String SHARE_PATH = "ajax/share.php";
971 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
973 final String WEBDAV_SCRIPT = "webdav.php";
974 final String WEBDAV_FILES_LOCATION = "/files/";
976 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
977 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
978 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
980 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
981 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
983 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
985 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
986 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
987 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
988 Log_OC.d("share", mPath+"");
989 formparams.add(new BasicNameValuePair("sources",mPath));
990 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
991 formparams.add(new BasicNameValuePair("permissions", "0"));
992 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
996 PropFindMethod find = new PropFindMethod(url+"/");
997 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
998 Log_OC.d("sharer", ""+ url+"/");
1000 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
1001 Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
1004 int status2 = wc.executeMethod(find);
1006 Log_OC.d("sharer", "propstatus "+status2);
1008 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
1009 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
1011 status2 = wc.executeMethod(get);
1013 Log_OC.d("sharer", "getstatus "+status2);
1014 Log_OC.d("sharer", "" + get.getResponseBodyAsString());
1016 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
1017 Log_OC.d("sharer", a.getName() + ":"+a.getValue());
1020 status = wc.executeMethod(post);
1021 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
1022 Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
1024 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
1025 Log_OC.d("sharer", a.getName() + ":"+a.getValue());
1027 String resp = post.getResponseBodyAsString();
1028 Log_OC.d("share", ""+post.getURI().toString());
1029 Log_OC.d("share", "returned status " + status);
1030 Log_OC.d("share", " " +resp);
1032 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
1036 JSONObject jsonObject = new JSONObject (resp);
1037 String jsonStatus = jsonObject.getString("status");
1038 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
1040 String token = jsonObject.getString("data");
1041 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
1042 Log_OC.d("Actions:shareFile ok", "url: " + uri);
1044 } catch (Exception e) {
1045 e.printStackTrace();
1048 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {