1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package com
.owncloud
.android
.ui
.fragment
;
21 import java
.util
.ArrayList
;
22 import java
.util
.List
;
24 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
25 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
26 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
27 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
28 import org
.apache
.http
.HttpStatus
;
29 import org
.apache
.http
.NameValuePair
;
30 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
31 import org
.apache
.http
.message
.BasicNameValuePair
;
32 import org
.apache
.http
.protocol
.HTTP
;
33 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
34 import org
.json
.JSONObject
;
36 import android
.accounts
.Account
;
37 import android
.accounts
.AccountManager
;
38 import android
.annotation
.SuppressLint
;
39 import android
.app
.Activity
;
40 import android
.content
.ActivityNotFoundException
;
41 import android
.content
.BroadcastReceiver
;
42 import android
.content
.Context
;
43 import android
.content
.Intent
;
44 import android
.content
.IntentFilter
;
45 import android
.graphics
.Bitmap
;
46 import android
.graphics
.BitmapFactory
;
47 import android
.graphics
.BitmapFactory
.Options
;
48 import android
.graphics
.Point
;
49 import android
.net
.Uri
;
50 import android
.os
.AsyncTask
;
51 import android
.os
.Bundle
;
52 import android
.os
.Handler
;
53 import android
.support
.v4
.app
.FragmentTransaction
;
54 import android
.util
.Log
;
55 import android
.view
.Display
;
56 import android
.view
.LayoutInflater
;
57 import android
.view
.View
;
58 import android
.view
.View
.OnClickListener
;
59 import android
.view
.ViewGroup
;
60 import android
.webkit
.MimeTypeMap
;
61 import android
.widget
.Button
;
62 import android
.widget
.CheckBox
;
63 import android
.widget
.ImageView
;
64 import android
.widget
.TextView
;
65 import android
.widget
.Toast
;
67 import com
.actionbarsherlock
.app
.SherlockFragment
;
68 import com
.owncloud
.android
.AccountUtils
;
69 import com
.owncloud
.android
.DisplayUtils
;
70 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
71 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
72 import com
.owncloud
.android
.datamodel
.OCFile
;
73 import com
.owncloud
.android
.files
.services
.FileDownloader
;
74 import com
.owncloud
.android
.files
.services
.FileObserverService
;
75 import com
.owncloud
.android
.files
.services
.FileUploader
;
76 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
77 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
78 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
79 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
80 import com
.owncloud
.android
.operations
.RemoteOperation
;
81 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
82 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
83 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RenameFileOperation
;
85 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
86 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
87 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
88 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
89 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
90 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
92 import com
.owncloud
.android
.R
;
93 import eu
.alefzero
.webdav
.WebdavClient
;
94 import eu
.alefzero
.webdav
.WebdavUtils
;
97 * This Fragment is used to display the details about a file.
99 * @author Bartek Przybylski
102 public class FileDetailFragment
extends SherlockFragment
implements
103 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
{
105 public static final String EXTRA_FILE
= "FILE";
106 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
108 private FileDetailFragment
.ContainerActivity mContainerActivity
;
112 private OCFile mFile
;
113 private Account mAccount
;
114 private ImageView mPreview
;
116 private DownloadFinishReceiver mDownloadFinishReceiver
;
117 private UploadFinishReceiver mUploadFinishReceiver
;
119 private Handler mHandler
;
120 private RemoteOperation mLastRemoteOperation
;
122 private static final String TAG
= "FileDetailFragment";
123 public static final String FTAG
= "FileDetails";
124 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
128 * Creates an empty details fragment.
130 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
132 public FileDetailFragment() {
135 mLayout
= R
.layout
.file_details_empty
;
140 * Creates a details fragment.
142 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
144 * @param fileToDetail An {@link OCFile} to show in the fragment
145 * @param ocAccount An ownCloud account; needed to start downloads
147 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
148 mFile
= fileToDetail
;
149 mAccount
= ocAccount
;
150 mLayout
= R
.layout
.file_details_empty
;
152 if(fileToDetail
!= null
&& ocAccount
!= null
) {
153 mLayout
= R
.layout
.file_details_fragment
;
159 public void onCreate(Bundle savedInstanceState
) {
160 super.onCreate(savedInstanceState
);
161 mHandler
= new Handler();
166 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
167 Bundle savedInstanceState
) {
168 super.onCreateView(inflater
, container
, savedInstanceState
);
170 if (savedInstanceState
!= null
) {
171 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
172 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
176 view
= inflater
.inflate(mLayout
, container
, false
);
179 if (mLayout
== R
.layout
.file_details_fragment
) {
180 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
181 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
182 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
183 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
184 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
185 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
186 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
189 updateFileDetails(false
);
198 public void onAttach(Activity activity
) {
199 super.onAttach(activity
);
201 mContainerActivity
= (ContainerActivity
) activity
;
202 } catch (ClassCastException e
) {
203 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
209 public void onSaveInstanceState(Bundle outState
) {
210 Log
.i(getClass().toString(), "onSaveInstanceState() start");
211 super.onSaveInstanceState(outState
);
212 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
213 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
214 Log
.i(getClass().toString(), "onSaveInstanceState() end");
219 public void onResume() {
222 mDownloadFinishReceiver
= new DownloadFinishReceiver();
223 IntentFilter filter
= new IntentFilter(
224 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
225 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
227 mUploadFinishReceiver
= new UploadFinishReceiver();
228 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
229 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
231 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
235 public void onPause() {
238 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
239 mDownloadFinishReceiver
= null
;
241 getActivity().unregisterReceiver(mUploadFinishReceiver
);
242 mUploadFinishReceiver
= null
;
244 if (mPreview
!= null
) {
250 public View
getView() {
251 return super.getView() == null ? mView
: super.getView();
257 public void onClick(View v
) {
259 case R
.id
.fdDownloadBtn
: {
260 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath())) {
261 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
262 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
263 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
264 downloaderBinder
.cancel(mAccount
, mFile
);
265 if (mFile
.isDown()) {
268 setButtonsForRemote();
271 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
272 uploaderBinder
.cancel(mAccount
, mFile
);
273 if (!mFile
.fileExists()) {
274 // TODO make something better
275 if (getActivity() instanceof FileDisplayActivity
) {
277 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
278 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
279 transaction
.commit();
280 mContainerActivity
.onFileStateChanged();
282 getActivity().finish();
285 } else if (mFile
.isDown()) {
288 setButtonsForRemote();
292 Intent i
= new Intent(getActivity(), FileDownloader
.class);
293 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
294 i
.putExtra(FileDownloader
.EXTRA_FILE
, mFile
);
295 /*i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());
296 i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getRemotePath());
297 i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());*/
300 setButtonsForTransferring();
302 getActivity().startService(i
);
303 mContainerActivity
.onFileStateChanged(); // this is not working; it is performed before the fileDownloadService registers it as 'in progress'
307 case R
.id
.fdKeepInSync
: {
308 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
309 mFile
.setKeepInSync(cb
.isChecked());
310 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
311 fdsm
.saveFile(mFile
);
312 if (mFile
.keepInSync()) {
313 onClick(getView().findViewById(R
.id
.fdDownloadBtn
));
315 mContainerActivity
.onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)
318 Intent intent
= new Intent(getActivity().getApplicationContext(),
319 FileObserverService
.class);
320 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
322 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
323 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
324 intent
.putExtra(FileObserverService
.KEY_CMD_ARG
, mFile
.getStoragePath());
325 Log
.e(TAG
, "starting observer service");
326 getActivity().startService(intent
);
330 case R
.id
.fdRenameBtn
: {
331 EditNameDialog dialog
= EditNameDialog
.newInstance(mFile
.getFileName());
332 dialog
.setOnDismissListener(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 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
347 case R
.id
.fdOpenBtn
: {
348 String storagePath
= mFile
.getStoragePath();
349 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
351 Intent i
= new Intent(Intent
.ACTION_VIEW
);
352 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
353 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
356 } catch (Throwable t
) {
357 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
358 boolean toastIt
= true
;
359 String mimeType
= "";
361 Intent i
= new Intent(Intent
.ACTION_VIEW
);
362 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
363 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
364 if (mimeType
!= null
) {
365 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
368 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
370 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
375 } catch (IndexOutOfBoundsException e
) {
376 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
378 } catch (ActivityNotFoundException e
) {
379 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
381 } catch (Throwable th
) {
382 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
386 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
394 Log
.e(TAG
, "Incorrect view clicked!");
397 /* else if (v.getId() == R.id.fdShareBtn) {
398 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
405 public void onConfirmation(String callerTag
) {
406 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
407 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
408 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
409 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
411 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
412 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
413 mLastRemoteOperation
.execute(wc
, this, mHandler
);
415 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
416 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
422 public void onNeutral(String callerTag
) {
423 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
425 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
427 mFile
.setStoragePath(null
);
428 fdsm
.saveFile(mFile
);
429 updateFileDetails(mFile
, mAccount
);
434 public void onCancel(String callerTag
) {
435 Log
.d(TAG
, "REMOVAL CANCELED");
440 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
442 * @return True when the fragment was created with the empty layout.
444 public boolean isEmpty() {
445 return mLayout
== R
.layout
.file_details_empty
;
450 * Can be used to get the file that is currently being displayed.
451 * @return The file on the screen.
453 public OCFile
getDisplayedFile(){
458 * Use this method to signal this Activity that it shall update its view.
460 * @param file : An {@link OCFile}
462 public void updateFileDetails(OCFile file
, Account ocAccount
) {
464 mAccount
= ocAccount
;
465 updateFileDetails(false
);
470 * Updates the view with all relevant details about that file.
472 * TODO Remove parameter when the transferring state of files is kept in database.
474 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
475 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
476 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
479 public void updateFileDetails(boolean transferring
) {
481 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
484 setFilename(mFile
.getFileName());
485 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
487 setFilesize(mFile
.getFileLength());
488 if(ocVersionSupportsTimeCreated()){
489 setTimeCreated(mFile
.getCreationTimestamp());
492 setTimeModified(mFile
.getModificationTimestamp());
494 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
495 cb
.setChecked(mFile
.keepInSync());
497 // configure UI for depending upon local state of the file
498 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
499 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
500 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
501 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
502 setButtonsForTransferring();
504 } else if (mFile
.isDown()) {
506 if (mFile
.getMimetype().startsWith("image/")) {
507 BitmapLoader bl
= new BitmapLoader();
508 bl
.execute(new String
[]{mFile
.getStoragePath()});
514 // TODO load default preview image; when the local file is removed, the preview remains there
515 setButtonsForRemote();
518 getView().invalidate();
523 * Updates the filename in view
524 * @param filename to set
526 private void setFilename(String filename
) {
527 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
529 tv
.setText(filename
);
533 * Updates the MIME type in view
534 * @param mimetype to set
536 private void setFiletype(String mimetype
) {
537 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
539 tv
.setText(mimetype
);
543 * Updates the file size in view
544 * @param filesize in bytes to set
546 private void setFilesize(long filesize
) {
547 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
549 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
553 * Updates the time that the file was created in view
554 * @param milliseconds Unix time to set
556 private void setTimeCreated(long milliseconds
){
557 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
558 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
560 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
561 tv
.setVisibility(View
.VISIBLE
);
562 tvLabel
.setVisibility(View
.VISIBLE
);
567 * Updates the time that the file was last modified
568 * @param milliseconds Unix time to set
570 private void setTimeModified(long milliseconds
){
571 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
573 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
578 * Enables or disables buttons for a file being downloaded
580 private void setButtonsForTransferring() {
582 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
583 downloadButton
.setText(R
.string
.common_cancel
);
584 //downloadButton.setEnabled(false);
586 // let's protect the user from himself ;)
587 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
588 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
589 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
590 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
595 * Enables or disables buttons for a file locally available
597 private void setButtonsForDown() {
599 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
600 downloadButton
.setText(R
.string
.filedetails_redownload
);
601 //downloadButton.setEnabled(true);
603 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
604 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
605 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
606 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
611 * Enables or disables buttons for a file not locally available
613 private void setButtonsForRemote() {
615 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
616 downloadButton
.setText(R
.string
.filedetails_download
);
618 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
619 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
620 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
621 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
627 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
628 * the time that the file was created. There is a chance that this will
629 * be fixed in future versions. Use this method to check if this version of
630 * ownCloud has this fix.
631 * @return True, if ownCloud the ownCloud version is supporting creation time
633 private boolean ocVersionSupportsTimeCreated(){
634 /*if(mAccount != null){
635 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
636 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
637 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
638 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
647 * Interface to implement by any Activity that includes some instance of FileDetailFragment
649 * @author David A. Velasco
651 public interface ContainerActivity
extends TransferServiceGetter
{
654 * Callback method invoked when the detail fragment wants to notice its container
655 * activity about a relevant state the file shown by the fragment.
657 * Added to notify to FileDisplayActivity about the need of refresh the files list.
659 * Currently called when:
660 * - a download is started;
661 * - a rename is completed;
662 * - a deletion is completed;
663 * - the 'inSync' flag is changed;
665 public void onFileStateChanged();
671 * Once the file download has finished -> update view
672 * @author Bartek Przybylski
674 private class DownloadFinishReceiver
extends BroadcastReceiver
{
676 public void onReceive(Context context
, Intent intent
) {
677 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
679 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
680 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
681 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
682 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
683 if (downloadWasFine
) {
684 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
)); // updates the local object without accessing the database again
686 updateFileDetails(false
); // it updates the buttons; must be called although !downloadWasFine
694 * Once the file upload has finished -> update view
696 * Being notified about the finish of an upload is necessary for the next sequence:
697 * 1. Upload a big file.
698 * 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
699 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
700 * 3. Click the file in the list to see its details.
701 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
703 private class UploadFinishReceiver
extends BroadcastReceiver
{
705 public void onReceive(Context context
, Intent intent
) {
706 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
708 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
709 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
710 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
711 if (mFile
.getRemotePath().equals(uploadRemotePath
)) {
713 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
714 mFile
= fdsm
.getFileByPath(mFile
.getRemotePath());
716 updateFileDetails(false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
723 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
724 @SuppressWarnings("unused")
725 private class ShareRunnable
implements Runnable
{
726 private String mPath
;
728 public ShareRunnable(String path
) {
733 AccountManager am
= AccountManager
.get(getActivity());
734 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
735 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
736 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
738 Log
.d("share", "sharing for version " + ocv
.toString());
740 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
741 String APPS_PATH
= "/apps/files_sharing/";
742 String SHARE_PATH
= "ajax/share.php";
744 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
746 final String WEBDAV_SCRIPT
= "webdav.php";
747 final String WEBDAV_FILES_LOCATION
= "/files/";
749 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
750 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
751 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
753 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
754 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
756 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
758 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
759 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
760 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
761 Log
.d("share", mPath
+"");
762 formparams
.add(new BasicNameValuePair("sources",mPath
));
763 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
764 formparams
.add(new BasicNameValuePair("permissions", "0"));
765 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
769 PropFindMethod find
= new PropFindMethod(url
+"/");
770 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
771 Log
.d("sharer", ""+ url
+"/");
773 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
774 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
777 int status2
= wc
.executeMethod(find
);
779 Log
.d("sharer", "propstatus "+status2
);
781 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
782 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
784 status2
= wc
.executeMethod(get
);
786 Log
.d("sharer", "getstatus "+status2
);
787 Log
.d("sharer", "" + get
.getResponseBodyAsString());
789 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
790 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
793 status
= wc
.executeMethod(post
);
794 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
795 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
797 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
798 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
800 String resp
= post
.getResponseBodyAsString();
801 Log
.d("share", ""+post
.getURI().toString());
802 Log
.d("share", "returned status " + status
);
803 Log
.d("share", " " +resp
);
805 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
809 JSONObject jsonObject
= new JSONObject (resp
);
810 String jsonStatus
= jsonObject
.getString("status");
811 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
813 String token
= jsonObject
.getString("data");
814 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
815 Log
.d("Actions:shareFile ok", "url: " + uri
);
817 } catch (Exception e
) {
821 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
827 public void onDismiss(EditNameDialog dialog
) {
828 if (dialog
.getResult()) {
829 String newFilename
= dialog
.getNewFilename();
830 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
831 mLastRemoteOperation
= new RenameFileOperation( mFile
,
834 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
835 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
836 mLastRemoteOperation
.execute(wc
, this, mHandler
);
837 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
838 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
843 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
844 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
846 protected Bitmap
doInBackground(String
... params
) {
847 Bitmap result
= null
;
848 if (params
.length
!= 1) return result
;
849 String storagePath
= params
[0];
852 BitmapFactory
.Options options
= new Options();
853 options
.inScaled
= true
;
854 options
.inPurgeable
= true
;
855 options
.inJustDecodeBounds
= true
;
856 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
857 options
.inPreferQualityOverSpeed
= false
;
859 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
860 options
.inMutable
= false
;
863 result
= BitmapFactory
.decodeFile(storagePath
, options
);
864 options
.inJustDecodeBounds
= false
;
866 int width
= options
.outWidth
;
867 int height
= options
.outHeight
;
869 if (width
>= 2048 || height
>= 2048) {
870 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
871 options
.inSampleSize
= scale
;
873 Display display
= getActivity().getWindowManager().getDefaultDisplay();
874 Point size
= new Point();
876 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
877 display
.getSize(size
);
878 screenwidth
= size
.x
;
880 screenwidth
= display
.getWidth();
883 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
885 if (width
> screenwidth
) {
886 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
887 options
.inSampleSize
= scale
;
890 result
= BitmapFactory
.decodeFile(storagePath
, options
);
892 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
894 } catch (OutOfMemoryError e
) {
896 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
898 } catch (NoSuchFieldError e
) {
900 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
902 } catch (Throwable t
) {
904 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
909 protected void onPostExecute(Bitmap result
) {
910 if (result
!= null
&& mPreview
!= null
) {
911 mPreview
.setImageBitmap(result
);
921 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
922 if (operation
.equals(mLastRemoteOperation
)) {
923 if (operation
instanceof RemoveFileOperation
) {
924 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
926 } else if (operation
instanceof RenameFileOperation
) {
927 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
933 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
934 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
935 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
937 if (result
.isSuccess()) {
938 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
940 if (inDisplayActivity
) {
942 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
943 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
944 transaction
.commit();
945 mContainerActivity
.onFileStateChanged();
947 getActivity().finish();
951 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
953 if (result
.isSslRecoverableException()) {
954 // TODO show the SSL warning dialog
959 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
960 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
961 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
963 if (result
.isSuccess()) {
964 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
965 mContainerActivity
.onFileStateChanged();
968 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
969 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
971 // TODO throw again the new rename dialog
973 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
975 if (result
.isSslRecoverableException()) {
976 // TODO show the SSL warning dialog