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 FileDataStorageManager mStorageManager
;
117 private ImageView mPreview
;
119 private DownloadFinishReceiver mDownloadFinishReceiver
;
120 private UploadFinishReceiver mUploadFinishReceiver
;
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
;
144 * Creates a details fragment.
146 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
148 * @param fileToDetail An {@link OCFile} to show in the fragment
149 * @param ocAccount An ownCloud account; needed to start downloads
151 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
152 mFile
= fileToDetail
;
153 mAccount
= ocAccount
;
154 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
155 mLayout
= R
.layout
.file_details_empty
;
157 if(fileToDetail
!= null
&& ocAccount
!= null
) {
158 mLayout
= R
.layout
.file_details_fragment
;
164 public void onCreate(Bundle savedInstanceState
) {
165 super.onCreate(savedInstanceState
);
166 mHandler
= new Handler();
171 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
172 Bundle savedInstanceState
) {
173 super.onCreateView(inflater
, container
, savedInstanceState
);
175 if (savedInstanceState
!= null
) {
176 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
177 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
181 view
= inflater
.inflate(mLayout
, container
, false
);
184 if (mLayout
== R
.layout
.file_details_fragment
) {
185 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
186 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
187 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
188 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
189 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
190 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
191 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
194 updateFileDetails(false
);
203 public void onAttach(Activity activity
) {
204 super.onAttach(activity
);
206 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 Log
.i(getClass().toString(), "onSaveInstanceState() start");
228 super.onSaveInstanceState(outState
);
229 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
230 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
231 Log
.i(getClass().toString(), "onSaveInstanceState() end");
236 public void onResume() {
239 mDownloadFinishReceiver
= new DownloadFinishReceiver();
240 IntentFilter filter
= new IntentFilter(
241 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
242 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
244 mUploadFinishReceiver
= new UploadFinishReceiver();
245 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
246 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
248 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
252 public void onPause() {
255 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
256 mDownloadFinishReceiver
= null
;
258 getActivity().unregisterReceiver(mUploadFinishReceiver
);
259 mUploadFinishReceiver
= null
;
261 if (mPreview
!= null
) {
267 public View
getView() {
268 return super.getView() == null ? mView
: super.getView();
274 public void onClick(View v
) {
276 case R
.id
.fdDownloadBtn
: {
277 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
278 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
279 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
280 downloaderBinder
.cancel(mAccount
, mFile
);
281 if (mFile
.isDown()) {
284 setButtonsForRemote();
287 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
288 uploaderBinder
.cancel(mAccount
, mFile
);
289 if (!mFile
.fileExists()) {
290 // TODO make something better
291 if (getActivity() instanceof FileDisplayActivity
) {
293 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
294 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
295 transaction
.commit();
296 mContainerActivity
.onFileStateChanged();
298 getActivity().finish();
301 } else if (mFile
.isDown()) {
304 setButtonsForRemote();
308 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
309 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
310 mLastRemoteOperation
.execute(wc
, this, mHandler
);
313 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
314 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
315 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
320 case R
.id
.fdKeepInSync
: {
321 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
322 mFile
.setKeepInSync(cb
.isChecked());
323 mStorageManager
.saveFile(mFile
);
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 if (mFile
.keepInSync()) {
339 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
343 case R
.id
.fdRenameBtn
: {
344 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
345 dialog
.show(getFragmentManager(), "nameeditdialog");
348 case R
.id
.fdRemoveBtn
: {
349 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
350 R
.string
.confirmation_remove_alert
,
351 new String
[]{mFile
.getFileName()},
352 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
353 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
354 R
.string
.common_cancel
);
355 confDialog
.setOnConfirmationListener(this);
356 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
359 case R
.id
.fdOpenBtn
: {
360 String storagePath
= mFile
.getStoragePath();
361 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
363 Intent i
= new Intent(Intent
.ACTION_VIEW
);
364 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
365 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
368 } catch (Throwable t
) {
369 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
370 boolean toastIt
= true
;
371 String mimeType
= "";
373 Intent i
= new Intent(Intent
.ACTION_VIEW
);
374 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
375 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
376 if (mimeType
!= null
) {
377 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
380 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
382 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
387 } catch (IndexOutOfBoundsException e
) {
388 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
390 } catch (ActivityNotFoundException e
) {
391 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
393 } catch (Throwable th
) {
394 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
398 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
406 Log
.e(TAG
, "Incorrect view clicked!");
409 /* else if (v.getId() == R.id.fdShareBtn) {
410 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
417 public void onConfirmation(String callerTag
) {
418 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
419 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
420 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
423 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
424 mLastRemoteOperation
.execute(wc
, this, mHandler
);
426 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
427 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
433 public void onNeutral(String callerTag
) {
435 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
437 mFile
.setStoragePath(null
);
438 mStorageManager
.saveFile(mFile
);
439 updateFileDetails(mFile
, mAccount
);
444 public void onCancel(String callerTag
) {
445 Log
.d(TAG
, "REMOVAL CANCELED");
450 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
452 * @return True when the fragment was created with the empty layout.
454 public boolean isEmpty() {
455 return mLayout
== R
.layout
.file_details_empty
;
460 * Can be used to get the file that is currently being displayed.
461 * @return The file on the screen.
463 public OCFile
getDisplayedFile(){
468 * Use this method to signal this Activity that it shall update its view.
470 * @param file : An {@link OCFile}
472 public void updateFileDetails(OCFile file
, Account ocAccount
) {
474 if (ocAccount
!= null
&& (
475 mStorageManager
== null
||
476 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
478 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
480 mAccount
= ocAccount
;
481 updateFileDetails(false
);
486 * Updates the view with all relevant details about that file.
488 * TODO Remove parameter when the transferring state of files is kept in database.
490 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
491 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
492 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
495 public void updateFileDetails(boolean transferring
) {
497 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
500 setFilename(mFile
.getFileName());
501 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
503 setFilesize(mFile
.getFileLength());
504 if(ocVersionSupportsTimeCreated()){
505 setTimeCreated(mFile
.getCreationTimestamp());
508 setTimeModified(mFile
.getModificationTimestamp());
510 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
511 cb
.setChecked(mFile
.keepInSync());
513 // configure UI for depending upon local state of the file
514 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
515 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
516 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
517 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
518 setButtonsForTransferring();
520 } else if (mFile
.isDown()) {
522 if (mFile
.getMimetype().startsWith("image/")) {
523 BitmapLoader bl
= new BitmapLoader();
524 bl
.execute(new String
[]{mFile
.getStoragePath()});
530 // TODO load default preview image; when the local file is removed, the preview remains there
531 setButtonsForRemote();
534 getView().invalidate();
539 * Updates the filename in view
540 * @param filename to set
542 private void setFilename(String filename
) {
543 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
545 tv
.setText(filename
);
549 * Updates the MIME type in view
550 * @param mimetype to set
552 private void setFiletype(String mimetype
) {
553 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
555 tv
.setText(mimetype
);
559 * Updates the file size in view
560 * @param filesize in bytes to set
562 private void setFilesize(long filesize
) {
563 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
565 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
569 * Updates the time that the file was created in view
570 * @param milliseconds Unix time to set
572 private void setTimeCreated(long milliseconds
){
573 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
574 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
576 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
577 tv
.setVisibility(View
.VISIBLE
);
578 tvLabel
.setVisibility(View
.VISIBLE
);
583 * Updates the time that the file was last modified
584 * @param milliseconds Unix time to set
586 private void setTimeModified(long milliseconds
){
587 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
589 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
594 * Enables or disables buttons for a file being downloaded
596 private void setButtonsForTransferring() {
598 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
599 downloadButton
.setText(R
.string
.common_cancel
);
600 //downloadButton.setEnabled(false);
602 // let's protect the user from himself ;)
603 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
604 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
605 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
606 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
611 * Enables or disables buttons for a file locally available
613 private void setButtonsForDown() {
615 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
616 downloadButton
.setText(R
.string
.filedetails_sync_file
);
618 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
619 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
620 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
621 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
626 * Enables or disables buttons for a file not locally available
628 private void setButtonsForRemote() {
630 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
631 downloadButton
.setText(R
.string
.filedetails_download
);
633 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
634 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
635 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
636 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
642 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
643 * the time that the file was created. There is a chance that this will
644 * be fixed in future versions. Use this method to check if this version of
645 * ownCloud has this fix.
646 * @return True, if ownCloud the ownCloud version is supporting creation time
648 private boolean ocVersionSupportsTimeCreated(){
649 /*if(mAccount != null){
650 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
651 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
652 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
653 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
662 * Interface to implement by any Activity that includes some instance of FileDetailFragment
664 * @author David A. Velasco
666 public interface ContainerActivity
extends TransferServiceGetter
{
669 * Callback method invoked when the detail fragment wants to notice its container
670 * activity about a relevant state the file shown by the fragment.
672 * Added to notify to FileDisplayActivity about the need of refresh the files list.
674 * Currently called when:
675 * - a download is started;
676 * - a rename is completed;
677 * - a deletion is completed;
678 * - the 'inSync' flag is changed;
680 public void onFileStateChanged();
686 * Once the file download has finished -> update view
687 * @author Bartek Przybylski
689 private class DownloadFinishReceiver
extends BroadcastReceiver
{
691 public void onReceive(Context context
, Intent intent
) {
692 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
694 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
695 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
696 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
697 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
698 if (downloadWasFine
) {
699 mFile
= mStorageManager
.getFileByPath(downloadedRemotePath
);
701 updateFileDetails(false
); // it updates the buttons; must be called although !downloadWasFine
709 * Once the file upload has finished -> update view
711 * Being notified about the finish of an upload is necessary for the next sequence:
712 * 1. Upload a big file.
713 * 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
714 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
715 * 3. Click the file in the list to see its details.
716 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
718 private class UploadFinishReceiver
extends BroadcastReceiver
{
720 public void onReceive(Context context
, Intent intent
) {
721 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
723 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
724 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
725 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
726 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
727 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
730 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
732 if (renamedInUpload
) {
733 String newName
= (new File(uploadRemotePath
)).getName();
734 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
737 updateFileDetails(false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
744 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
745 @SuppressWarnings("unused")
746 private class ShareRunnable
implements Runnable
{
747 private String mPath
;
749 public ShareRunnable(String path
) {
754 AccountManager am
= AccountManager
.get(getActivity());
755 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
756 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
757 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
759 Log
.d("share", "sharing for version " + ocv
.toString());
761 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
762 String APPS_PATH
= "/apps/files_sharing/";
763 String SHARE_PATH
= "ajax/share.php";
765 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
767 final String WEBDAV_SCRIPT
= "webdav.php";
768 final String WEBDAV_FILES_LOCATION
= "/files/";
770 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
771 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
772 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
774 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
775 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
777 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
779 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
780 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
781 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
782 Log
.d("share", mPath
+"");
783 formparams
.add(new BasicNameValuePair("sources",mPath
));
784 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
785 formparams
.add(new BasicNameValuePair("permissions", "0"));
786 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
790 PropFindMethod find
= new PropFindMethod(url
+"/");
791 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
792 Log
.d("sharer", ""+ url
+"/");
794 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
795 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
798 int status2
= wc
.executeMethod(find
);
800 Log
.d("sharer", "propstatus "+status2
);
802 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
803 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
805 status2
= wc
.executeMethod(get
);
807 Log
.d("sharer", "getstatus "+status2
);
808 Log
.d("sharer", "" + get
.getResponseBodyAsString());
810 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
811 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
814 status
= wc
.executeMethod(post
);
815 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
816 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
818 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
819 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
821 String resp
= post
.getResponseBodyAsString();
822 Log
.d("share", ""+post
.getURI().toString());
823 Log
.d("share", "returned status " + status
);
824 Log
.d("share", " " +resp
);
826 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
830 JSONObject jsonObject
= new JSONObject (resp
);
831 String jsonStatus
= jsonObject
.getString("status");
832 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
834 String token
= jsonObject
.getString("data");
835 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
836 Log
.d("Actions:shareFile ok", "url: " + uri
);
838 } catch (Exception e
) {
842 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
848 public void onDismiss(EditNameDialog dialog
) {
849 if (dialog
.getResult()) {
850 String newFilename
= dialog
.getNewFilename();
851 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
852 mLastRemoteOperation
= new RenameFileOperation( mFile
,
855 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
856 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
857 mLastRemoteOperation
.execute(wc
, this, mHandler
);
858 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
859 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
864 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
865 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
867 protected Bitmap
doInBackground(String
... params
) {
868 Bitmap result
= null
;
869 if (params
.length
!= 1) return result
;
870 String storagePath
= params
[0];
873 BitmapFactory
.Options options
= new Options();
874 options
.inScaled
= true
;
875 options
.inPurgeable
= true
;
876 options
.inJustDecodeBounds
= true
;
877 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
878 options
.inPreferQualityOverSpeed
= false
;
880 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
881 options
.inMutable
= false
;
884 result
= BitmapFactory
.decodeFile(storagePath
, options
);
885 options
.inJustDecodeBounds
= false
;
887 int width
= options
.outWidth
;
888 int height
= options
.outHeight
;
890 if (width
>= 2048 || height
>= 2048) {
891 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
892 options
.inSampleSize
= scale
;
894 Display display
= getActivity().getWindowManager().getDefaultDisplay();
895 Point size
= new Point();
897 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
898 display
.getSize(size
);
899 screenwidth
= size
.x
;
901 screenwidth
= display
.getWidth();
904 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
906 if (width
> screenwidth
) {
907 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
908 options
.inSampleSize
= scale
;
911 result
= BitmapFactory
.decodeFile(storagePath
, options
);
913 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
915 } catch (OutOfMemoryError e
) {
917 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
919 } catch (NoSuchFieldError e
) {
921 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
923 } catch (Throwable t
) {
925 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
930 protected void onPostExecute(Bitmap result
) {
931 if (result
!= null
&& mPreview
!= null
) {
932 mPreview
.setImageBitmap(result
);
942 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
943 if (operation
.equals(mLastRemoteOperation
)) {
944 if (operation
instanceof RemoveFileOperation
) {
945 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
947 } else if (operation
instanceof RenameFileOperation
) {
948 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
950 } else if (operation
instanceof SynchronizeFileOperation
) {
951 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
957 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
958 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
959 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
961 if (result
.isSuccess()) {
962 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
964 if (inDisplayActivity
) {
966 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
967 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
968 transaction
.commit();
969 mContainerActivity
.onFileStateChanged();
971 getActivity().finish();
975 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
977 if (result
.isSslRecoverableException()) {
978 // TODO show the SSL warning dialog
983 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
984 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
985 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
987 if (result
.isSuccess()) {
988 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
989 mContainerActivity
.onFileStateChanged();
992 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
993 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
995 // TODO throw again the new rename dialog
997 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
999 if (result
.isSslRecoverableException()) {
1000 // TODO show the SSL warning dialog
1006 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1007 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1008 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1010 if (!result
.isSuccess()) {
1011 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1012 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1013 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1014 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1018 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1022 if (mFile
.isDown()) {
1023 setButtonsForDown();
1026 setButtonsForRemote();
1030 if (operation
.transferWasRequested()) {
1031 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1032 // checking the service to see if the file is downloading results in FALSE
1034 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1036 if (mFile
.isDown()) {
1037 setButtonsForDown();
1040 setButtonsForRemote();