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
.accounts
.AccountManager
;
27 import android
.app
.Activity
;
28 import android
.content
.ActivityNotFoundException
;
29 import android
.content
.BroadcastReceiver
;
30 import android
.content
.Context
;
31 import android
.content
.Intent
;
32 import android
.content
.IntentFilter
;
33 import android
.net
.Uri
;
34 import android
.os
.Bundle
;
35 import android
.os
.Handler
;
36 import android
.support
.v4
.app
.FragmentTransaction
;
37 import android
.view
.LayoutInflater
;
38 import android
.view
.View
;
39 import android
.view
.View
.OnClickListener
;
40 import android
.view
.ViewGroup
;
41 import android
.webkit
.MimeTypeMap
;
42 import android
.widget
.CheckBox
;
43 import android
.widget
.ImageView
;
44 import android
.widget
.ProgressBar
;
45 import android
.widget
.TextView
;
46 import android
.widget
.Toast
;
48 import com
.actionbarsherlock
.app
.SherlockFragment
;
49 import com
.actionbarsherlock
.view
.Menu
;
50 import com
.actionbarsherlock
.view
.MenuInflater
;
51 import com
.actionbarsherlock
.view
.MenuItem
;
52 import com
.owncloud
.android
.DisplayUtils
;
53 import com
.owncloud
.android
.Log_OC
;
54 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
55 import com
.owncloud
.android
.datamodel
.OCFile
;
56 import com
.owncloud
.android
.files
.services
.FileObserverService
;
57 import com
.owncloud
.android
.files
.services
.FileUploader
;
58 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
59 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
60 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
61 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
62 import com
.owncloud
.android
.operations
.RemoteOperation
;
63 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
64 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
65 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
66 import com
.owncloud
.android
.operations
.RenameFileOperation
;
67 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
68 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
69 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
70 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
71 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
72 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
74 import com
.owncloud
.android
.R
;
76 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
77 import eu
.alefzero
.webdav
.WebdavClient
;
78 import eu
.alefzero
.webdav
.WebdavUtils
;
81 * This Fragment is used to display the details about a file.
83 * @author Bartek Przybylski
84 * @author David A. Velasco
86 public class FileDetailFragment
extends SherlockFragment
implements
88 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
91 public static final String EXTRA_FILE
= "FILE";
92 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
94 private FileFragment
.ContainerActivity mContainerActivity
;
99 private Account mAccount
;
100 private FileDataStorageManager mStorageManager
;
102 private UploadFinishReceiver mUploadFinishReceiver
;
103 public ProgressListener mProgressListener
;
105 private Handler mHandler
;
106 private RemoteOperation mLastRemoteOperation
;
108 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
109 public static final String FTAG
= "FileDetails";
110 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
114 * Creates an empty details fragment.
116 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
118 public FileDetailFragment() {
121 mStorageManager
= null
;
122 mLayout
= R
.layout
.file_details_empty
;
123 mProgressListener
= null
;
127 * Creates a details fragment.
129 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
131 * @param fileToDetail An {@link OCFile} to show in the fragment
132 * @param ocAccount An ownCloud account; needed to start downloads
134 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
135 mFile
= fileToDetail
;
136 mAccount
= ocAccount
;
137 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
138 mLayout
= R
.layout
.file_details_empty
;
139 mProgressListener
= null
;
144 public void onCreate(Bundle savedInstanceState
) {
145 super.onCreate(savedInstanceState
);
146 mHandler
= new Handler();
147 setHasOptionsMenu(true
);
152 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
153 Bundle savedInstanceState
) {
154 super.onCreateView(inflater
, container
, savedInstanceState
);
156 if (savedInstanceState
!= null
) {
157 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
158 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
161 if(mFile
!= null
&& mAccount
!= null
) {
162 mLayout
= R
.layout
.file_details_fragment
;
166 view
= inflater
.inflate(mLayout
, container
, false
);
169 if (mLayout
== R
.layout
.file_details_fragment
) {
170 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
171 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
172 mProgressListener
= new ProgressListener(progressBar
);
173 mView
.findViewById(R
.id
.fdCancelBtn
).setOnClickListener(this);
176 updateFileDetails(false
, false
);
184 public void onAttach(Activity activity
) {
185 super.onAttach(activity
);
187 mContainerActivity
= (ContainerActivity
) activity
;
189 } catch (ClassCastException e
) {
190 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
199 public void onActivityCreated(Bundle savedInstanceState
) {
200 super.onActivityCreated(savedInstanceState
);
201 if (mAccount
!= null
) {
202 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
208 public void onSaveInstanceState(Bundle outState
) {
209 super.onSaveInstanceState(outState
);
210 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
211 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
215 public void onStart() {
217 listenForTransferProgress();
221 public void onResume() {
223 mUploadFinishReceiver
= new UploadFinishReceiver();
224 IntentFilter filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
225 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
231 public void onPause() {
233 if (mUploadFinishReceiver
!= null
) {
234 getActivity().unregisterReceiver(mUploadFinishReceiver
);
235 mUploadFinishReceiver
= null
;
241 public void onStop() {
243 leaveTransferProgress();
248 public View
getView() {
249 return super.getView() == null ? mView
: super.getView();
257 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
258 super.onCreateOptionsMenu(menu
, inflater
);
259 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
260 MenuItem item
= menu
.findItem(R
.id
.action_see_details
);
262 item
.setVisible(false
);
263 item
.setEnabled(false
);
272 public void onPrepareOptionsMenu (Menu menu
) {
273 super.onPrepareOptionsMenu(menu
);
275 List
<Integer
> toHide
= new ArrayList
<Integer
>();
276 List
<Integer
> toShow
= new ArrayList
<Integer
>();
278 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
279 boolean downloading
= downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
);
280 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
281 boolean uploading
= uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
);
283 if (downloading
|| uploading
) {
284 toHide
.add(R
.id
.action_download_file
);
285 toHide
.add(R
.id
.action_rename_file
);
286 toHide
.add(R
.id
.action_remove_file
);
287 toHide
.add(R
.id
.action_open_file_with
);
289 toHide
.add(R
.id
.action_cancel_download
);
290 toShow
.add(R
.id
.action_cancel_upload
);
292 toHide
.add(R
.id
.action_cancel_upload
);
293 toShow
.add(R
.id
.action_cancel_download
);
296 } else if (mFile
!= null
&& mFile
.isDown()) {
297 toHide
.add(R
.id
.action_download_file
);
298 toHide
.add(R
.id
.action_cancel_download
);
299 toHide
.add(R
.id
.action_cancel_upload
);
301 toShow
.add(R
.id
.action_rename_file
);
302 toShow
.add(R
.id
.action_remove_file
);
303 toShow
.add(R
.id
.action_open_file_with
);
304 toShow
.add(R
.id
.action_sync_file
);
306 } else if (mFile
!= null
) {
307 toHide
.add(R
.id
.action_open_file_with
);
308 toHide
.add(R
.id
.action_cancel_download
);
309 toHide
.add(R
.id
.action_cancel_upload
);
310 toHide
.add(R
.id
.action_sync_file
);
312 toShow
.add(R
.id
.action_rename_file
);
313 toShow
.add(R
.id
.action_remove_file
);
314 toShow
.add(R
.id
.action_download_file
);
317 toHide
.add(R
.id
.action_open_file_with
);
318 toHide
.add(R
.id
.action_cancel_download
);
319 toHide
.add(R
.id
.action_cancel_upload
);
320 toHide
.add(R
.id
.action_sync_file
);
321 toHide
.add(R
.id
.action_download_file
);
322 toHide
.add(R
.id
.action_rename_file
);
323 toHide
.add(R
.id
.action_remove_file
);
327 MenuItem item
= null
;
328 for (int i
: toHide
) {
329 item
= menu
.findItem(i
);
331 item
.setVisible(false
);
332 item
.setEnabled(false
);
335 for (int i
: toShow
) {
336 item
= menu
.findItem(i
);
338 item
.setVisible(true
);
339 item
.setEnabled(true
);
349 public boolean onOptionsItemSelected(MenuItem item
) {
350 switch (item
.getItemId()) {
351 case R
.id
.action_open_file_with
: {
355 case R
.id
.action_remove_file
: {
359 case R
.id
.action_rename_file
: {
363 case R
.id
.action_download_file
:
364 case R
.id
.action_cancel_download
:
365 case R
.id
.action_cancel_upload
:
366 case R
.id
.action_sync_file
: {
376 public void onClick(View v
) {
378 case R
.id
.fdKeepInSync
: {
382 case R
.id
.fdCancelBtn
: {
387 Log_OC
.e(TAG
, "Incorrect view clicked!");
392 private void toggleKeepInSync() {
393 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
394 mFile
.setKeepInSync(cb
.isChecked());
395 mStorageManager
.saveFile(mFile
);
397 /// register the OCFile instance in the observer service to monitor local updates;
398 /// if necessary, the file is download
399 Intent intent
= new Intent(getActivity().getApplicationContext(),
400 FileObserverService
.class);
401 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
403 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
404 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
405 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
406 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
407 getActivity().startService(intent
);
409 if (mFile
.keepInSync()) {
410 synchronizeFile(); // force an immediate synchronization
415 private void removeFile() {
416 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
417 R
.string
.confirmation_remove_alert
,
418 new String
[]{mFile
.getFileName()},
419 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
420 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
421 R
.string
.common_cancel
);
422 confDialog
.setOnConfirmationListener(this);
423 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
427 private void renameFile() {
428 String fileName
= mFile
.getFileName();
429 int extensionStart
= mFile
.isDirectory() ?
-1 : fileName
.lastIndexOf(".");
430 int selectionEnd
= (extensionStart
>= 0) ? extensionStart
: fileName
.length();
431 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), fileName
, 0, selectionEnd
, this);
432 dialog
.show(getFragmentManager(), "nameeditdialog");
435 private void synchronizeFile() {
436 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
437 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
438 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
439 downloaderBinder
.cancel(mAccount
, mFile
);
440 if (mFile
.isDown()) {
443 setButtonsForRemote();
446 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
447 uploaderBinder
.cancel(mAccount
, mFile
);
448 if (!mFile
.fileExists()) {
449 // TODO make something better
450 if (getActivity() instanceof FileDisplayActivity
) {
452 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
453 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
454 transaction
.commit();
455 mContainerActivity
.onFileStateChanged();
457 getActivity().finish();
460 } else if (mFile
.isDown()) {
463 setButtonsForRemote();
467 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
468 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
471 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
472 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
480 private void openFile() {
482 String storagePath
= mFile
.getStoragePath();
483 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
485 Intent i
= new Intent(Intent
.ACTION_VIEW
);
486 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
487 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
490 } catch (Throwable t
) {
491 Log_OC
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
492 boolean toastIt
= true
;
493 String mimeType
= "";
495 Intent i
= new Intent(Intent
.ACTION_VIEW
);
496 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
497 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
498 if (mimeType
!= null
) {
499 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
502 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
504 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
509 } catch (IndexOutOfBoundsException e
) {
510 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
512 } catch (ActivityNotFoundException e
) {
513 Log_OC
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
515 } catch (Throwable th
) {
516 Log_OC
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
520 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
528 public void onConfirmation(String callerTag
) {
529 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
530 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
531 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
534 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
536 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
537 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
543 public void onNeutral(String callerTag
) {
545 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
547 mFile
.setStoragePath(null
);
548 mStorageManager
.saveFile(mFile
);
549 updateFileDetails(mFile
, mAccount
);
554 public void onCancel(String callerTag
) {
555 Log_OC
.d(TAG
, "REMOVAL CANCELED");
560 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
562 * @return True when the fragment was created with the empty layout.
564 public boolean isEmpty() {
565 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
572 public OCFile
getFile(){
577 * Use this method to signal this Activity that it shall update its view.
579 * @param file : An {@link OCFile}
581 public void updateFileDetails(OCFile file
, Account ocAccount
) {
583 if (ocAccount
!= null
&& (
584 mStorageManager
== null
||
585 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
587 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
589 mAccount
= ocAccount
;
590 updateFileDetails(false
, false
);
594 * Updates the view with all relevant details about that file.
596 * TODO Remove parameter when the transferring state of files is kept in database.
598 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
600 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
601 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
602 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
604 * @param refresh If 'true', try to refresh the hold file from the database
606 public void updateFileDetails(boolean transferring
, boolean refresh
) {
610 if (refresh
&& mStorageManager
!= null
) {
611 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
615 setFilename(mFile
.getFileName());
616 setFiletype(mFile
.getMimetype());
617 setFilesize(mFile
.getFileLength());
618 if(ocVersionSupportsTimeCreated()){
619 setTimeCreated(mFile
.getCreationTimestamp());
622 setTimeModified(mFile
.getModificationTimestamp());
624 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
625 cb
.setChecked(mFile
.keepInSync());
627 // configure UI for depending upon local state of the file
628 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
629 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
630 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
631 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
632 setButtonsForTransferring();
634 } else if (mFile
.isDown()) {
639 // TODO load default preview image; when the local file is removed, the preview remains there
640 setButtonsForRemote();
643 getView().invalidate();
647 * Checks if the fragment is ready to show details of a OCFile
649 * @return 'True' when the fragment is ready to show details of a file
651 private boolean readyToShow() {
652 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
657 * Updates the filename in view
658 * @param filename to set
660 private void setFilename(String filename
) {
661 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
663 tv
.setText(filename
);
667 * Updates the MIME type in view
668 * @param mimetype to set
670 private void setFiletype(String mimetype
) {
671 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
673 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
674 tv
.setText(printableMimetype
);
676 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
678 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
683 * Updates the file size in view
684 * @param filesize in bytes to set
686 private void setFilesize(long filesize
) {
687 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
689 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
693 * Updates the time that the file was created in view
694 * @param milliseconds Unix time to set
696 private void setTimeCreated(long milliseconds
){
697 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
698 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
700 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
701 tv
.setVisibility(View
.VISIBLE
);
702 tvLabel
.setVisibility(View
.VISIBLE
);
707 * Updates the time that the file was last modified
708 * @param milliseconds Unix time to set
710 private void setTimeModified(long milliseconds
){
711 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
713 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
718 * Enables or disables buttons for a file being downloaded
720 private void setButtonsForTransferring() {
722 // let's protect the user from himself ;)
723 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
725 // show the progress bar for the transfer
726 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.VISIBLE
);
727 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
728 progressText
.setVisibility(View
.VISIBLE
);
729 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
730 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
731 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
732 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
733 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
734 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
740 * Enables or disables buttons for a file locally available
742 private void setButtonsForDown() {
744 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
746 // hides the progress bar
747 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.GONE
);
748 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
749 progressText
.setVisibility(View
.GONE
);
754 * Enables or disables buttons for a file not locally available
756 private void setButtonsForRemote() {
758 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
760 // hides the progress bar
761 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.GONE
);
762 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
763 progressText
.setVisibility(View
.GONE
);
769 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
770 * the time that the file was created. There is a chance that this will
771 * be fixed in future versions. Use this method to check if this version of
772 * ownCloud has this fix.
773 * @return True, if ownCloud the ownCloud version is supporting creation time
775 private boolean ocVersionSupportsTimeCreated(){
776 /*if(mAccount != null){
777 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
778 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
779 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
780 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
789 * Once the file upload has finished -> update view
791 * Being notified about the finish of an upload is necessary for the next sequence:
792 * 1. Upload a big file.
793 * 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
794 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
795 * 3. Click the file in the list to see its details.
796 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
798 private class UploadFinishReceiver
extends BroadcastReceiver
{
800 public void onReceive(Context context
, Intent intent
) {
801 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
803 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
804 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
805 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
806 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
807 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
810 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
812 if (renamedInUpload
) {
813 String newName
= (new File(uploadRemotePath
)).getName();
814 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
817 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
818 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
825 public void onDismiss(EditNameDialog dialog
) {
826 if (dialog
.getResult()) {
827 String newFilename
= dialog
.getNewFilename();
828 Log_OC
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
829 mLastRemoteOperation
= new RenameFileOperation( mFile
,
832 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
833 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
834 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
835 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
844 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
845 if (operation
.equals(mLastRemoteOperation
)) {
846 if (operation
instanceof RemoveFileOperation
) {
847 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
849 } else if (operation
instanceof RenameFileOperation
) {
850 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
852 } else if (operation
instanceof SynchronizeFileOperation
) {
853 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
859 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
860 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
861 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
863 if (result
.isSuccess()) {
864 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
866 if (inDisplayActivity
) {
868 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
869 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
870 transaction
.commit();
871 mContainerActivity
.onFileStateChanged();
873 getActivity().finish();
877 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
879 if (result
.isSslRecoverableException()) {
880 // TODO show the SSL warning dialog
885 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
886 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
887 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
889 if (result
.isSuccess()) {
890 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
891 mContainerActivity
.onFileStateChanged();
894 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
895 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
897 // TODO throw again the new rename dialog
899 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
901 if (result
.isSslRecoverableException()) {
902 // TODO show the SSL warning dialog
908 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
909 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
910 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
912 if (!result
.isSuccess()) {
913 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
914 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
915 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
916 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
920 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
924 if (mFile
.isDown()) {
928 setButtonsForRemote();
932 if (operation
.transferWasRequested()) {
933 setButtonsForTransferring();
934 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
935 // checking the service to see if the file is downloading results in FALSE
937 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
939 if (mFile
.isDown()) {
943 setButtonsForRemote();
950 public void listenForTransferProgress() {
951 if (mProgressListener
!= null
) {
952 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
953 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
955 if (mContainerActivity
.getFileUploaderBinder() != null
) {
956 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
962 public void leaveTransferProgress() {
963 if (mProgressListener
!= null
) {
964 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
965 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
967 if (mContainerActivity
.getFileUploaderBinder() != null
) {
968 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
976 * Helper class responsible for updating the progress bar shown for file uploading or downloading
978 * @author David A. Velasco
980 private class ProgressListener
implements OnDatatransferProgressListener
{
981 int mLastPercent
= 0;
982 WeakReference
<ProgressBar
> mProgressBar
= null
;
984 ProgressListener(ProgressBar progressBar
) {
985 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
989 public void onTransferProgress(long progressRate
) {
990 // old method, nothing here
994 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
995 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
996 if (percent
!= mLastPercent
) {
997 ProgressBar pb
= mProgressBar
.get();
999 pb
.setProgress(percent
);
1000 pb
.postInvalidate();
1003 mLastPercent
= percent
;
1009 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
1010 @SuppressWarnings("unused")
1011 private class ShareRunnable implements Runnable {
1012 private String mPath;
1014 public ShareRunnable(String path) {
1019 AccountManager am = AccountManager.get(getActivity());
1020 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
1021 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
1022 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
1024 Log_OC.d("share", "sharing for version " + ocv.toString());
1026 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
1027 String APPS_PATH = "/apps/files_sharing/";
1028 String SHARE_PATH = "ajax/share.php";
1030 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
1032 final String WEBDAV_SCRIPT = "webdav.php";
1033 final String WEBDAV_FILES_LOCATION = "/files/";
1035 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
1036 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
1037 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
1039 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
1040 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
1042 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
1044 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
1045 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
1046 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
1047 Log_OC.d("share", mPath+"");
1048 formparams.add(new BasicNameValuePair("sources",mPath));
1049 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
1050 formparams.add(new BasicNameValuePair("permissions", "0"));
1051 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
1055 PropFindMethod find = new PropFindMethod(url+"/");
1056 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
1057 Log_OC.d("sharer", ""+ url+"/");
1059 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
1060 Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
1063 int status2 = wc.executeMethod(find);
1065 Log_OC.d("sharer", "propstatus "+status2);
1067 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
1068 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
1070 status2 = wc.executeMethod(get);
1072 Log_OC.d("sharer", "getstatus "+status2);
1073 Log_OC.d("sharer", "" + get.getResponseBodyAsString());
1075 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
1076 Log_OC.d("sharer", a.getName() + ":"+a.getValue());
1079 status = wc.executeMethod(post);
1080 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
1081 Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
1083 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
1084 Log_OC.d("sharer", a.getName() + ":"+a.getValue());
1086 String resp = post.getResponseBodyAsString();
1087 Log_OC.d("share", ""+post.getURI().toString());
1088 Log_OC.d("share", "returned status " + status);
1089 Log_OC.d("share", " " +resp);
1091 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
1095 JSONObject jsonObject = new JSONObject (resp);
1096 String jsonStatus = jsonObject.getString("status");
1097 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
1099 String token = jsonObject.getString("data");
1100 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
1101 Log_OC.d("Actions:shareFile ok", "url: " + uri);
1103 } catch (Exception e) {
1104 e.printStackTrace();
1107 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {