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
.DialogFragment
;
54 import android
.support
.v4
.app
.FragmentTransaction
;
55 import android
.util
.Log
;
56 import android
.view
.Display
;
57 import android
.view
.LayoutInflater
;
58 import android
.view
.View
;
59 import android
.view
.View
.OnClickListener
;
60 import android
.view
.ViewGroup
;
61 import android
.webkit
.MimeTypeMap
;
62 import android
.widget
.Button
;
63 import android
.widget
.CheckBox
;
64 import android
.widget
.ImageView
;
65 import android
.widget
.TextView
;
66 import android
.widget
.Toast
;
68 import com
.actionbarsherlock
.app
.SherlockFragment
;
69 import com
.owncloud
.android
.AccountUtils
;
70 import com
.owncloud
.android
.DisplayUtils
;
71 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
72 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
73 import com
.owncloud
.android
.datamodel
.OCFile
;
74 import com
.owncloud
.android
.files
.services
.FileDownloader
;
75 import com
.owncloud
.android
.files
.services
.FileObserverService
;
76 import com
.owncloud
.android
.files
.services
.FileUploader
;
77 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
78 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
79 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
80 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
81 import com
.owncloud
.android
.operations
.RemoteOperation
;
82 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
83 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
88 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
89 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
90 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
91 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
93 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
95 import com
.owncloud
.android
.R
;
96 import eu
.alefzero
.webdav
.WebdavClient
;
97 import eu
.alefzero
.webdav
.WebdavUtils
;
100 * This Fragment is used to display the details about a file.
102 * @author Bartek Przybylski
105 public class FileDetailFragment
extends SherlockFragment
implements
106 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
{
108 public static final String EXTRA_FILE
= "FILE";
109 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
111 private FileDetailFragment
.ContainerActivity mContainerActivity
;
115 private OCFile mFile
;
116 private Account mAccount
;
117 private FileDataStorageManager mStorageManager
;
118 private ImageView mPreview
;
120 private DownloadFinishReceiver mDownloadFinishReceiver
;
121 private UploadFinishReceiver mUploadFinishReceiver
;
123 private Handler mHandler
;
124 private RemoteOperation mLastRemoteOperation
;
125 private DialogFragment mCurrentDialog
;
127 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
128 public static final String FTAG
= "FileDetails";
129 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
133 * Creates an empty details fragment.
135 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
137 public FileDetailFragment() {
140 mStorageManager
= null
;
141 mLayout
= R
.layout
.file_details_empty
;
146 * Creates a details fragment.
148 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
150 * @param fileToDetail An {@link OCFile} to show in the fragment
151 * @param ocAccount An ownCloud account; needed to start downloads
153 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
154 mFile
= fileToDetail
;
155 mAccount
= ocAccount
;
156 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
157 mLayout
= R
.layout
.file_details_empty
;
159 if(fileToDetail
!= null
&& ocAccount
!= null
) {
160 mLayout
= R
.layout
.file_details_fragment
;
166 public void onCreate(Bundle savedInstanceState
) {
167 super.onCreate(savedInstanceState
);
168 mHandler
= new Handler();
173 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
174 Bundle savedInstanceState
) {
175 super.onCreateView(inflater
, container
, savedInstanceState
);
177 if (savedInstanceState
!= null
) {
178 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
179 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
183 view
= inflater
.inflate(mLayout
, container
, false
);
186 if (mLayout
== R
.layout
.file_details_fragment
) {
187 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
188 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
189 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
190 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
191 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
192 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
193 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
196 updateFileDetails(false
);
205 public void onAttach(Activity activity
) {
206 super.onAttach(activity
);
208 mContainerActivity
= (ContainerActivity
) activity
;
209 } catch (ClassCastException e
) {
210 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
219 public void onActivityCreated(Bundle savedInstanceState
) {
220 super.onActivityCreated(savedInstanceState
);
221 if (mAccount
!= null
) {
222 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());;
228 public void onSaveInstanceState(Bundle outState
) {
229 Log
.i(getClass().toString(), "onSaveInstanceState() start");
230 super.onSaveInstanceState(outState
);
231 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
232 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
233 Log
.i(getClass().toString(), "onSaveInstanceState() end");
238 public void onResume() {
241 mDownloadFinishReceiver
= new DownloadFinishReceiver();
242 IntentFilter filter
= new IntentFilter(
243 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
244 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
246 mUploadFinishReceiver
= new UploadFinishReceiver();
247 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
248 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
250 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
254 public void onPause() {
257 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
258 mDownloadFinishReceiver
= null
;
260 getActivity().unregisterReceiver(mUploadFinishReceiver
);
261 mUploadFinishReceiver
= null
;
263 if (mPreview
!= null
) {
269 public View
getView() {
270 return super.getView() == null ? mView
: super.getView();
276 public void onClick(View v
) {
278 case R
.id
.fdDownloadBtn
: {
279 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
280 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
281 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
282 downloaderBinder
.cancel(mAccount
, mFile
);
283 if (mFile
.isDown()) {
286 setButtonsForRemote();
289 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
290 uploaderBinder
.cancel(mAccount
, mFile
);
291 if (!mFile
.fileExists()) {
292 // TODO make something better
293 if (getActivity() instanceof FileDisplayActivity
) {
295 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
296 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
297 transaction
.commit();
298 mContainerActivity
.onFileStateChanged();
300 getActivity().finish();
303 } else if (mFile
.isDown()) {
306 setButtonsForRemote();
310 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
311 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
);
314 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
315 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
316 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
321 case R
.id
.fdKeepInSync
: {
322 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
323 mFile
.setKeepInSync(cb
.isChecked());
324 mStorageManager
.saveFile(mFile
);
326 /// register the OCFile instance in the observer service to monitor local updates;
327 /// if necessary, the file is download
328 Intent intent
= new Intent(getActivity().getApplicationContext(),
329 FileObserverService
.class);
330 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
332 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
333 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
334 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
335 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
336 Log
.e(TAG
, "starting observer service");
337 getActivity().startService(intent
);
339 if (mFile
.keepInSync()) {
340 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
344 case R
.id
.fdRenameBtn
: {
345 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
346 dialog
.show(getFragmentManager(), "nameeditdialog");
349 case R
.id
.fdRemoveBtn
: {
350 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
351 R
.string
.confirmation_remove_alert
,
352 new String
[]{mFile
.getFileName()},
353 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
354 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
355 R
.string
.common_cancel
);
356 confDialog
.setOnConfirmationListener(this);
357 mCurrentDialog
= confDialog
;
358 mCurrentDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
361 case R
.id
.fdOpenBtn
: {
362 String storagePath
= mFile
.getStoragePath();
363 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
365 Intent i
= new Intent(Intent
.ACTION_VIEW
);
366 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
367 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
370 } catch (Throwable t
) {
371 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
372 boolean toastIt
= true
;
373 String mimeType
= "";
375 Intent i
= new Intent(Intent
.ACTION_VIEW
);
376 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
377 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
378 if (mimeType
!= null
) {
379 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
382 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
384 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
389 } catch (IndexOutOfBoundsException e
) {
390 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
392 } catch (ActivityNotFoundException e
) {
393 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
395 } catch (Throwable th
) {
396 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
400 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
408 Log
.e(TAG
, "Incorrect view clicked!");
411 /* else if (v.getId() == R.id.fdShareBtn) {
412 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
419 public void onConfirmation(String callerTag
) {
420 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
421 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
422 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
425 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
);
427 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
428 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
431 mCurrentDialog
.dismiss();
432 mCurrentDialog
= null
;
436 public void onNeutral(String callerTag
) {
438 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
440 mFile
.setStoragePath(null
);
441 mStorageManager
.saveFile(mFile
);
442 updateFileDetails(mFile
, mAccount
);
444 mCurrentDialog
.dismiss();
445 mCurrentDialog
= null
;
449 public void onCancel(String callerTag
) {
450 Log
.d(TAG
, "REMOVAL CANCELED");
451 mCurrentDialog
.dismiss();
452 mCurrentDialog
= null
;
457 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
459 * @return True when the fragment was created with the empty layout.
461 public boolean isEmpty() {
462 return mLayout
== R
.layout
.file_details_empty
;
467 * Can be used to get the file that is currently being displayed.
468 * @return The file on the screen.
470 public OCFile
getDisplayedFile(){
475 * Use this method to signal this Activity that it shall update its view.
477 * @param file : An {@link OCFile}
479 public void updateFileDetails(OCFile file
, Account ocAccount
) {
481 if (ocAccount
!= null
&& (
482 mStorageManager
== null
||
483 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
485 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
487 mAccount
= ocAccount
;
488 updateFileDetails(false
);
493 * Updates the view with all relevant details about that file.
495 * TODO Remove parameter when the transferring state of files is kept in database.
497 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
498 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
499 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
502 public void updateFileDetails(boolean transferring
) {
504 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
507 setFilename(mFile
.getFileName());
508 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
510 setFilesize(mFile
.getFileLength());
511 if(ocVersionSupportsTimeCreated()){
512 setTimeCreated(mFile
.getCreationTimestamp());
515 setTimeModified(mFile
.getModificationTimestamp());
517 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
518 cb
.setChecked(mFile
.keepInSync());
520 // configure UI for depending upon local state of the file
521 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
522 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
523 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
524 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
525 setButtonsForTransferring();
527 } else if (mFile
.isDown()) {
529 if (mFile
.getMimetype().startsWith("image/")) {
530 BitmapLoader bl
= new BitmapLoader();
531 bl
.execute(new String
[]{mFile
.getStoragePath()});
537 // TODO load default preview image; when the local file is removed, the preview remains there
538 setButtonsForRemote();
541 getView().invalidate();
546 * Updates the filename in view
547 * @param filename to set
549 private void setFilename(String filename
) {
550 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
552 tv
.setText(filename
);
556 * Updates the MIME type in view
557 * @param mimetype to set
559 private void setFiletype(String mimetype
) {
560 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
562 tv
.setText(mimetype
);
566 * Updates the file size in view
567 * @param filesize in bytes to set
569 private void setFilesize(long filesize
) {
570 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
572 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
576 * Updates the time that the file was created in view
577 * @param milliseconds Unix time to set
579 private void setTimeCreated(long milliseconds
){
580 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
581 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
583 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
584 tv
.setVisibility(View
.VISIBLE
);
585 tvLabel
.setVisibility(View
.VISIBLE
);
590 * Updates the time that the file was last modified
591 * @param milliseconds Unix time to set
593 private void setTimeModified(long milliseconds
){
594 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
596 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
601 * Enables or disables buttons for a file being downloaded
603 private void setButtonsForTransferring() {
605 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
606 downloadButton
.setText(R
.string
.common_cancel
);
607 //downloadButton.setEnabled(false);
609 // let's protect the user from himself ;)
610 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
611 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
612 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
613 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
618 * Enables or disables buttons for a file locally available
620 private void setButtonsForDown() {
622 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
623 downloadButton
.setText(R
.string
.filedetails_sync_file
);
625 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
626 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
627 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
628 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
633 * Enables or disables buttons for a file not locally available
635 private void setButtonsForRemote() {
637 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
638 downloadButton
.setText(R
.string
.filedetails_download
);
640 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
641 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
642 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
643 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
649 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
650 * the time that the file was created. There is a chance that this will
651 * be fixed in future versions. Use this method to check if this version of
652 * ownCloud has this fix.
653 * @return True, if ownCloud the ownCloud version is supporting creation time
655 private boolean ocVersionSupportsTimeCreated(){
656 /*if(mAccount != null){
657 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
658 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
659 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
660 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
669 * Interface to implement by any Activity that includes some instance of FileDetailFragment
671 * @author David A. Velasco
673 public interface ContainerActivity
extends TransferServiceGetter
{
676 * Callback method invoked when the detail fragment wants to notice its container
677 * activity about a relevant state the file shown by the fragment.
679 * Added to notify to FileDisplayActivity about the need of refresh the files list.
681 * Currently called when:
682 * - a download is started;
683 * - a rename is completed;
684 * - a deletion is completed;
685 * - the 'inSync' flag is changed;
687 public void onFileStateChanged();
693 * Once the file download has finished -> update view
694 * @author Bartek Przybylski
696 private class DownloadFinishReceiver
extends BroadcastReceiver
{
698 public void onReceive(Context context
, Intent intent
) {
699 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
701 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
702 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
703 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
704 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
705 if (downloadWasFine
) {
706 mFile
= mStorageManager
.getFileByPath(downloadedRemotePath
);
708 updateFileDetails(false
); // it updates the buttons; must be called although !downloadWasFine
716 * Once the file upload has finished -> update view
718 * Being notified about the finish of an upload is necessary for the next sequence:
719 * 1. Upload a big file.
720 * 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
721 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
722 * 3. Click the file in the list to see its details.
723 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
725 private class UploadFinishReceiver
extends BroadcastReceiver
{
727 public void onReceive(Context context
, Intent intent
) {
728 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
730 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
731 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
732 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
733 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
734 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
737 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
739 if (renamedInUpload
) {
740 String newName
= (new File(uploadRemotePath
)).getName();
741 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
743 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
745 updateFileDetails(false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
752 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
754 @SuppressWarnings("unused")
755 private class ShareRunnable implements Runnable {
756 private String mPath;
758 public ShareRunnable(String path) {
763 AccountManager am = AccountManager.get(getActivity());
764 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
765 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
766 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
768 Log.d("share", "sharing for version " + ocv.toString());
770 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
771 String APPS_PATH = "/apps/files_sharing/";
772 String SHARE_PATH = "ajax/share.php";
774 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
776 final String WEBDAV_SCRIPT = "webdav.php";
777 final String WEBDAV_FILES_LOCATION = "/files/";
779 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
780 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
781 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
783 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
784 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
786 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
788 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
789 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
790 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
791 Log.d("share", mPath+"");
792 formparams.add(new BasicNameValuePair("sources",mPath));
793 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
794 formparams.add(new BasicNameValuePair("permissions", "0"));
795 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
799 PropFindMethod find = new PropFindMethod(url+"/");
800 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
801 Log.d("sharer", ""+ url+"/");
803 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
804 Log.d("sharer-h", a.getName() + ":"+a.getValue());
807 int status2 = wc.executeMethod(find);
809 Log.d("sharer", "propstatus "+status2);
811 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
812 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
814 status2 = wc.executeMethod(get);
816 Log.d("sharer", "getstatus "+status2);
817 Log.d("sharer", "" + get.getResponseBodyAsString());
819 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
820 Log.d("sharer", a.getName() + ":"+a.getValue());
823 status = wc.executeMethod(post);
824 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
825 Log.d("sharer-h", a.getName() + ":"+a.getValue());
827 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
828 Log.d("sharer", a.getName() + ":"+a.getValue());
830 String resp = post.getResponseBodyAsString();
831 Log.d("share", ""+post.getURI().toString());
832 Log.d("share", "returned status " + status);
833 Log.d("share", " " +resp);
835 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
839 JSONObject jsonObject = new JSONObject (resp);
840 String jsonStatus = jsonObject.getString("status");
841 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
843 String token = jsonObject.getString("data");
844 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
845 Log.d("Actions:shareFile ok", "url: " + uri);
847 } catch (Exception e) {
851 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
858 public void onDismiss(EditNameDialog dialog
) {
859 if (dialog
.getResult()) {
860 String newFilename
= dialog
.getNewFilename();
861 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
862 mLastRemoteOperation
= new RenameFileOperation( mFile
,
865 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
866 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
);
867 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
868 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
873 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
874 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
876 protected Bitmap
doInBackground(String
... params
) {
877 Bitmap result
= null
;
878 if (params
.length
!= 1) return result
;
879 String storagePath
= params
[0];
882 BitmapFactory
.Options options
= new Options();
883 options
.inScaled
= true
;
884 options
.inPurgeable
= true
;
885 options
.inJustDecodeBounds
= true
;
886 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
887 options
.inPreferQualityOverSpeed
= false
;
889 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
890 options
.inMutable
= false
;
893 result
= BitmapFactory
.decodeFile(storagePath
, options
);
894 options
.inJustDecodeBounds
= false
;
896 int width
= options
.outWidth
;
897 int height
= options
.outHeight
;
899 if (width
>= 2048 || height
>= 2048) {
900 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
901 options
.inSampleSize
= scale
;
903 Display display
= getActivity().getWindowManager().getDefaultDisplay();
904 Point size
= new Point();
906 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
907 display
.getSize(size
);
908 screenwidth
= size
.x
;
910 screenwidth
= display
.getWidth();
913 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
915 if (width
> screenwidth
) {
916 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
917 options
.inSampleSize
= scale
;
920 result
= BitmapFactory
.decodeFile(storagePath
, options
);
922 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
924 } catch (OutOfMemoryError e
) {
926 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
928 } catch (NoSuchFieldError e
) {
930 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
932 } catch (Throwable t
) {
934 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
939 protected void onPostExecute(Bitmap result
) {
940 if (result
!= null
&& mPreview
!= null
) {
941 mPreview
.setImageBitmap(result
);
951 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
952 if (operation
.equals(mLastRemoteOperation
)) {
953 if (operation
instanceof RemoveFileOperation
) {
954 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
956 } else if (operation
instanceof RenameFileOperation
) {
957 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
959 } else if (operation
instanceof SynchronizeFileOperation
) {
960 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
966 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
967 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
968 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
970 if (result
.isSuccess()) {
971 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
973 if (inDisplayActivity
) {
975 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
976 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
977 transaction
.commit();
978 mContainerActivity
.onFileStateChanged();
980 getActivity().finish();
984 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
986 if (result
.isSslRecoverableException()) {
987 // TODO show the SSL warning dialog
992 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
993 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
994 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
996 if (result
.isSuccess()) {
997 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
998 mContainerActivity
.onFileStateChanged();
1001 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1002 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1004 // TODO throw again the new rename dialog
1006 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1008 if (result
.isSslRecoverableException()) {
1009 // TODO show the SSL warning dialog
1015 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1016 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1017 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1019 if (!result
.isSuccess()) {
1020 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1021 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1022 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1023 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1027 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1031 if (mFile
.isDown()) {
1032 setButtonsForDown();
1035 setButtonsForRemote();
1039 if (operation
.transferWasRequested()) {
1040 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1041 // checking the service to see if the file is downloading results in FALSE
1043 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1045 if (mFile
.isDown()) {
1046 setButtonsForDown();
1049 setButtonsForRemote();