1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
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
.util
.ArrayList
;
22 import java
.util
.List
;
24 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
25 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
26 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
27 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
28 import org
.apache
.http
.HttpStatus
;
29 import org
.apache
.http
.NameValuePair
;
30 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
31 import org
.apache
.http
.message
.BasicNameValuePair
;
32 import org
.apache
.http
.protocol
.HTTP
;
33 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
34 import org
.json
.JSONObject
;
36 import android
.accounts
.Account
;
37 import android
.accounts
.AccountManager
;
38 import android
.annotation
.SuppressLint
;
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
.graphics
.Bitmap
;
46 import android
.graphics
.BitmapFactory
;
47 import android
.graphics
.BitmapFactory
.Options
;
48 import android
.graphics
.Point
;
49 import android
.net
.Uri
;
50 import android
.os
.AsyncTask
;
51 import android
.os
.Bundle
;
52 import android
.os
.Handler
;
53 import android
.support
.v4
.app
.FragmentTransaction
;
54 import android
.util
.Log
;
55 import android
.view
.Display
;
56 import android
.view
.LayoutInflater
;
57 import android
.view
.View
;
58 import android
.view
.View
.OnClickListener
;
59 import android
.view
.ViewGroup
;
60 import android
.webkit
.MimeTypeMap
;
61 import android
.widget
.Button
;
62 import android
.widget
.CheckBox
;
63 import android
.widget
.ImageView
;
64 import android
.widget
.TextView
;
65 import android
.widget
.Toast
;
67 import com
.actionbarsherlock
.app
.SherlockFragment
;
68 import com
.owncloud
.android
.AccountUtils
;
69 import com
.owncloud
.android
.DisplayUtils
;
70 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
71 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
72 import com
.owncloud
.android
.datamodel
.OCFile
;
73 import com
.owncloud
.android
.files
.services
.FileDownloader
;
74 import com
.owncloud
.android
.files
.services
.FileObserverService
;
75 import com
.owncloud
.android
.files
.services
.FileUploader
;
76 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
77 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
78 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
79 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
80 import com
.owncloud
.android
.operations
.RemoteOperation
;
81 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
82 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
83 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RenameFileOperation
;
85 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
86 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
87 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
88 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
89 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
90 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
91 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
92 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
94 import com
.owncloud
.android
.R
;
95 import eu
.alefzero
.webdav
.WebdavClient
;
96 import eu
.alefzero
.webdav
.WebdavUtils
;
99 * This Fragment is used to display the details about a file.
101 * @author Bartek Przybylski
104 public class FileDetailFragment
extends SherlockFragment
implements
105 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
{
107 public static final String EXTRA_FILE
= "FILE";
108 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
110 private FileDetailFragment
.ContainerActivity mContainerActivity
;
114 private OCFile mFile
;
115 private Account mAccount
;
116 private ImageView mPreview
;
118 private DownloadFinishReceiver mDownloadFinishReceiver
;
119 private UploadFinishReceiver mUploadFinishReceiver
;
121 private Handler mHandler
;
122 private RemoteOperation mLastRemoteOperation
;
124 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
125 public static final String FTAG
= "FileDetails";
126 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
130 * Creates an empty details fragment.
132 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
134 public FileDetailFragment() {
137 mLayout
= R
.layout
.file_details_empty
;
142 * Creates a details fragment.
144 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
146 * @param fileToDetail An {@link OCFile} to show in the fragment
147 * @param ocAccount An ownCloud account; needed to start downloads
149 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
150 mFile
= fileToDetail
;
151 mAccount
= ocAccount
;
152 mLayout
= R
.layout
.file_details_empty
;
154 if(fileToDetail
!= null
&& ocAccount
!= null
) {
155 mLayout
= R
.layout
.file_details_fragment
;
161 public void onCreate(Bundle savedInstanceState
) {
162 super.onCreate(savedInstanceState
);
163 mHandler
= new Handler();
168 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
169 Bundle savedInstanceState
) {
170 super.onCreateView(inflater
, container
, savedInstanceState
);
172 if (savedInstanceState
!= null
) {
173 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
174 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
178 view
= inflater
.inflate(mLayout
, container
, false
);
181 if (mLayout
== R
.layout
.file_details_fragment
) {
182 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
183 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
184 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
185 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
186 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
187 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
188 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
200 public void onAttach(Activity activity
) {
201 super.onAttach(activity
);
203 mContainerActivity
= (ContainerActivity
) activity
;
204 } catch (ClassCastException e
) {
205 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
211 public void onSaveInstanceState(Bundle outState
) {
212 Log
.i(getClass().toString(), "onSaveInstanceState() start");
213 super.onSaveInstanceState(outState
);
214 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
215 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
216 Log
.i(getClass().toString(), "onSaveInstanceState() end");
221 public void onResume() {
224 mDownloadFinishReceiver
= new DownloadFinishReceiver();
225 IntentFilter filter
= new IntentFilter(
226 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
227 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
229 mUploadFinishReceiver
= new UploadFinishReceiver();
230 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
231 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
233 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
237 public void onPause() {
240 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
241 mDownloadFinishReceiver
= null
;
243 getActivity().unregisterReceiver(mUploadFinishReceiver
);
244 mUploadFinishReceiver
= null
;
246 if (mPreview
!= null
) {
252 public View
getView() {
253 return super.getView() == null ? mView
: super.getView();
259 public void onClick(View v
) {
260 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
262 case R
.id
.fdDownloadBtn
: {
263 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath())) {
264 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
265 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
266 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
267 downloaderBinder
.cancel(mAccount
, mFile
);
268 if (mFile
.isDown()) {
271 setButtonsForRemote();
274 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
275 uploaderBinder
.cancel(mAccount
, mFile
);
276 if (!mFile
.fileExists()) {
277 // TODO make something better
278 if (getActivity() instanceof FileDisplayActivity
) {
280 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
281 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
282 transaction
.commit();
283 mContainerActivity
.onFileStateChanged();
285 getActivity().finish();
288 } else if (mFile
.isDown()) {
291 setButtonsForRemote();
295 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
.getRemotePath(), fdsm
, mAccount
, true
, false
, getActivity());
296 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
297 mLastRemoteOperation
.execute(wc
, this, mHandler
);
300 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
301 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
302 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
307 case R
.id
.fdKeepInSync
: {
308 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
309 mFile
.setKeepInSync(cb
.isChecked());
310 fdsm
.saveFile(mFile
);
313 * now that FileObserverService is involved, the easiest way to coordinate it with the download service
314 * in every possible case is let the FileObserverService decide if the download should be started at
317 * see changes at FileObserverService#addObservedFile
319 if (mFile.keepInSync()) {
320 onClick(getView().findViewById(R.id.fdDownloadBtn));
322 mContainerActivity.onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)
325 /// register the OCFile instance in the observer service to monitor local updates;
326 /// if necessary, the file is download
327 Intent intent
= new Intent(getActivity().getApplicationContext(),
328 FileObserverService
.class);
329 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
331 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
332 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
333 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
334 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
335 Log
.e(TAG
, "starting observer service");
336 getActivity().startService(intent
);
338 mContainerActivity
.onFileStateChanged();
341 case R
.id
.fdRenameBtn
: {
342 EditNameDialog dialog
= EditNameDialog
.newInstance(mFile
.getFileName());
343 dialog
.setOnDismissListener(this);
344 dialog
.show(getFragmentManager(), "nameeditdialog");
347 case R
.id
.fdRemoveBtn
: {
348 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
349 R
.string
.confirmation_remove_alert
,
350 new String
[]{mFile
.getFileName()},
351 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
352 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
353 R
.string
.common_cancel
);
354 confDialog
.setOnConfirmationListener(this);
355 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
358 case R
.id
.fdOpenBtn
: {
359 String storagePath
= mFile
.getStoragePath();
360 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
362 Intent i
= new Intent(Intent
.ACTION_VIEW
);
363 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
364 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
367 } catch (Throwable t
) {
368 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
369 boolean toastIt
= true
;
370 String mimeType
= "";
372 Intent i
= new Intent(Intent
.ACTION_VIEW
);
373 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
374 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
375 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
376 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
381 } catch (IndexOutOfBoundsException e
) {
382 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
384 } catch (ActivityNotFoundException e
) {
385 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
387 } catch (Throwable th
) {
388 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
392 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
400 Log
.e(TAG
, "Incorrect view clicked!");
403 /* else if (v.getId() == R.id.fdShareBtn) {
404 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
411 public void onConfirmation(String callerTag
) {
412 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
413 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
414 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
415 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
417 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
418 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
419 mLastRemoteOperation
.execute(wc
, this, mHandler
);
421 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
422 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
428 public void onNeutral(String callerTag
) {
429 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
431 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
433 mFile
.setStoragePath(null
);
434 fdsm
.saveFile(mFile
);
435 updateFileDetails(mFile
, mAccount
);
440 public void onCancel(String callerTag
) {
441 Log
.d(TAG
, "REMOVAL CANCELED");
446 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
448 * @return True when the fragment was created with the empty layout.
450 public boolean isEmpty() {
451 return mLayout
== R
.layout
.file_details_empty
;
456 * Can be used to get the file that is currently being displayed.
457 * @return The file on the screen.
459 public OCFile
getDisplayedFile(){
464 * Use this method to signal this Activity that it shall update its view.
466 * @param file : An {@link OCFile}
468 public void updateFileDetails(OCFile file
, Account ocAccount
) {
470 mAccount
= ocAccount
;
476 * Updates the view with all relevant details about that file.
478 public void updateFileDetails() {
480 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
483 setFilename(mFile
.getFileName());
484 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
486 setFilesize(mFile
.getFileLength());
487 if(ocVersionSupportsTimeCreated()){
488 setTimeCreated(mFile
.getCreationTimestamp());
491 setTimeModified(mFile
.getModificationTimestamp());
493 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
494 cb
.setChecked(mFile
.keepInSync());
496 // configure UI for depending upon local state of the file
497 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
498 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
499 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
500 if ((downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
501 setButtonsForTransferring();
503 } else if (mFile
.isDown()) {
505 if (mFile
.getMimetype().startsWith("image/")) {
506 BitmapLoader bl
= new BitmapLoader();
507 bl
.execute(new String
[]{mFile
.getStoragePath()});
513 setButtonsForRemote();
520 * Updates the filename in view
521 * @param filename to set
523 private void setFilename(String filename
) {
524 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
526 tv
.setText(filename
);
530 * Updates the MIME type in view
531 * @param mimetype to set
533 private void setFiletype(String mimetype
) {
534 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
536 tv
.setText(mimetype
);
540 * Updates the file size in view
541 * @param filesize in bytes to set
543 private void setFilesize(long filesize
) {
544 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
546 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
550 * Updates the time that the file was created in view
551 * @param milliseconds Unix time to set
553 private void setTimeCreated(long milliseconds
){
554 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
555 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
557 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
558 tv
.setVisibility(View
.VISIBLE
);
559 tvLabel
.setVisibility(View
.VISIBLE
);
564 * Updates the time that the file was last modified
565 * @param milliseconds Unix time to set
567 private void setTimeModified(long milliseconds
){
568 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
570 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
575 * Enables or disables buttons for a file being downloaded
577 private void setButtonsForTransferring() {
579 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
580 downloadButton
.setText(R
.string
.common_cancel
);
581 //downloadButton.setEnabled(false);
583 // let's protect the user from himself ;)
584 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
585 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
586 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
587 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
592 * Enables or disables buttons for a file locally available
594 private void setButtonsForDown() {
596 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
597 downloadButton
.setText(R
.string
.filedetails_redownload
);
598 //downloadButton.setEnabled(true);
600 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
601 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
602 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
603 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
608 * Enables or disables buttons for a file not locally available
610 private void setButtonsForRemote() {
612 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
613 downloadButton
.setText(R
.string
.filedetails_download
);
615 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
616 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
617 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
618 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
624 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
625 * the time that the file was created. There is a chance that this will
626 * be fixed in future versions. Use this method to check if this version of
627 * ownCloud has this fix.
628 * @return True, if ownCloud the ownCloud version is supporting creation time
630 private boolean ocVersionSupportsTimeCreated(){
631 /*if(mAccount != null){
632 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
633 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
634 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
635 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
644 * Interface to implement by any Activity that includes some instance of FileDetailFragment
646 * @author David A. Velasco
648 public interface ContainerActivity
extends TransferServiceGetter
{
651 * Callback method invoked when the detail fragment wants to notice its container
652 * activity about a relevant state the file shown by the fragment.
654 * Added to notify to FileDisplayActivity about the need of refresh the files list.
656 * Currently called when:
657 * - a download is started;
658 * - a rename is completed;
659 * - a deletion is completed;
660 * - the 'inSync' flag is changed;
662 public void onFileStateChanged();
668 * Once the file download has finished -> update view
669 * @author Bartek Przybylski
671 private class DownloadFinishReceiver
extends BroadcastReceiver
{
673 public void onReceive(Context context
, Intent intent
) {
674 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
676 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
677 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
678 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
679 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
680 if (downloadWasFine
) {
681 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
)); // updates the local object without accessing the database again
683 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
691 * Once the file upload has finished -> update view
693 * Being notified about the finish of an upload is necessary for the next sequence:
694 * 1. Upload a big file.
695 * 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
696 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
697 * 3. Click the file in the list to see its details.
698 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
700 private class UploadFinishReceiver
extends BroadcastReceiver
{
702 public void onReceive(Context context
, Intent intent
) {
703 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
705 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
706 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
707 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
708 if (mFile
.getRemotePath().equals(uploadRemotePath
)) {
710 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
711 mFile
= fdsm
.getFileByPath(mFile
.getRemotePath());
713 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
720 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
721 @SuppressWarnings("unused")
722 private class ShareRunnable
implements Runnable
{
723 private String mPath
;
725 public ShareRunnable(String path
) {
730 AccountManager am
= AccountManager
.get(getActivity());
731 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
732 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
733 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
735 Log
.d("share", "sharing for version " + ocv
.toString());
737 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
738 String APPS_PATH
= "/apps/files_sharing/";
739 String SHARE_PATH
= "ajax/share.php";
741 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
743 final String WEBDAV_SCRIPT
= "webdav.php";
744 final String WEBDAV_FILES_LOCATION
= "/files/";
746 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
747 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
748 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
750 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
751 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
753 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
755 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
756 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
757 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
758 Log
.d("share", mPath
+"");
759 formparams
.add(new BasicNameValuePair("sources",mPath
));
760 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
761 formparams
.add(new BasicNameValuePair("permissions", "0"));
762 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
766 PropFindMethod find
= new PropFindMethod(url
+"/");
767 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
768 Log
.d("sharer", ""+ url
+"/");
770 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
771 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
774 int status2
= wc
.executeMethod(find
);
776 Log
.d("sharer", "propstatus "+status2
);
778 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
779 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
781 status2
= wc
.executeMethod(get
);
783 Log
.d("sharer", "getstatus "+status2
);
784 Log
.d("sharer", "" + get
.getResponseBodyAsString());
786 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
787 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
790 status
= wc
.executeMethod(post
);
791 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
792 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
794 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
795 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
797 String resp
= post
.getResponseBodyAsString();
798 Log
.d("share", ""+post
.getURI().toString());
799 Log
.d("share", "returned status " + status
);
800 Log
.d("share", " " +resp
);
802 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
806 JSONObject jsonObject
= new JSONObject (resp
);
807 String jsonStatus
= jsonObject
.getString("status");
808 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
810 String token
= jsonObject
.getString("data");
811 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
812 Log
.d("Actions:shareFile ok", "url: " + uri
);
814 } catch (Exception e
) {
818 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
824 public void onDismiss(EditNameDialog dialog
) {
825 if (dialog
.getResult()) {
826 String newFilename
= dialog
.getNewFilename();
827 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
828 mLastRemoteOperation
= new RenameFileOperation( mFile
,
830 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
831 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
832 mLastRemoteOperation
.execute(wc
, this, mHandler
);
833 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
834 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
839 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
840 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
842 protected Bitmap
doInBackground(String
... params
) {
843 Bitmap result
= null
;
844 if (params
.length
!= 1) return result
;
845 String storagePath
= params
[0];
848 BitmapFactory
.Options options
= new Options();
849 options
.inScaled
= true
;
850 options
.inPurgeable
= true
;
851 options
.inJustDecodeBounds
= true
;
852 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
853 options
.inPreferQualityOverSpeed
= false
;
855 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
856 options
.inMutable
= false
;
859 result
= BitmapFactory
.decodeFile(storagePath
, options
);
860 options
.inJustDecodeBounds
= false
;
862 int width
= options
.outWidth
;
863 int height
= options
.outHeight
;
865 if (width
>= 2048 || height
>= 2048) {
866 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
867 options
.inSampleSize
= scale
;
869 Display display
= getActivity().getWindowManager().getDefaultDisplay();
870 Point size
= new Point();
872 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
873 display
.getSize(size
);
874 screenwidth
= size
.x
;
876 screenwidth
= display
.getWidth();
879 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
881 if (width
> screenwidth
) {
882 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
883 options
.inSampleSize
= scale
;
886 result
= BitmapFactory
.decodeFile(storagePath
, options
);
888 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
890 } catch (OutOfMemoryError e
) {
892 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
894 } catch (NoSuchFieldError e
) {
896 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
898 } catch (Throwable t
) {
900 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
905 protected void onPostExecute(Bitmap result
) {
906 if (result
!= null
&& mPreview
!= null
) {
907 mPreview
.setImageBitmap(result
);
917 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
918 if (operation
.equals(mLastRemoteOperation
)) {
919 if (operation
instanceof RemoveFileOperation
) {
920 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
922 } else if (operation
instanceof RenameFileOperation
) {
923 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
925 } else if (operation
instanceof SynchronizeFileOperation
) {
926 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
932 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
933 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
934 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
936 if (result
.isSuccess()) {
937 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
939 if (inDisplayActivity
) {
941 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
942 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
943 transaction
.commit();
944 mContainerActivity
.onFileStateChanged();
946 getActivity().finish();
950 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
952 if (result
.isSslRecoverableException()) {
953 // TODO show the SSL warning dialog
958 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
959 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
960 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
962 if (result
.isSuccess()) {
963 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
964 mContainerActivity
.onFileStateChanged();
967 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
968 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
970 // TODO throw again the new rename dialog
972 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
974 if (result
.isSslRecoverableException()) {
975 // TODO show the SSL warning dialog
981 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
982 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
983 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
985 if (!result
.isSuccess()) {
986 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
987 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
988 //i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
989 i
.putExtra("remotepath", mFile
.getRemotePath());
990 i
.putExtra("localpath", mFile
.getStoragePath());
991 i
.putExtra("account", mAccount
);
995 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1000 if (operation
.transferWasRequested()) {
1001 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1002 // checking the service to see if the file is downloading results in FALSE
1004 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1006 if (mFile
.isDown()) {
1007 setButtonsForDown();
1010 setButtonsForRemote();