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
;
23 import org
.apache
.commons
.httpclient
.UsernamePasswordCredentials
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.annotation
.SuppressLint
;
28 import android
.app
.Activity
;
29 import android
.content
.ActivityNotFoundException
;
30 import android
.content
.BroadcastReceiver
;
31 import android
.content
.Context
;
32 import android
.content
.Intent
;
33 import android
.content
.IntentFilter
;
34 import android
.graphics
.Bitmap
;
35 import android
.graphics
.BitmapFactory
;
36 import android
.graphics
.BitmapFactory
.Options
;
37 import android
.graphics
.Point
;
38 import android
.net
.Uri
;
39 import android
.os
.AsyncTask
;
40 import android
.os
.Bundle
;
41 import android
.os
.Handler
;
42 import android
.support
.v4
.app
.DialogFragment
;
43 import android
.support
.v4
.app
.FragmentTransaction
;
44 import android
.util
.Log
;
45 import android
.view
.Display
;
46 import android
.view
.LayoutInflater
;
47 import android
.view
.View
;
48 import android
.view
.View
.OnClickListener
;
49 import android
.view
.ViewGroup
;
50 import android
.webkit
.MimeTypeMap
;
51 import android
.widget
.Button
;
52 import android
.widget
.CheckBox
;
53 import android
.widget
.ImageView
;
54 import android
.widget
.TextView
;
55 import android
.widget
.Toast
;
57 import com
.actionbarsherlock
.app
.SherlockFragment
;
58 import com
.owncloud
.android
.DisplayUtils
;
59 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
60 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
61 import com
.owncloud
.android
.datamodel
.OCFile
;
62 import com
.owncloud
.android
.files
.services
.FileDownloader
;
63 import com
.owncloud
.android
.files
.services
.FileObserverService
;
64 import com
.owncloud
.android
.files
.services
.FileUploader
;
65 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
67 import com
.owncloud
.android
.network
.BearerCredentials
;
68 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
69 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
70 import com
.owncloud
.android
.operations
.RemoteOperation
;
71 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
72 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
73 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
74 import com
.owncloud
.android
.operations
.RenameFileOperation
;
75 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
76 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
77 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
78 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
79 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
80 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
81 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
83 import com
.owncloud
.android
.R
;
84 import eu
.alefzero
.webdav
.WebdavUtils
;
87 * This Fragment is used to display the details about a file.
89 * @author Bartek Przybylski
92 public class FileDetailFragment
extends SherlockFragment
implements
93 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
{
95 public static final String EXTRA_FILE
= "FILE";
96 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
98 private FileDetailFragment
.ContainerActivity mContainerActivity
;
102 private OCFile mFile
;
103 private Account mAccount
;
104 private FileDataStorageManager mStorageManager
;
105 private ImageView mPreview
;
107 private DownloadFinishReceiver mDownloadFinishReceiver
;
108 private UploadFinishReceiver mUploadFinishReceiver
;
110 private Handler mHandler
;
111 private RemoteOperation mLastRemoteOperation
;
112 private DialogFragment mCurrentDialog
;
114 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
115 public static final String FTAG
= "FileDetails";
116 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
120 * Creates an empty details fragment.
122 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
124 public FileDetailFragment() {
127 mStorageManager
= null
;
128 mLayout
= R
.layout
.file_details_empty
;
133 * Creates a details fragment.
135 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
137 * @param fileToDetail An {@link OCFile} to show in the fragment
138 * @param ocAccount An ownCloud account; needed to start downloads
140 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
141 mFile
= fileToDetail
;
142 mAccount
= ocAccount
;
143 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
144 mLayout
= R
.layout
.file_details_empty
;
146 if(fileToDetail
!= null
&& ocAccount
!= null
) {
147 mLayout
= R
.layout
.file_details_fragment
;
153 public void onCreate(Bundle savedInstanceState
) {
154 super.onCreate(savedInstanceState
);
155 mHandler
= new Handler();
160 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
161 Bundle savedInstanceState
) {
162 super.onCreateView(inflater
, container
, savedInstanceState
);
164 if (savedInstanceState
!= null
) {
165 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
166 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
170 view
= inflater
.inflate(mLayout
, container
, false
);
173 if (mLayout
== R
.layout
.file_details_fragment
) {
174 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
175 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
176 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
177 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
178 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
179 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
180 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
183 updateFileDetails(false
);
192 public void onAttach(Activity activity
) {
193 super.onAttach(activity
);
195 mContainerActivity
= (ContainerActivity
) activity
;
196 } catch (ClassCastException e
) {
197 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
206 public void onActivityCreated(Bundle savedInstanceState
) {
207 super.onActivityCreated(savedInstanceState
);
208 if (mAccount
!= null
) {
209 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());;
215 public void onSaveInstanceState(Bundle outState
) {
216 Log
.i(getClass().toString(), "onSaveInstanceState() start");
217 super.onSaveInstanceState(outState
);
218 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
219 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
220 Log
.i(getClass().toString(), "onSaveInstanceState() end");
225 public void onResume() {
228 mDownloadFinishReceiver
= new DownloadFinishReceiver();
229 IntentFilter filter
= new IntentFilter(
230 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
231 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
233 mUploadFinishReceiver
= new UploadFinishReceiver();
234 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
235 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
237 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
241 public void onPause() {
244 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
245 mDownloadFinishReceiver
= null
;
247 getActivity().unregisterReceiver(mUploadFinishReceiver
);
248 mUploadFinishReceiver
= null
;
250 if (mPreview
!= null
) {
256 public View
getView() {
257 return super.getView() == null ? mView
: super.getView();
263 public void onClick(View v
) {
265 case R
.id
.fdDownloadBtn
: {
266 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
267 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
268 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
269 downloaderBinder
.cancel(mAccount
, mFile
);
270 if (mFile
.isDown()) {
273 setButtonsForRemote();
276 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
277 uploaderBinder
.cancel(mAccount
, mFile
);
278 if (!mFile
.fileExists()) {
279 // TODO make something better
280 if (getActivity() instanceof FileDisplayActivity
) {
282 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
283 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
284 transaction
.commit();
285 mContainerActivity
.onFileStateChanged();
287 getActivity().finish();
290 } else if (mFile
.isDown()) {
293 setButtonsForRemote();
297 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
298 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
301 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
302 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
303 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
308 case R
.id
.fdKeepInSync
: {
309 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
310 mFile
.setKeepInSync(cb
.isChecked());
311 mStorageManager
.saveFile(mFile
);
313 /// register the OCFile instance in the observer service to monitor local updates;
314 /// if necessary, the file is download
315 Intent intent
= new Intent(getActivity().getApplicationContext(),
316 FileObserverService
.class);
317 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
319 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
320 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
321 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
322 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
323 Log
.e(TAG
, "starting observer service");
324 getActivity().startService(intent
);
326 if (mFile
.keepInSync()) {
327 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
331 case R
.id
.fdRenameBtn
: {
332 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
333 dialog
.show(getFragmentManager(), "nameeditdialog");
336 case R
.id
.fdRemoveBtn
: {
337 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
338 R
.string
.confirmation_remove_alert
,
339 new String
[]{mFile
.getFileName()},
340 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
341 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
342 R
.string
.common_cancel
);
343 confDialog
.setOnConfirmationListener(this);
344 mCurrentDialog
= confDialog
;
345 mCurrentDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
348 case R
.id
.fdOpenBtn
: {
349 String storagePath
= mFile
.getStoragePath();
350 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
352 Intent i
= new Intent(Intent
.ACTION_VIEW
);
353 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
354 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
357 } catch (Throwable t
) {
358 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
359 boolean toastIt
= true
;
360 String mimeType
= "";
362 Intent i
= new Intent(Intent
.ACTION_VIEW
);
363 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
364 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
365 if (mimeType
!= null
) {
366 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
369 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
371 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
376 } catch (IndexOutOfBoundsException e
) {
377 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
379 } catch (ActivityNotFoundException e
) {
380 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
382 } catch (Throwable th
) {
383 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
387 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
395 Log
.e(TAG
, "Incorrect view clicked!");
398 /* else if (v.getId() == R.id.fdShareBtn) {
399 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
406 public void onConfirmation(String callerTag
) {
407 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
408 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
409 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
412 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
414 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
415 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
418 mCurrentDialog
.dismiss();
419 mCurrentDialog
= null
;
423 public void onNeutral(String callerTag
) {
425 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
427 mFile
.setStoragePath(null
);
428 mStorageManager
.saveFile(mFile
);
429 updateFileDetails(mFile
, mAccount
);
431 mCurrentDialog
.dismiss();
432 mCurrentDialog
= null
;
436 public void onCancel(String callerTag
) {
437 Log
.d(TAG
, "REMOVAL CANCELED");
438 mCurrentDialog
.dismiss();
439 mCurrentDialog
= null
;
444 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
446 * @return True when the fragment was created with the empty layout.
448 public boolean isEmpty() {
449 return mLayout
== R
.layout
.file_details_empty
;
454 * Can be used to get the file that is currently being displayed.
455 * @return The file on the screen.
457 public OCFile
getDisplayedFile(){
462 * Use this method to signal this Activity that it shall update its view.
464 * @param file : An {@link OCFile}
466 public void updateFileDetails(OCFile file
, Account ocAccount
) {
468 if (ocAccount
!= null
&& (
469 mStorageManager
== null
||
470 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
472 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
474 mAccount
= ocAccount
;
475 updateFileDetails(false
);
480 * Updates the view with all relevant details about that file.
482 * TODO Remove parameter when the transferring state of files is kept in database.
484 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
485 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
486 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
489 public void updateFileDetails(boolean transferring
) {
491 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
494 setFilename(mFile
.getFileName());
495 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
497 setFilesize(mFile
.getFileLength());
498 if(ocVersionSupportsTimeCreated()){
499 setTimeCreated(mFile
.getCreationTimestamp());
502 setTimeModified(mFile
.getModificationTimestamp());
504 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
505 cb
.setChecked(mFile
.keepInSync());
507 // configure UI for depending upon local state of the file
508 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
509 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
510 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
511 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
512 setButtonsForTransferring();
514 } else if (mFile
.isDown()) {
516 if (mFile
.getMimetype().startsWith("image/")) {
517 BitmapLoader bl
= new BitmapLoader();
518 bl
.execute(new String
[]{mFile
.getStoragePath()});
524 // TODO load default preview image; when the local file is removed, the preview remains there
525 setButtonsForRemote();
528 getView().invalidate();
533 * Updates the filename in view
534 * @param filename to set
536 private void setFilename(String filename
) {
537 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
539 tv
.setText(filename
);
543 * Updates the MIME type in view
544 * @param mimetype to set
546 private void setFiletype(String mimetype
) {
547 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
549 tv
.setText(mimetype
);
553 * Updates the file size in view
554 * @param filesize in bytes to set
556 private void setFilesize(long filesize
) {
557 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
559 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
563 * Updates the time that the file was created in view
564 * @param milliseconds Unix time to set
566 private void setTimeCreated(long milliseconds
){
567 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
568 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
570 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
571 tv
.setVisibility(View
.VISIBLE
);
572 tvLabel
.setVisibility(View
.VISIBLE
);
577 * Updates the time that the file was last modified
578 * @param milliseconds Unix time to set
580 private void setTimeModified(long milliseconds
){
581 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
583 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
588 * Enables or disables buttons for a file being downloaded
590 private void setButtonsForTransferring() {
592 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
593 downloadButton
.setText(R
.string
.common_cancel
);
594 //downloadButton.setEnabled(false);
596 // let's protect the user from himself ;)
597 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
598 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
599 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
600 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
605 * Enables or disables buttons for a file locally available
607 private void setButtonsForDown() {
609 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
610 downloadButton
.setText(R
.string
.filedetails_sync_file
);
612 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
613 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
614 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
615 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
620 * Enables or disables buttons for a file not locally available
622 private void setButtonsForRemote() {
624 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
625 downloadButton
.setText(R
.string
.filedetails_download
);
627 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
628 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
629 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
630 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
636 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
637 * the time that the file was created. There is a chance that this will
638 * be fixed in future versions. Use this method to check if this version of
639 * ownCloud has this fix.
640 * @return True, if ownCloud the ownCloud version is supporting creation time
642 private boolean ocVersionSupportsTimeCreated(){
643 /*if(mAccount != null){
644 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
645 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
646 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
647 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
656 * Interface to implement by any Activity that includes some instance of FileDetailFragment
658 * @author David A. Velasco
660 public interface ContainerActivity
extends TransferServiceGetter
{
663 * Callback method invoked when the detail fragment wants to notice its container
664 * activity about a relevant state the file shown by the fragment.
666 * Added to notify to FileDisplayActivity about the need of refresh the files list.
668 * Currently called when:
669 * - a download is started;
670 * - a rename is completed;
671 * - a deletion is completed;
672 * - the 'inSync' flag is changed;
674 public void onFileStateChanged();
680 * Once the file download has finished -> update view
681 * @author Bartek Przybylski
683 private class DownloadFinishReceiver
extends BroadcastReceiver
{
685 public void onReceive(Context context
, Intent intent
) {
686 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
688 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
689 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
690 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
691 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
692 if (downloadWasFine
) {
693 mFile
= mStorageManager
.getFileByPath(downloadedRemotePath
);
695 updateFileDetails(false
); // it updates the buttons; must be called although !downloadWasFine
703 * Once the file upload has finished -> update view
705 * Being notified about the finish of an upload is necessary for the next sequence:
706 * 1. Upload a big file.
707 * 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
708 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
709 * 3. Click the file in the list to see its details.
710 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
712 private class UploadFinishReceiver
extends BroadcastReceiver
{
714 public void onReceive(Context context
, Intent intent
) {
715 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
717 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
718 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
719 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
720 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
721 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
724 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
726 if (renamedInUpload
) {
727 String newName
= (new File(uploadRemotePath
)).getName();
728 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
730 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
732 updateFileDetails(false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
739 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
741 @SuppressWarnings("unused")
742 private class ShareRunnable implements Runnable {
743 private String mPath;
745 public ShareRunnable(String path) {
750 AccountManager am = AccountManager.get(getActivity());
751 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
752 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
753 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
755 Log.d("share", "sharing for version " + ocv.toString());
757 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
758 String APPS_PATH = "/apps/files_sharing/";
759 String SHARE_PATH = "ajax/share.php";
761 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
763 final String WEBDAV_SCRIPT = "webdav.php";
764 final String WEBDAV_FILES_LOCATION = "/files/";
766 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
767 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
768 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
770 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
771 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
773 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
775 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
776 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
777 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
778 Log.d("share", mPath+"");
779 formparams.add(new BasicNameValuePair("sources",mPath));
780 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
781 formparams.add(new BasicNameValuePair("permissions", "0"));
782 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
786 PropFindMethod find = new PropFindMethod(url+"/");
787 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
788 Log.d("sharer", ""+ url+"/");
790 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
791 Log.d("sharer-h", a.getName() + ":"+a.getValue());
794 int status2 = wc.executeMethod(find);
796 Log.d("sharer", "propstatus "+status2);
798 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
799 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
801 status2 = wc.executeMethod(get);
803 Log.d("sharer", "getstatus "+status2);
804 Log.d("sharer", "" + get.getResponseBodyAsString());
806 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
807 Log.d("sharer", a.getName() + ":"+a.getValue());
810 status = wc.executeMethod(post);
811 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
812 Log.d("sharer-h", a.getName() + ":"+a.getValue());
814 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
815 Log.d("sharer", a.getName() + ":"+a.getValue());
817 String resp = post.getResponseBodyAsString();
818 Log.d("share", ""+post.getURI().toString());
819 Log.d("share", "returned status " + status);
820 Log.d("share", " " +resp);
822 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
826 JSONObject jsonObject = new JSONObject (resp);
827 String jsonStatus = jsonObject.getString("status");
828 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
830 String token = jsonObject.getString("data");
831 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
832 Log.d("Actions:shareFile ok", "url: " + uri);
834 } catch (Exception e) {
838 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
845 public void onDismiss(EditNameDialog dialog
) {
846 if (dialog
.getResult()) {
847 String newFilename
= dialog
.getNewFilename();
848 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
849 mLastRemoteOperation
= new RenameFileOperation( mFile
,
852 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
853 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
854 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
855 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
860 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
861 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
863 protected Bitmap
doInBackground(String
... params
) {
864 Bitmap result
= null
;
865 if (params
.length
!= 1) return result
;
866 String storagePath
= params
[0];
869 BitmapFactory
.Options options
= new Options();
870 options
.inScaled
= true
;
871 options
.inPurgeable
= true
;
872 options
.inJustDecodeBounds
= true
;
873 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
874 options
.inPreferQualityOverSpeed
= false
;
876 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
877 options
.inMutable
= false
;
880 result
= BitmapFactory
.decodeFile(storagePath
, options
);
881 options
.inJustDecodeBounds
= false
;
883 int width
= options
.outWidth
;
884 int height
= options
.outHeight
;
886 if (width
>= 2048 || height
>= 2048) {
887 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
888 options
.inSampleSize
= scale
;
890 Display display
= getActivity().getWindowManager().getDefaultDisplay();
891 Point size
= new Point();
893 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
894 display
.getSize(size
);
895 screenwidth
= size
.x
;
897 screenwidth
= display
.getWidth();
900 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
902 if (width
> screenwidth
) {
903 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
904 options
.inSampleSize
= scale
;
907 result
= BitmapFactory
.decodeFile(storagePath
, options
);
909 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
911 } catch (OutOfMemoryError e
) {
913 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
915 } catch (NoSuchFieldError e
) {
917 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
919 } catch (Throwable t
) {
921 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
926 protected void onPostExecute(Bitmap result
) {
927 if (result
!= null
&& mPreview
!= null
) {
928 mPreview
.setImageBitmap(result
);
938 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
939 if (!result
.isSuccess() && result
.getCode() == ResultCode
.UNAUTHORIZED
) {
940 AccountManager am
= AccountManager
.get(getSherlockActivity());
941 //am.invalidateAuthToken(AccountAuthenticator.ACCOUNT_TYPE, OwnCloudClientUtils.getAuthorizationTokenType(operation.getClient().getCredentials()));
942 Credentials cred
= operation
.getClient().getCredentials();
943 if (cred
instanceof BearerCredentials
) {
944 am
.invalidateAuthToken(AccountAuthenticator
.ACCOUNT_TYPE
, ((BearerCredentials
)cred
).getAccessToken());
946 am
.clearPassword(mAccount
);
948 operation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity()); // need a new client instance, so avoid retry()
949 // TODO si el usuario no se autoriza de nuevo, esto genera un bucle infinito; o un error en la creación del objecto cliente
952 if (operation
instanceof RemoveFileOperation
) {
953 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
955 } else if (operation
instanceof RenameFileOperation
) {
956 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
958 } else if (operation
instanceof SynchronizeFileOperation
) {
959 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
965 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
966 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
967 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
969 if (result
.isSuccess()) {
970 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
972 if (inDisplayActivity
) {
974 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
975 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
976 transaction
.commit();
977 mContainerActivity
.onFileStateChanged();
979 getActivity().finish();
983 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
985 if (result
.isSslRecoverableException()) {
986 // TODO show the SSL warning dialog
991 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
992 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
993 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
995 if (result
.isSuccess()) {
996 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
997 mContainerActivity
.onFileStateChanged();
1000 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1001 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1003 // TODO throw again the new rename dialog
1005 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1007 if (result
.isSslRecoverableException()) {
1008 // TODO show the SSL warning dialog
1014 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1015 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1016 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1018 if (!result
.isSuccess()) {
1019 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1020 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1021 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1022 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1026 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1030 if (mFile
.isDown()) {
1031 setButtonsForDown();
1034 setButtonsForRemote();
1038 if (operation
.transferWasRequested()) {
1039 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1040 // checking the service to see if the file is downloading results in FALSE
1042 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1044 if (mFile
.isDown()) {
1045 setButtonsForDown();
1048 setButtonsForRemote();