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
;
22 import org
.apache
.commons
.httpclient
.Credentials
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.annotation
.SuppressLint
;
27 import android
.app
.Activity
;
28 import android
.content
.ActivityNotFoundException
;
29 import android
.content
.BroadcastReceiver
;
30 import android
.content
.Context
;
31 import android
.content
.Intent
;
32 import android
.content
.IntentFilter
;
33 import android
.graphics
.Bitmap
;
34 import android
.graphics
.BitmapFactory
;
35 import android
.graphics
.BitmapFactory
.Options
;
36 import android
.graphics
.Point
;
37 import android
.net
.Uri
;
38 import android
.os
.AsyncTask
;
39 import android
.os
.Bundle
;
40 import android
.os
.Handler
;
41 import android
.support
.v4
.app
.DialogFragment
;
42 import android
.support
.v4
.app
.FragmentTransaction
;
43 import android
.util
.Log
;
44 import android
.view
.Display
;
45 import android
.view
.LayoutInflater
;
46 import android
.view
.View
;
47 import android
.view
.View
.OnClickListener
;
48 import android
.view
.ViewGroup
;
49 import android
.webkit
.MimeTypeMap
;
50 import android
.widget
.Button
;
51 import android
.widget
.CheckBox
;
52 import android
.widget
.ImageView
;
53 import android
.widget
.TextView
;
54 import android
.widget
.Toast
;
56 import com
.actionbarsherlock
.app
.SherlockFragment
;
57 import com
.owncloud
.android
.DisplayUtils
;
58 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
59 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
60 import com
.owncloud
.android
.datamodel
.OCFile
;
61 import com
.owncloud
.android
.files
.services
.FileDownloader
;
62 import com
.owncloud
.android
.files
.services
.FileObserverService
;
63 import com
.owncloud
.android
.files
.services
.FileUploader
;
64 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
65 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
66 import com
.owncloud
.android
.network
.BearerCredentials
;
67 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
68 import com
.owncloud
.android
.operations
.RemoteOperation
;
69 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
70 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
71 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
72 import com
.owncloud
.android
.operations
.RenameFileOperation
;
73 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
74 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
75 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
76 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
77 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
78 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
79 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
81 import com
.owncloud
.android
.R
;
82 import eu
.alefzero
.webdav
.WebdavUtils
;
85 * This Fragment is used to display the details about a file.
87 * @author Bartek Przybylski
90 public class FileDetailFragment
extends SherlockFragment
implements
91 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
{
93 public static final String EXTRA_FILE
= "FILE";
94 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
96 private FileDetailFragment
.ContainerActivity mContainerActivity
;
100 private OCFile mFile
;
101 private Account mAccount
;
102 private FileDataStorageManager mStorageManager
;
103 private ImageView mPreview
;
105 private DownloadFinishReceiver mDownloadFinishReceiver
;
106 private UploadFinishReceiver mUploadFinishReceiver
;
108 private Handler mHandler
;
109 private RemoteOperation mLastRemoteOperation
;
110 private DialogFragment mCurrentDialog
;
112 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
113 public static final String FTAG
= "FileDetails";
114 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
118 * Creates an empty details fragment.
120 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
122 public FileDetailFragment() {
125 mStorageManager
= null
;
126 mLayout
= R
.layout
.file_details_empty
;
131 * Creates a details fragment.
133 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
135 * @param fileToDetail An {@link OCFile} to show in the fragment
136 * @param ocAccount An ownCloud account; needed to start downloads
138 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
139 mFile
= fileToDetail
;
140 mAccount
= ocAccount
;
141 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
142 mLayout
= R
.layout
.file_details_empty
;
147 public void onCreate(Bundle savedInstanceState
) {
148 super.onCreate(savedInstanceState
);
149 mHandler
= new Handler();
154 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
155 Bundle savedInstanceState
) {
156 super.onCreateView(inflater
, container
, savedInstanceState
);
158 if (savedInstanceState
!= null
) {
159 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
160 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
163 if(mFile
!= null
&& mAccount
!= null
) {
164 mLayout
= R
.layout
.file_details_fragment
;
168 view
= inflater
.inflate(mLayout
, container
, false
);
171 if (mLayout
== R
.layout
.file_details_fragment
) {
172 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
173 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
174 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
175 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
176 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
177 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
178 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
181 updateFileDetails(false
);
190 public void onAttach(Activity activity
) {
191 super.onAttach(activity
);
193 mContainerActivity
= (ContainerActivity
) activity
;
194 } catch (ClassCastException e
) {
195 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
204 public void onActivityCreated(Bundle savedInstanceState
) {
205 super.onActivityCreated(savedInstanceState
);
206 if (mAccount
!= null
) {
207 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());;
213 public void onSaveInstanceState(Bundle outState
) {
214 Log
.i(getClass().toString(), "onSaveInstanceState() start");
215 super.onSaveInstanceState(outState
);
216 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
217 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
218 Log
.i(getClass().toString(), "onSaveInstanceState() end");
223 public void onResume() {
226 mDownloadFinishReceiver
= new DownloadFinishReceiver();
227 IntentFilter filter
= new IntentFilter(
228 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
229 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
231 mUploadFinishReceiver
= new UploadFinishReceiver();
232 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
233 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
235 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
239 public void onPause() {
242 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
243 mDownloadFinishReceiver
= null
;
245 getActivity().unregisterReceiver(mUploadFinishReceiver
);
246 mUploadFinishReceiver
= null
;
248 if (mPreview
!= null
) {
254 public View
getView() {
255 return super.getView() == null ? mView
: super.getView();
261 public void onClick(View v
) {
263 case R
.id
.fdDownloadBtn
: {
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
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
296 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
299 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
300 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
301 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
306 case R
.id
.fdKeepInSync
: {
307 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
308 mFile
.setKeepInSync(cb
.isChecked());
309 mStorageManager
.saveFile(mFile
);
311 /// register the OCFile instance in the observer service to monitor local updates;
312 /// if necessary, the file is download
313 Intent intent
= new Intent(getActivity().getApplicationContext(),
314 FileObserverService
.class);
315 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
317 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
318 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
319 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
320 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
321 Log
.e(TAG
, "starting observer service");
322 getActivity().startService(intent
);
324 if (mFile
.keepInSync()) {
325 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
329 case R
.id
.fdRenameBtn
: {
330 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
331 dialog
.show(getFragmentManager(), "nameeditdialog");
334 case R
.id
.fdRemoveBtn
: {
335 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
336 R
.string
.confirmation_remove_alert
,
337 new String
[]{mFile
.getFileName()},
338 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
339 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
340 R
.string
.common_cancel
);
341 confDialog
.setOnConfirmationListener(this);
342 mCurrentDialog
= confDialog
;
343 mCurrentDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
346 case R
.id
.fdOpenBtn
: {
347 String storagePath
= mFile
.getStoragePath();
348 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
350 Intent i
= new Intent(Intent
.ACTION_VIEW
);
351 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
352 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
355 } catch (Throwable t
) {
356 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
357 boolean toastIt
= true
;
358 String mimeType
= "";
360 Intent i
= new Intent(Intent
.ACTION_VIEW
);
361 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
362 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
363 if (mimeType
!= null
) {
364 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
367 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
369 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
374 } catch (IndexOutOfBoundsException e
) {
375 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
377 } catch (ActivityNotFoundException e
) {
378 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
380 } catch (Throwable th
) {
381 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
385 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
393 Log
.e(TAG
, "Incorrect view clicked!");
396 /* else if (v.getId() == R.id.fdShareBtn) {
397 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
404 public void onConfirmation(String callerTag
) {
405 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
406 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
407 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
410 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
411 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
412 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
415 mCurrentDialog
.dismiss();
416 mCurrentDialog
= null
;
420 public void onNeutral(String callerTag
) {
422 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
424 mFile
.setStoragePath(null
);
425 mStorageManager
.saveFile(mFile
);
426 updateFileDetails(mFile
, mAccount
);
428 mCurrentDialog
.dismiss();
429 mCurrentDialog
= null
;
433 public void onCancel(String callerTag
) {
434 Log
.d(TAG
, "REMOVAL CANCELED");
435 mCurrentDialog
.dismiss();
436 mCurrentDialog
= null
;
441 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
443 * @return True when the fragment was created with the empty layout.
445 public boolean isEmpty() {
446 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
451 * Can be used to get the file that is currently being displayed.
452 * @return The file on the screen.
454 public OCFile
getDisplayedFile(){
459 * Use this method to signal this Activity that it shall update its view.
461 * @param file : An {@link OCFile}
463 public void updateFileDetails(OCFile file
, Account ocAccount
) {
465 if (ocAccount
!= null
&& (
466 mStorageManager
== null
||
467 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
469 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
471 mAccount
= ocAccount
;
472 updateFileDetails(false
);
477 * Updates the view with all relevant details about that file.
479 * TODO Remove parameter when the transferring state of files is kept in database.
481 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
482 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
483 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
486 public void updateFileDetails(boolean transferring
) {
488 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
491 setFilename(mFile
.getFileName());
492 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
494 setFilesize(mFile
.getFileLength());
495 if(ocVersionSupportsTimeCreated()){
496 setTimeCreated(mFile
.getCreationTimestamp());
499 setTimeModified(mFile
.getModificationTimestamp());
501 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
502 cb
.setChecked(mFile
.keepInSync());
504 // configure UI for depending upon local state of the file
505 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
506 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
507 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
508 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
509 setButtonsForTransferring();
511 } else if (mFile
.isDown()) {
513 if (mFile
.getMimetype().startsWith("image/")) {
514 BitmapLoader bl
= new BitmapLoader();
515 bl
.execute(new String
[]{mFile
.getStoragePath()});
521 // TODO load default preview image; when the local file is removed, the preview remains there
522 setButtonsForRemote();
525 getView().invalidate();
530 * Updates the filename in view
531 * @param filename to set
533 private void setFilename(String filename
) {
534 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
536 tv
.setText(filename
);
540 * Updates the MIME type in view
541 * @param mimetype to set
543 private void setFiletype(String mimetype
) {
544 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
546 tv
.setText(mimetype
);
550 * Updates the file size in view
551 * @param filesize in bytes to set
553 private void setFilesize(long filesize
) {
554 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
556 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
560 * Updates the time that the file was created in view
561 * @param milliseconds Unix time to set
563 private void setTimeCreated(long milliseconds
){
564 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
565 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
567 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
568 tv
.setVisibility(View
.VISIBLE
);
569 tvLabel
.setVisibility(View
.VISIBLE
);
574 * Updates the time that the file was last modified
575 * @param milliseconds Unix time to set
577 private void setTimeModified(long milliseconds
){
578 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
580 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
585 * Enables or disables buttons for a file being downloaded
587 private void setButtonsForTransferring() {
589 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
590 downloadButton
.setText(R
.string
.common_cancel
);
591 //downloadButton.setEnabled(false);
593 // let's protect the user from himself ;)
594 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
595 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
596 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
597 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
602 * Enables or disables buttons for a file locally available
604 private void setButtonsForDown() {
606 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
607 downloadButton
.setText(R
.string
.filedetails_sync_file
);
609 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
610 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
611 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
612 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
617 * Enables or disables buttons for a file not locally available
619 private void setButtonsForRemote() {
621 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
622 downloadButton
.setText(R
.string
.filedetails_download
);
624 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
625 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
626 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
627 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
633 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
634 * the time that the file was created. There is a chance that this will
635 * be fixed in future versions. Use this method to check if this version of
636 * ownCloud has this fix.
637 * @return True, if ownCloud the ownCloud version is supporting creation time
639 private boolean ocVersionSupportsTimeCreated(){
640 /*if(mAccount != null){
641 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
642 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
643 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
644 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
653 * Interface to implement by any Activity that includes some instance of FileDetailFragment
655 * @author David A. Velasco
657 public interface ContainerActivity
extends TransferServiceGetter
{
660 * Callback method invoked when the detail fragment wants to notice its container
661 * activity about a relevant state the file shown by the fragment.
663 * Added to notify to FileDisplayActivity about the need of refresh the files list.
665 * Currently called when:
666 * - a download is started;
667 * - a rename is completed;
668 * - a deletion is completed;
669 * - the 'inSync' flag is changed;
671 public void onFileStateChanged();
677 * Once the file download has finished -> update view
678 * @author Bartek Przybylski
680 private class DownloadFinishReceiver
extends BroadcastReceiver
{
682 public void onReceive(Context context
, Intent intent
) {
683 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
685 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
686 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
687 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
688 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
689 if (downloadWasFine
) {
690 mFile
= mStorageManager
.getFileByPath(downloadedRemotePath
);
692 updateFileDetails(false
); // it updates the buttons; must be called although !downloadWasFine
700 * Once the file upload has finished -> update view
702 * Being notified about the finish of an upload is necessary for the next sequence:
703 * 1. Upload a big file.
704 * 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
705 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
706 * 3. Click the file in the list to see its details.
707 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
709 private class UploadFinishReceiver
extends BroadcastReceiver
{
711 public void onReceive(Context context
, Intent intent
) {
712 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
714 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
715 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
716 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
717 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
718 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
721 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
723 if (renamedInUpload
) {
724 String newName
= (new File(uploadRemotePath
)).getName();
725 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
728 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
729 updateFileDetails(false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
736 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
738 @SuppressWarnings("unused")
739 private class ShareRunnable implements Runnable {
740 private String mPath;
742 public ShareRunnable(String path) {
747 AccountManager am = AccountManager.get(getActivity());
748 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
749 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
750 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
752 Log.d("share", "sharing for version " + ocv.toString());
754 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
755 String APPS_PATH = "/apps/files_sharing/";
756 String SHARE_PATH = "ajax/share.php";
758 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
760 final String WEBDAV_SCRIPT = "webdav.php";
761 final String WEBDAV_FILES_LOCATION = "/files/";
763 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
764 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
765 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
767 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
768 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
770 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
772 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
773 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
774 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
775 Log.d("share", mPath+"");
776 formparams.add(new BasicNameValuePair("sources",mPath));
777 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
778 formparams.add(new BasicNameValuePair("permissions", "0"));
779 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
783 PropFindMethod find = new PropFindMethod(url+"/");
784 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
785 Log.d("sharer", ""+ url+"/");
787 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
788 Log.d("sharer-h", a.getName() + ":"+a.getValue());
791 int status2 = wc.executeMethod(find);
793 Log.d("sharer", "propstatus "+status2);
795 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
796 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
798 status2 = wc.executeMethod(get);
800 Log.d("sharer", "getstatus "+status2);
801 Log.d("sharer", "" + get.getResponseBodyAsString());
803 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
804 Log.d("sharer", a.getName() + ":"+a.getValue());
807 status = wc.executeMethod(post);
808 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
809 Log.d("sharer-h", a.getName() + ":"+a.getValue());
811 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
812 Log.d("sharer", a.getName() + ":"+a.getValue());
814 String resp = post.getResponseBodyAsString();
815 Log.d("share", ""+post.getURI().toString());
816 Log.d("share", "returned status " + status);
817 Log.d("share", " " +resp);
819 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
823 JSONObject jsonObject = new JSONObject (resp);
824 String jsonStatus = jsonObject.getString("status");
825 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
827 String token = jsonObject.getString("data");
828 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
829 Log.d("Actions:shareFile ok", "url: " + uri);
831 } catch (Exception e) {
835 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
842 public void onDismiss(EditNameDialog dialog
) {
843 if (dialog
.getResult()) {
844 String newFilename
= dialog
.getNewFilename();
845 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
846 mLastRemoteOperation
= new RenameFileOperation( mFile
,
849 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
850 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
851 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
852 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
857 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
858 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
860 protected Bitmap
doInBackground(String
... params
) {
861 Bitmap result
= null
;
862 if (params
.length
!= 1) return result
;
863 String storagePath
= params
[0];
866 BitmapFactory
.Options options
= new Options();
867 options
.inScaled
= true
;
868 options
.inPurgeable
= true
;
869 options
.inJustDecodeBounds
= true
;
870 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
871 options
.inPreferQualityOverSpeed
= false
;
873 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
874 options
.inMutable
= false
;
877 result
= BitmapFactory
.decodeFile(storagePath
, options
);
878 options
.inJustDecodeBounds
= false
;
880 int width
= options
.outWidth
;
881 int height
= options
.outHeight
;
883 if (width
>= 2048 || height
>= 2048) {
884 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
885 options
.inSampleSize
= scale
;
887 Display display
= getActivity().getWindowManager().getDefaultDisplay();
888 Point size
= new Point();
890 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
891 display
.getSize(size
);
892 screenwidth
= size
.x
;
894 screenwidth
= display
.getWidth();
897 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
899 if (width
> screenwidth
) {
900 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
901 options
.inSampleSize
= scale
;
904 result
= BitmapFactory
.decodeFile(storagePath
, options
);
906 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
908 } catch (OutOfMemoryError e
) {
910 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
912 } catch (NoSuchFieldError e
) {
914 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
916 } catch (Throwable t
) {
918 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
923 protected void onPostExecute(Bitmap result
) {
924 if (result
!= null
&& mPreview
!= null
) {
925 mPreview
.setImageBitmap(result
);
935 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
936 if (operation
instanceof RemoveFileOperation
) {
937 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
939 } else if (operation
instanceof RenameFileOperation
) {
940 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
942 } else if (operation
instanceof SynchronizeFileOperation
) {
943 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
948 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
949 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
950 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
952 if (result
.isSuccess()) {
953 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
955 if (inDisplayActivity
) {
957 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
958 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
959 transaction
.commit();
960 mContainerActivity
.onFileStateChanged();
962 getActivity().finish();
966 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
968 if (result
.isSslRecoverableException()) {
969 // TODO show the SSL warning dialog
974 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
975 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
976 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
978 if (result
.isSuccess()) {
979 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
980 mContainerActivity
.onFileStateChanged();
983 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
984 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
986 // TODO throw again the new rename dialog
988 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
990 if (result
.isSslRecoverableException()) {
991 // TODO show the SSL warning dialog
997 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
998 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
999 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1001 if (!result
.isSuccess()) {
1002 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1003 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1004 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1005 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1009 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1013 if (mFile
.isDown()) {
1014 setButtonsForDown();
1017 setButtonsForRemote();
1021 if (operation
.transferWasRequested()) {
1022 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1023 // checking the service to see if the file is downloading results in FALSE
1025 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1027 if (mFile
.isDown()) {
1028 setButtonsForDown();
1031 setButtonsForRemote();