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
);
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 MenuItem item
= null
;
336 for (int i
: toHide
) {
337 item
= menu
.findItem(i
);
339 item
.setVisible(false
);
340 item
.setEnabled(false
);
343 for (int i
: toShow
) {
344 item
= menu
.findItem(i
);
346 item
.setVisible(true
);
347 item
.setEnabled(true
);
357 public boolean onOptionsItemSelected(MenuItem item
) {
358 switch (item
.getItemId()) {
359 case R
.id
.action_open_file_with
: {
363 case R
.id
.action_remove_file
: {
367 case R
.id
.action_rename_file
: {
371 case R
.id
.action_download_file
:
372 case R
.id
.action_cancel_download
:
373 case R
.id
.action_cancel_upload
:
374 case R
.id
.action_sync_file
: {
385 public void onClick(View v
) {
387 case R
.id
.fdKeepInSync
: {
391 case R
.id
.fdCancelBtn
: {
396 Log_OC
.e(TAG
, "Incorrect view clicked!");
401 private void toggleKeepInSync() {
402 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
403 mFile
.setKeepInSync(cb
.isChecked());
404 mStorageManager
.saveFile(mFile
);
406 /// register the OCFile instance in the observer service to monitor local updates;
407 /// if necessary, the file is download
408 Intent intent
= new Intent(getActivity().getApplicationContext(),
409 FileObserverService
.class);
410 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
412 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
413 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
414 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
415 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
416 getActivity().startService(intent
);
418 if (mFile
.keepInSync()) {
419 synchronizeFile(); // force an immediate synchronization
424 private void removeFile() {
425 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
426 R
.string
.confirmation_remove_alert
,
427 new String
[]{mFile
.getFileName()},
428 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
429 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
430 R
.string
.common_cancel
);
431 confDialog
.setOnConfirmationListener(this);
432 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
436 private void renameFile() {
437 String fileName
= mFile
.getFileName();
438 int extensionStart
= mFile
.isDirectory() ?
-1 : fileName
.lastIndexOf(".");
439 int selectionEnd
= (extensionStart
>= 0) ? extensionStart
: fileName
.length();
440 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), fileName
, 0, selectionEnd
, this);
441 dialog
.show(getFragmentManager(), "nameeditdialog");
444 private void synchronizeFile() {
445 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
446 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
447 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
448 downloaderBinder
.cancel(mAccount
, mFile
);
449 if (mFile
.isDown()) {
452 setButtonsForRemote();
455 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
456 uploaderBinder
.cancel(mAccount
, mFile
);
457 if (!mFile
.fileExists()) {
458 // TODO make something better
459 if (getActivity() instanceof FileDisplayActivity
) {
461 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
462 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
463 transaction
.commit();
464 mContainerActivity
.onFileStateChanged();
466 getActivity().finish();
469 } else if (mFile
.isDown()) {
472 setButtonsForRemote();
476 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
477 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
478 mLastRemoteOperation
.execute(wc
, this, mHandler
);
481 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
482 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
491 private void openFile() {
493 String storagePath
= mFile
.getStoragePath();
494 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
496 Intent i
= new Intent(Intent
.ACTION_VIEW
);
497 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
498 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
501 } catch (Throwable t
) {
502 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
503 boolean toastIt
= true
;
504 String mimeType
= "";
506 Intent i
= new Intent(Intent
.ACTION_VIEW
);
507 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
508 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
509 if (mimeType
!= null
) {
510 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
513 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
515 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
520 } catch (IndexOutOfBoundsException e
) {
521 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
523 } catch (ActivityNotFoundException e
) {
524 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
526 } catch (Throwable th
) {
527 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
531 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
540 public void onConfirmation(String callerTag
) {
541 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
542 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
543 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
546 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
547 mLastRemoteOperation
.execute(wc
, this, mHandler
);
549 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
550 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
556 public void onNeutral(String callerTag
) {
558 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
560 mFile
.setStoragePath(null
);
561 mStorageManager
.saveFile(mFile
);
562 updateFileDetails(mFile
, mAccount
);
567 public void onCancel(String callerTag
) {
568 Log
.d(TAG
, "REMOVAL CANCELED");
573 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
575 * @return True when the fragment was created with the empty layout.
577 public boolean isEmpty() {
578 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
585 public OCFile
getFile(){
590 * Use this method to signal this Activity that it shall update its view.
592 * @param file : An {@link OCFile}
594 public void updateFileDetails(OCFile file
, Account ocAccount
) {
596 if (ocAccount
!= null
&& (
597 mStorageManager
== null
||
598 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
600 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
602 mAccount
= ocAccount
;
603 updateFileDetails(false
, false
);
607 * Updates the view with all relevant details about that file.
609 * TODO Remove parameter when the transferring state of files is kept in database.
611 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
613 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
614 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
615 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
617 * @param refresh If 'true', try to refresh the hold file from the database
619 public void updateFileDetails(boolean transferring
, boolean refresh
) {
623 if (refresh
&& mStorageManager
!= null
) {
624 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
628 setFilename(mFile
.getFileName());
629 setFiletype(mFile
.getMimetype());
630 setFilesize(mFile
.getFileLength());
631 if(ocVersionSupportsTimeCreated()){
632 setTimeCreated(mFile
.getCreationTimestamp());
635 setTimeModified(mFile
.getModificationTimestamp());
637 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
638 cb
.setChecked(mFile
.keepInSync());
640 // configure UI for depending upon local state of the file
641 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
642 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
643 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
644 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
645 setButtonsForTransferring();
647 } else if (mFile
.isDown()) {
652 // TODO load default preview image; when the local file is removed, the preview remains there
653 setButtonsForRemote();
656 getView().invalidate();
661 * Checks if the fragment is ready to show details of a OCFile
663 * @return 'True' when the fragment is ready to show details of a file
665 private boolean readyToShow() {
666 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
671 * Updates the filename in view
672 * @param filename to set
674 private void setFilename(String filename
) {
675 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
677 tv
.setText(filename
);
681 * Updates the MIME type in view
682 * @param mimetype to set
684 private void setFiletype(String mimetype
) {
685 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
687 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
688 tv
.setText(printableMimetype
);
690 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
692 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
697 * Updates the file size in view
698 * @param filesize in bytes to set
700 private void setFilesize(long filesize
) {
701 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
703 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
707 * Updates the time that the file was created in view
708 * @param milliseconds Unix time to set
710 private void setTimeCreated(long milliseconds
){
711 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
712 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
714 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
715 tv
.setVisibility(View
.VISIBLE
);
716 tvLabel
.setVisibility(View
.VISIBLE
);
721 * Updates the time that the file was last modified
722 * @param milliseconds Unix time to set
724 private void setTimeModified(long milliseconds
){
725 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
727 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
732 * Enables or disables buttons for a file being downloaded
734 private void setButtonsForTransferring() {
736 // let's protect the user from himself ;)
737 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
739 // show the progress bar for the transfer
740 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.VISIBLE
);
741 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
742 progressText
.setVisibility(View
.VISIBLE
);
743 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
744 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
745 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
746 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
747 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
748 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
754 * Enables or disables buttons for a file locally available
756 private void setButtonsForDown() {
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
);
768 * Enables or disables buttons for a file not locally available
770 private void setButtonsForRemote() {
772 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
774 // hides the progress bar
775 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.GONE
);
776 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
777 progressText
.setVisibility(View
.GONE
);
783 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
784 * the time that the file was created. There is a chance that this will
785 * be fixed in future versions. Use this method to check if this version of
786 * ownCloud has this fix.
787 * @return True, if ownCloud the ownCloud version is supporting creation time
789 private boolean ocVersionSupportsTimeCreated(){
790 /*if(mAccount != null){
791 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
792 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
793 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
794 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
803 * Once the file upload has finished -> update view
805 * Being notified about the finish of an upload is necessary for the next sequence:
806 * 1. Upload a big file.
807 * 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
808 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
809 * 3. Click the file in the list to see its details.
810 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
812 private class UploadFinishReceiver
extends BroadcastReceiver
{
814 public void onReceive(Context context
, Intent intent
) {
815 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
817 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
818 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
819 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
820 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
821 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
824 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
826 if (renamedInUpload
) {
827 String newName
= (new File(uploadRemotePath
)).getName();
828 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
831 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
832 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
839 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
840 @SuppressWarnings("unused")
841 private class ShareRunnable
implements Runnable
{
842 private String mPath
;
844 public ShareRunnable(String path
) {
849 AccountManager am
= AccountManager
.get(getActivity());
850 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
851 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
852 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
854 Log
.d("share", "sharing for version " + ocv
.toString());
856 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
857 String APPS_PATH
= "/apps/files_sharing/";
858 String SHARE_PATH
= "ajax/share.php";
860 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
862 final String WEBDAV_SCRIPT
= "webdav.php";
863 final String WEBDAV_FILES_LOCATION
= "/files/";
865 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
866 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
867 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
869 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
870 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
872 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
874 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
875 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
876 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
877 Log
.d("share", mPath
+"");
878 formparams
.add(new BasicNameValuePair("sources",mPath
));
879 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
880 formparams
.add(new BasicNameValuePair("permissions", "0"));
881 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
885 PropFindMethod find
= new PropFindMethod(url
+"/");
886 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
887 Log
.d("sharer", ""+ url
+"/");
889 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
890 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
893 int status2
= wc
.executeMethod(find
);
895 Log
.d("sharer", "propstatus "+status2
);
897 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
898 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
900 status2
= wc
.executeMethod(get
);
902 Log
.d("sharer", "getstatus "+status2
);
903 Log
.d("sharer", "" + get
.getResponseBodyAsString());
905 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
906 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
909 status
= wc
.executeMethod(post
);
910 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
911 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
913 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
914 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
916 String resp
= post
.getResponseBodyAsString();
917 Log
.d("share", ""+post
.getURI().toString());
918 Log
.d("share", "returned status " + status
);
919 Log
.d("share", " " +resp
);
921 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
925 JSONObject jsonObject
= new JSONObject (resp
);
926 String jsonStatus
= jsonObject
.getString("status");
927 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
929 String token
= jsonObject
.getString("data");
930 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
931 Log
.d("Actions:shareFile ok", "url: " + uri
);
933 } catch (Exception e
) {
937 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
943 public void onDismiss(EditNameDialog dialog
) {
944 if (dialog
.getResult()) {
945 String newFilename
= dialog
.getNewFilename();
946 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
947 mLastRemoteOperation
= new RenameFileOperation( mFile
,
950 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
951 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
952 mLastRemoteOperation
.execute(wc
, this, mHandler
);
953 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
954 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
963 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
964 if (operation
.equals(mLastRemoteOperation
)) {
965 if (operation
instanceof RemoveFileOperation
) {
966 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
968 } else if (operation
instanceof RenameFileOperation
) {
969 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
971 } else if (operation
instanceof SynchronizeFileOperation
) {
972 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
978 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
979 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
980 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
982 if (result
.isSuccess()) {
983 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
985 if (inDisplayActivity
) {
987 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
988 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
989 transaction
.commit();
990 mContainerActivity
.onFileStateChanged();
992 getActivity().finish();
996 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
998 if (result
.isSslRecoverableException()) {
999 // TODO show the SSL warning dialog
1004 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1005 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1006 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1008 if (result
.isSuccess()) {
1009 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
1010 mContainerActivity
.onFileStateChanged();
1013 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1014 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1016 // TODO throw again the new rename dialog
1018 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1020 if (result
.isSslRecoverableException()) {
1021 // TODO show the SSL warning dialog
1027 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1028 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1029 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1031 if (!result
.isSuccess()) {
1032 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1033 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1034 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1035 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1039 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1043 if (mFile
.isDown()) {
1044 setButtonsForDown();
1047 setButtonsForRemote();
1051 if (operation
.transferWasRequested()) {
1052 setButtonsForTransferring();
1053 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1054 // checking the service to see if the file is downloading results in FALSE
1056 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1058 if (mFile
.isDown()) {
1059 setButtonsForDown();
1062 setButtonsForRemote();
1069 public void listenForTransferProgress() {
1070 if (mProgressListener
!= null
) {
1071 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1072 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1074 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1075 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1081 public void leaveTransferProgress() {
1082 if (mProgressListener
!= null
) {
1083 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1084 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1086 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1087 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1095 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1097 * @author David A. Velasco
1099 private class ProgressListener
implements OnDatatransferProgressListener
{
1100 int mLastPercent
= 0;
1101 WeakReference
<ProgressBar
> mProgressBar
= null
;
1103 ProgressListener(ProgressBar progressBar
) {
1104 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
1108 public void onTransferProgress(long progressRate
) {
1109 // old method, nothing here
1113 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
1114 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
1115 if (percent
!= mLastPercent
) {
1116 ProgressBar pb
= mProgressBar
.get();
1118 pb
.setProgress(percent
);
1119 pb
.postInvalidate();
1122 mLastPercent
= percent
;