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 org
.apache
.commons
.httpclient
.methods
.GetMethod
;
26 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
27 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
28 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
29 import org
.apache
.http
.HttpStatus
;
30 import org
.apache
.http
.NameValuePair
;
31 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
32 import org
.apache
.http
.message
.BasicNameValuePair
;
33 import org
.apache
.http
.protocol
.HTTP
;
34 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
35 import org
.json
.JSONObject
;
37 import android
.accounts
.Account
;
38 import android
.accounts
.AccountManager
;
39 import android
.app
.Activity
;
40 import android
.content
.ActivityNotFoundException
;
41 import android
.content
.BroadcastReceiver
;
42 import android
.content
.Context
;
43 import android
.content
.Intent
;
44 import android
.content
.IntentFilter
;
45 import android
.net
.Uri
;
46 import android
.os
.Bundle
;
47 import android
.os
.Handler
;
48 import android
.support
.v4
.app
.FragmentTransaction
;
49 import android
.util
.Log
;
50 import android
.view
.LayoutInflater
;
51 import android
.view
.View
;
52 import android
.view
.View
.OnClickListener
;
53 import android
.view
.ViewGroup
;
54 import android
.webkit
.MimeTypeMap
;
55 import android
.widget
.CheckBox
;
56 import android
.widget
.ImageView
;
57 import android
.widget
.ProgressBar
;
58 import android
.widget
.TextView
;
59 import android
.widget
.Toast
;
61 import com
.actionbarsherlock
.app
.SherlockFragment
;
62 import com
.actionbarsherlock
.view
.Menu
;
63 import com
.actionbarsherlock
.view
.MenuInflater
;
64 import com
.actionbarsherlock
.view
.MenuItem
;
65 import com
.owncloud
.android
.AccountUtils
;
66 import com
.owncloud
.android
.DisplayUtils
;
67 import com
.owncloud
.android
.Log_OC
;
68 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
69 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
70 import com
.owncloud
.android
.datamodel
.OCFile
;
71 import com
.owncloud
.android
.files
.services
.FileObserverService
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
;
73 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
74 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
75 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
76 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
77 import com
.owncloud
.android
.operations
.RemoteOperation
;
78 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
79 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
80 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
81 import com
.owncloud
.android
.operations
.RenameFileOperation
;
82 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
83 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
84 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
85 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
86 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
87 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
88 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
90 import com
.owncloud
.android
.R
;
92 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
93 import eu
.alefzero
.webdav
.WebdavClient
;
94 import eu
.alefzero
.webdav
.WebdavUtils
;
98 * This Fragment is used to display the details about a file.
100 * @author Bartek Przybylski
101 * @author David A. Velasco
103 public class FileDetailFragment
extends SherlockFragment
implements
105 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
108 public static final String EXTRA_FILE
= "FILE";
109 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
111 private FileFragment
.ContainerActivity mContainerActivity
;
115 private OCFile mFile
;
116 private Account mAccount
;
117 private FileDataStorageManager mStorageManager
;
119 private UploadFinishReceiver mUploadFinishReceiver
;
120 public ProgressListener mProgressListener
;
122 private Handler mHandler
;
123 private RemoteOperation mLastRemoteOperation
;
125 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
126 public static final String FTAG
= "FileDetails";
127 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
131 * Creates an empty details fragment.
133 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
135 public FileDetailFragment() {
138 mStorageManager
= null
;
139 mLayout
= R
.layout
.file_details_empty
;
140 mProgressListener
= null
;
145 * Creates a details fragment.
147 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
149 * @param fileToDetail An {@link OCFile} to show in the fragment
150 * @param ocAccount An ownCloud account; needed to start downloads
152 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
153 mFile
= fileToDetail
;
154 mAccount
= ocAccount
;
155 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
156 mLayout
= R
.layout
.file_details_empty
;
157 mProgressListener
= null
;
162 public void onCreate(Bundle savedInstanceState
) {
163 super.onCreate(savedInstanceState
);
164 mHandler
= new Handler();
165 setHasOptionsMenu(true
);
170 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
171 Bundle savedInstanceState
) {
172 super.onCreateView(inflater
, container
, savedInstanceState
);
174 if (savedInstanceState
!= null
) {
175 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
176 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
179 if(mFile
!= null
&& mAccount
!= null
) {
180 mLayout
= R
.layout
.file_details_fragment
;
184 view
= inflater
.inflate(mLayout
, container
, false
);
187 if (mLayout
== R
.layout
.file_details_fragment
) {
188 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
189 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
190 mProgressListener
= new ProgressListener(progressBar
);
191 mView
.findViewById(R
.id
.fdCancelBtn
).setOnClickListener(this);
194 updateFileDetails(false
, false
);
202 public void onAttach(Activity activity
) {
203 super.onAttach(activity
);
205 mContainerActivity
= (ContainerActivity
) activity
;
207 } catch (ClassCastException e
) {
208 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
217 public void onActivityCreated(Bundle savedInstanceState
) {
218 super.onActivityCreated(savedInstanceState
);
219 if (mAccount
!= null
) {
220 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
226 public void onSaveInstanceState(Bundle outState
) {
227 super.onSaveInstanceState(outState
);
228 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
229 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
233 public void onStart() {
235 listenForTransferProgress();
239 public void onResume() {
241 mUploadFinishReceiver
= new UploadFinishReceiver();
242 IntentFilter filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
243 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
249 public void onPause() {
251 if (mUploadFinishReceiver
!= null
) {
252 getActivity().unregisterReceiver(mUploadFinishReceiver
);
253 mUploadFinishReceiver
= null
;
259 public void onStop() {
261 leaveTransferProgress();
266 public View
getView() {
267 return super.getView() == null ? mView
: super.getView();
275 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
276 super.onCreateOptionsMenu(menu
, inflater
);
277 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
278 MenuItem item
= menu
.findItem(R
.id
.action_see_details
);
280 item
.setVisible(false
);
281 item
.setEnabled(false
);
290 public void onPrepareOptionsMenu (Menu menu
) {
291 super.onPrepareOptionsMenu(menu
);
293 List
<Integer
> toHide
= new ArrayList
<Integer
>();
294 List
<Integer
> toShow
= new ArrayList
<Integer
>();
296 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
297 boolean downloading
= downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
);
298 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
299 boolean uploading
= uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
);
301 if (downloading
|| uploading
) {
302 toHide
.add(R
.id
.action_download_file
);
303 toHide
.add(R
.id
.action_rename_file
);
304 toHide
.add(R
.id
.action_remove_file
);
305 toHide
.add(R
.id
.action_open_file_with
);
307 toHide
.add(R
.id
.action_cancel_download
);
308 toShow
.add(R
.id
.action_cancel_upload
);
310 toHide
.add(R
.id
.action_cancel_upload
);
311 toShow
.add(R
.id
.action_cancel_download
);
314 } else if (mFile
!= null
&& mFile
.isDown()) {
315 toHide
.add(R
.id
.action_download_file
);
316 toHide
.add(R
.id
.action_cancel_download
);
317 toHide
.add(R
.id
.action_cancel_upload
);
319 toShow
.add(R
.id
.action_rename_file
);
320 toShow
.add(R
.id
.action_remove_file
);
321 toShow
.add(R
.id
.action_open_file_with
);
322 toShow
.add(R
.id
.action_sync_file
);
324 } else if (mFile
!= null
) {
325 toHide
.add(R
.id
.action_open_file_with
);
326 toHide
.add(R
.id
.action_cancel_download
);
327 toHide
.add(R
.id
.action_cancel_upload
);
328 toHide
.add(R
.id
.action_sync_file
);
330 toShow
.add(R
.id
.action_rename_file
);
331 toShow
.add(R
.id
.action_remove_file
);
332 toShow
.add(R
.id
.action_download_file
);
335 toHide
.add(R
.id
.action_open_file_with
);
336 toHide
.add(R
.id
.action_cancel_download
);
337 toHide
.add(R
.id
.action_cancel_upload
);
338 toHide
.add(R
.id
.action_sync_file
);
339 toHide
.add(R
.id
.action_download_file
);
340 toHide
.add(R
.id
.action_rename_file
);
341 toHide
.add(R
.id
.action_remove_file
);
345 MenuItem item
= null
;
346 for (int i
: toHide
) {
347 item
= menu
.findItem(i
);
349 item
.setVisible(false
);
350 item
.setEnabled(false
);
353 for (int i
: toShow
) {
354 item
= menu
.findItem(i
);
356 item
.setVisible(true
);
357 item
.setEnabled(true
);
367 public boolean onOptionsItemSelected(MenuItem item
) {
368 switch (item
.getItemId()) {
369 case R
.id
.action_open_file_with
: {
373 case R
.id
.action_remove_file
: {
377 case R
.id
.action_rename_file
: {
381 case R
.id
.action_download_file
:
382 case R
.id
.action_cancel_download
:
383 case R
.id
.action_cancel_upload
:
384 case R
.id
.action_sync_file
: {
395 public void onClick(View v
) {
397 case R
.id
.fdKeepInSync
: {
401 case R
.id
.fdCancelBtn
: {
406 Log_OC
.e(TAG
, "Incorrect view clicked!");
411 private void toggleKeepInSync() {
412 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
413 mFile
.setKeepInSync(cb
.isChecked());
414 mStorageManager
.saveFile(mFile
);
416 /// register the OCFile instance in the observer service to monitor local updates;
417 /// if necessary, the file is download
418 Intent intent
= new Intent(getActivity().getApplicationContext(),
419 FileObserverService
.class);
420 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
422 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
423 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
424 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
425 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
426 getActivity().startService(intent
);
428 if (mFile
.keepInSync()) {
429 synchronizeFile(); // force an immediate synchronization
434 private void removeFile() {
435 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
436 R
.string
.confirmation_remove_alert
,
437 new String
[]{mFile
.getFileName()},
438 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
439 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
440 R
.string
.common_cancel
);
441 confDialog
.setOnConfirmationListener(this);
442 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
446 private void renameFile() {
447 String fileName
= mFile
.getFileName();
448 int extensionStart
= mFile
.isDirectory() ?
-1 : fileName
.lastIndexOf(".");
449 int selectionEnd
= (extensionStart
>= 0) ? extensionStart
: fileName
.length();
450 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), fileName
, 0, selectionEnd
, this);
451 dialog
.show(getFragmentManager(), "nameeditdialog");
454 private void synchronizeFile() {
455 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
456 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
457 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
458 downloaderBinder
.cancel(mAccount
, mFile
);
459 if (mFile
.isDown()) {
462 setButtonsForRemote();
465 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
466 uploaderBinder
.cancel(mAccount
, mFile
);
467 if (!mFile
.fileExists()) {
468 // TODO make something better
469 if (getActivity() instanceof FileDisplayActivity
) {
471 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
472 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
473 transaction
.commit();
474 mContainerActivity
.onFileStateChanged();
476 getActivity().finish();
479 } else if (mFile
.isDown()) {
482 setButtonsForRemote();
486 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
487 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
488 mLastRemoteOperation
.execute(wc
, this, mHandler
);
491 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
492 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
501 private void openFile() {
503 String storagePath
= mFile
.getStoragePath();
504 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
506 Intent i
= new Intent(Intent
.ACTION_VIEW
);
507 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
508 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
511 } catch (Throwable t
) {
512 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
513 boolean toastIt
= true
;
514 String mimeType
= "";
516 Intent i
= new Intent(Intent
.ACTION_VIEW
);
517 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
518 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
519 if (mimeType
!= null
) {
520 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
523 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
525 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
530 } catch (IndexOutOfBoundsException e
) {
531 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
533 } catch (ActivityNotFoundException e
) {
534 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
536 } catch (Throwable th
) {
537 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
541 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
550 public void onConfirmation(String callerTag
) {
551 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
552 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
553 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
556 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
557 mLastRemoteOperation
.execute(wc
, this, mHandler
);
559 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
560 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
566 public void onNeutral(String callerTag
) {
568 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
570 mFile
.setStoragePath(null
);
571 mStorageManager
.saveFile(mFile
);
572 updateFileDetails(mFile
, mAccount
);
577 public void onCancel(String callerTag
) {
578 Log
.d(TAG
, "REMOVAL CANCELED");
583 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
585 * @return True when the fragment was created with the empty layout.
587 public boolean isEmpty() {
588 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
595 public OCFile
getFile(){
600 * Use this method to signal this Activity that it shall update its view.
602 * @param file : An {@link OCFile}
604 public void updateFileDetails(OCFile file
, Account ocAccount
) {
606 if (ocAccount
!= null
&& (
607 mStorageManager
== null
||
608 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
610 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
612 mAccount
= ocAccount
;
613 updateFileDetails(false
, false
);
617 * Updates the view with all relevant details about that file.
619 * TODO Remove parameter when the transferring state of files is kept in database.
621 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
623 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
624 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
625 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
627 * @param refresh If 'true', try to refresh the hold file from the database
629 public void updateFileDetails(boolean transferring
, boolean refresh
) {
633 if (refresh
&& mStorageManager
!= null
) {
634 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
638 setFilename(mFile
.getFileName());
639 setFiletype(mFile
.getMimetype());
640 setFilesize(mFile
.getFileLength());
641 if(ocVersionSupportsTimeCreated()){
642 setTimeCreated(mFile
.getCreationTimestamp());
645 setTimeModified(mFile
.getModificationTimestamp());
647 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
648 cb
.setChecked(mFile
.keepInSync());
650 // configure UI for depending upon local state of the file
651 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
652 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
653 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
654 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
655 setButtonsForTransferring();
657 } else if (mFile
.isDown()) {
662 // TODO load default preview image; when the local file is removed, the preview remains there
663 setButtonsForRemote();
666 getView().invalidate();
671 * Checks if the fragment is ready to show details of a OCFile
673 * @return 'True' when the fragment is ready to show details of a file
675 private boolean readyToShow() {
676 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
681 * Updates the filename in view
682 * @param filename to set
684 private void setFilename(String filename
) {
685 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
687 tv
.setText(filename
);
691 * Updates the MIME type in view
692 * @param mimetype to set
694 private void setFiletype(String mimetype
) {
695 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
697 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
698 tv
.setText(printableMimetype
);
700 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
702 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
707 * Updates the file size in view
708 * @param filesize in bytes to set
710 private void setFilesize(long filesize
) {
711 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
713 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
717 * Updates the time that the file was created in view
718 * @param milliseconds Unix time to set
720 private void setTimeCreated(long milliseconds
){
721 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
722 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
724 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
725 tv
.setVisibility(View
.VISIBLE
);
726 tvLabel
.setVisibility(View
.VISIBLE
);
731 * Updates the time that the file was last modified
732 * @param milliseconds Unix time to set
734 private void setTimeModified(long milliseconds
){
735 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
737 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
742 * Enables or disables buttons for a file being downloaded
744 private void setButtonsForTransferring() {
746 // let's protect the user from himself ;)
747 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
749 // show the progress bar for the transfer
750 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.VISIBLE
);
751 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
752 progressText
.setVisibility(View
.VISIBLE
);
753 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
754 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
755 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
756 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
757 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
758 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
764 * Enables or disables buttons for a file locally available
766 private void setButtonsForDown() {
768 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
770 // hides the progress bar
771 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.GONE
);
772 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
773 progressText
.setVisibility(View
.GONE
);
778 * Enables or disables buttons for a file not locally available
780 private void setButtonsForRemote() {
782 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
784 // hides the progress bar
785 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.GONE
);
786 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
787 progressText
.setVisibility(View
.GONE
);
793 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
794 * the time that the file was created. There is a chance that this will
795 * be fixed in future versions. Use this method to check if this version of
796 * ownCloud has this fix.
797 * @return True, if ownCloud the ownCloud version is supporting creation time
799 private boolean ocVersionSupportsTimeCreated(){
800 /*if(mAccount != null){
801 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
802 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
803 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
804 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
813 * Once the file upload has finished -> update view
815 * Being notified about the finish of an upload is necessary for the next sequence:
816 * 1. Upload a big file.
817 * 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
818 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
819 * 3. Click the file in the list to see its details.
820 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
822 private class UploadFinishReceiver
extends BroadcastReceiver
{
824 public void onReceive(Context context
, Intent intent
) {
825 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
827 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
828 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
829 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
830 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
831 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
834 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
836 if (renamedInUpload
) {
837 String newName
= (new File(uploadRemotePath
)).getName();
838 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
841 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
842 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
849 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
850 @SuppressWarnings("unused")
851 private class ShareRunnable
implements Runnable
{
852 private String mPath
;
854 public ShareRunnable(String path
) {
859 AccountManager am
= AccountManager
.get(getActivity());
860 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
861 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
862 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
864 Log
.d("share", "sharing for version " + ocv
.toString());
866 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
867 String APPS_PATH
= "/apps/files_sharing/";
868 String SHARE_PATH
= "ajax/share.php";
870 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
872 final String WEBDAV_SCRIPT
= "webdav.php";
873 final String WEBDAV_FILES_LOCATION
= "/files/";
875 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
876 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
877 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
879 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
880 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
882 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
884 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
885 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
886 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
887 Log
.d("share", mPath
+"");
888 formparams
.add(new BasicNameValuePair("sources",mPath
));
889 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
890 formparams
.add(new BasicNameValuePair("permissions", "0"));
891 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
895 PropFindMethod find
= new PropFindMethod(url
+"/");
896 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
897 Log
.d("sharer", ""+ url
+"/");
899 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
900 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
903 int status2
= wc
.executeMethod(find
);
905 Log
.d("sharer", "propstatus "+status2
);
907 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
908 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
910 status2
= wc
.executeMethod(get
);
912 Log
.d("sharer", "getstatus "+status2
);
913 Log
.d("sharer", "" + get
.getResponseBodyAsString());
915 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
916 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
919 status
= wc
.executeMethod(post
);
920 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
921 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
923 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
924 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
926 String resp
= post
.getResponseBodyAsString();
927 Log
.d("share", ""+post
.getURI().toString());
928 Log
.d("share", "returned status " + status
);
929 Log
.d("share", " " +resp
);
931 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
935 JSONObject jsonObject
= new JSONObject (resp
);
936 String jsonStatus
= jsonObject
.getString("status");
937 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
939 String token
= jsonObject
.getString("data");
940 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
941 Log
.d("Actions:shareFile ok", "url: " + uri
);
943 } catch (Exception e
) {
947 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
953 public void onDismiss(EditNameDialog dialog
) {
954 if (dialog
.getResult()) {
955 String newFilename
= dialog
.getNewFilename();
956 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
957 mLastRemoteOperation
= new RenameFileOperation( mFile
,
960 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
961 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
962 mLastRemoteOperation
.execute(wc
, this, mHandler
);
963 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
964 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
973 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
974 if (operation
.equals(mLastRemoteOperation
)) {
975 if (operation
instanceof RemoveFileOperation
) {
976 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
978 } else if (operation
instanceof RenameFileOperation
) {
979 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
981 } else if (operation
instanceof SynchronizeFileOperation
) {
982 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
988 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
989 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
990 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
992 if (result
.isSuccess()) {
993 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
995 if (inDisplayActivity
) {
997 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
998 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
999 transaction
.commit();
1000 mContainerActivity
.onFileStateChanged();
1002 getActivity().finish();
1006 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1008 if (result
.isSslRecoverableException()) {
1009 // TODO show the SSL warning dialog
1014 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1015 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1016 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1018 if (result
.isSuccess()) {
1019 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
1020 mContainerActivity
.onFileStateChanged();
1023 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1024 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1026 // TODO throw again the new rename dialog
1028 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1030 if (result
.isSslRecoverableException()) {
1031 // TODO show the SSL warning dialog
1037 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1038 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1039 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1041 if (!result
.isSuccess()) {
1042 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1043 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1044 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1045 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1049 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1053 if (mFile
.isDown()) {
1054 setButtonsForDown();
1057 setButtonsForRemote();
1061 if (operation
.transferWasRequested()) {
1062 setButtonsForTransferring();
1063 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1064 // checking the service to see if the file is downloading results in FALSE
1066 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1068 if (mFile
.isDown()) {
1069 setButtonsForDown();
1072 setButtonsForRemote();
1079 public void listenForTransferProgress() {
1080 if (mProgressListener
!= null
) {
1081 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1082 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1084 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1085 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1091 public void leaveTransferProgress() {
1092 if (mProgressListener
!= null
) {
1093 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1094 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1096 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1097 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1105 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1107 * @author David A. Velasco
1109 private class ProgressListener
implements OnDatatransferProgressListener
{
1110 int mLastPercent
= 0;
1111 WeakReference
<ProgressBar
> mProgressBar
= null
;
1113 ProgressListener(ProgressBar progressBar
) {
1114 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
1118 public void onTransferProgress(long progressRate
) {
1119 // old method, nothing here
1123 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
1124 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
1125 if (percent
!= mLastPercent
) {
1126 ProgressBar pb
= mProgressBar
.get();
1128 pb
.setProgress(percent
);
1129 pb
.postInvalidate();
1132 mLastPercent
= percent
;