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
.FileStorageUtils
;
91 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
93 import com
.owncloud
.android
.R
;
94 import eu
.alefzero
.webdav
.WebdavClient
;
95 import eu
.alefzero
.webdav
.WebdavUtils
;
98 * This Fragment is used to display the details about a file.
100 * @author Bartek Przybylski
103 public class FileDetailFragment
extends SherlockFragment
implements
104 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
{
106 public static final String EXTRA_FILE
= "FILE";
107 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
109 private FileDetailFragment
.ContainerActivity mContainerActivity
;
113 private OCFile mFile
;
114 private Account mAccount
;
115 private ImageView mPreview
;
117 private DownloadFinishReceiver mDownloadFinishReceiver
;
118 private UploadFinishReceiver mUploadFinishReceiver
;
120 private Handler mHandler
;
121 private RemoteOperation mLastRemoteOperation
;
123 private static final String TAG
= "FileDetailFragment";
124 public static final String FTAG
= "FileDetails";
125 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
129 * Creates an empty details fragment.
131 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
133 public FileDetailFragment() {
136 mLayout
= R
.layout
.file_details_empty
;
141 * Creates a details fragment.
143 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
145 * @param fileToDetail An {@link OCFile} to show in the fragment
146 * @param ocAccount An ownCloud account; needed to start downloads
148 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
149 mFile
= fileToDetail
;
150 mAccount
= ocAccount
;
151 mLayout
= R
.layout
.file_details_empty
;
153 if(fileToDetail
!= null
&& ocAccount
!= null
) {
154 mLayout
= R
.layout
.file_details_fragment
;
160 public void onCreate(Bundle savedInstanceState
) {
161 super.onCreate(savedInstanceState
);
162 mHandler
= new Handler();
167 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
168 Bundle savedInstanceState
) {
169 super.onCreateView(inflater
, container
, savedInstanceState
);
171 if (savedInstanceState
!= null
) {
172 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
173 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
177 view
= inflater
.inflate(mLayout
, container
, false
);
180 if (mLayout
== R
.layout
.file_details_fragment
) {
181 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
182 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
183 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
184 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
185 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
186 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
187 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
199 public void onAttach(Activity activity
) {
200 super.onAttach(activity
);
202 mContainerActivity
= (ContainerActivity
) activity
;
203 } catch (ClassCastException e
) {
204 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
210 public void onSaveInstanceState(Bundle outState
) {
211 Log
.i(getClass().toString(), "onSaveInstanceState() start");
212 super.onSaveInstanceState(outState
);
213 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
214 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
215 Log
.i(getClass().toString(), "onSaveInstanceState() end");
220 public void onResume() {
223 mDownloadFinishReceiver
= new DownloadFinishReceiver();
224 IntentFilter filter
= new IntentFilter(
225 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
226 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
228 mUploadFinishReceiver
= new UploadFinishReceiver();
229 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
230 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
232 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
236 public void onPause() {
239 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
240 mDownloadFinishReceiver
= null
;
242 getActivity().unregisterReceiver(mUploadFinishReceiver
);
243 mUploadFinishReceiver
= null
;
245 if (mPreview
!= null
) {
251 public View
getView() {
252 return super.getView() == null ? mView
: super.getView();
258 public void onClick(View v
) {
260 case R
.id
.fdDownloadBtn
: {
261 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath())) {
262 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
263 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
264 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
265 downloaderBinder
.cancel(mAccount
, mFile
);
266 if (mFile
.isDown()) {
269 setButtonsForRemote();
272 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
273 uploaderBinder
.cancel(mAccount
, mFile
);
274 if (!mFile
.fileExists()) {
275 // TODO make something better
276 if (getActivity() instanceof FileDisplayActivity
) {
278 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
279 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
280 transaction
.commit();
281 mContainerActivity
.onFileStateChanged();
283 getActivity().finish();
286 } else if (mFile
.isDown()) {
289 setButtonsForRemote();
293 // ISSUE 6: this button should be promoted to 'synchronize' if the file is DOWN, not just redownload
294 Intent i
= new Intent(getActivity(), FileDownloader
.class);
295 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
296 i
.putExtra(FileDownloader
.EXTRA_FILE
, mFile
);
297 /*i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());
298 i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getRemotePath());
299 i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());*/
302 setButtonsForTransferring();
304 getActivity().startService(i
);
305 mContainerActivity
.onFileStateChanged(); // this is not working; it is performed before the fileDownloadService registers it as 'in progress'
309 case R
.id
.fdKeepInSync
: {
310 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
311 mFile
.setKeepInSync(cb
.isChecked());
312 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
313 fdsm
.saveFile(mFile
);
314 if (mFile
.keepInSync()) {
315 onClick(getView().findViewById(R
.id
.fdDownloadBtn
));
317 mContainerActivity
.onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)
320 Intent intent
= new Intent(getActivity().getApplicationContext(),
321 FileObserverService
.class);
322 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
324 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
325 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
326 String localPath
= mFile
.getStoragePath();
327 if (localPath
== null
|| localPath
.length() <= 0) {
328 localPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mFile
);
330 intent
.putExtra(FileObserverService
.KEY_CMD_ARG
, localPath
);
331 Log
.e(TAG
, "starting observer service");
332 getActivity().startService(intent
);
336 case R
.id
.fdRenameBtn
: {
337 EditNameDialog dialog
= EditNameDialog
.newInstance(mFile
.getFileName());
338 dialog
.setOnDismissListener(this);
339 dialog
.show(getFragmentManager(), "nameeditdialog");
342 case R
.id
.fdRemoveBtn
: {
343 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
344 R
.string
.confirmation_remove_alert
,
345 new String
[]{mFile
.getFileName()},
346 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
347 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
348 R
.string
.common_cancel
);
349 confDialog
.setOnConfirmationListener(this);
350 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
353 case R
.id
.fdOpenBtn
: {
354 String storagePath
= mFile
.getStoragePath();
355 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
357 Intent i
= new Intent(Intent
.ACTION_VIEW
);
358 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
359 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
362 } catch (Throwable t
) {
363 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
364 boolean toastIt
= true
;
365 String mimeType
= "";
367 Intent i
= new Intent(Intent
.ACTION_VIEW
);
368 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
369 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
370 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
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 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
409 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
410 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
412 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
413 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
414 mLastRemoteOperation
.execute(wc
, this, mHandler
);
416 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
417 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
423 public void onNeutral(String callerTag
) {
424 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
426 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
428 mFile
.setStoragePath(null
);
429 fdsm
.saveFile(mFile
);
430 updateFileDetails(mFile
, mAccount
);
435 public void onCancel(String callerTag
) {
436 Log
.d(TAG
, "REMOVAL CANCELED");
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
;
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 mAccount
= ocAccount
;
471 * Updates the view with all relevant details about that file.
473 public void updateFileDetails() {
475 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
478 setFilename(mFile
.getFileName());
479 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
481 setFilesize(mFile
.getFileLength());
482 if(ocVersionSupportsTimeCreated()){
483 setTimeCreated(mFile
.getCreationTimestamp());
486 setTimeModified(mFile
.getModificationTimestamp());
488 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
489 cb
.setChecked(mFile
.keepInSync());
491 // configure UI for depending upon local state of the file
492 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
493 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
494 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
495 if ((downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
496 setButtonsForTransferring();
498 } else if (mFile
.isDown()) {
500 if (mFile
.getMimetype().startsWith("image/")) {
501 BitmapLoader bl
= new BitmapLoader();
502 bl
.execute(new String
[]{mFile
.getStoragePath()});
508 setButtonsForRemote();
515 * Updates the filename in view
516 * @param filename to set
518 private void setFilename(String filename
) {
519 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
521 tv
.setText(filename
);
525 * Updates the MIME type in view
526 * @param mimetype to set
528 private void setFiletype(String mimetype
) {
529 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
531 tv
.setText(mimetype
);
535 * Updates the file size in view
536 * @param filesize in bytes to set
538 private void setFilesize(long filesize
) {
539 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
541 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
545 * Updates the time that the file was created in view
546 * @param milliseconds Unix time to set
548 private void setTimeCreated(long milliseconds
){
549 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
550 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
552 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
553 tv
.setVisibility(View
.VISIBLE
);
554 tvLabel
.setVisibility(View
.VISIBLE
);
559 * Updates the time that the file was last modified
560 * @param milliseconds Unix time to set
562 private void setTimeModified(long milliseconds
){
563 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
565 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
570 * Enables or disables buttons for a file being downloaded
572 private void setButtonsForTransferring() {
574 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
575 downloadButton
.setText(R
.string
.common_cancel
);
576 //downloadButton.setEnabled(false);
578 // let's protect the user from himself ;)
579 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
580 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
581 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
582 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
587 * Enables or disables buttons for a file locally available
589 private void setButtonsForDown() {
591 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
592 downloadButton
.setText(R
.string
.filedetails_redownload
);
593 //downloadButton.setEnabled(true);
595 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
596 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
597 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
598 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
603 * Enables or disables buttons for a file not locally available
605 private void setButtonsForRemote() {
607 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
608 downloadButton
.setText(R
.string
.filedetails_download
);
610 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
611 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
612 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
613 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
619 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
620 * the time that the file was created. There is a chance that this will
621 * be fixed in future versions. Use this method to check if this version of
622 * ownCloud has this fix.
623 * @return True, if ownCloud the ownCloud version is supporting creation time
625 private boolean ocVersionSupportsTimeCreated(){
626 /*if(mAccount != null){
627 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
628 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
629 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
630 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
639 * Interface to implement by any Activity that includes some instance of FileDetailFragment
641 * @author David A. Velasco
643 public interface ContainerActivity
extends TransferServiceGetter
{
646 * Callback method invoked when the detail fragment wants to notice its container
647 * activity about a relevant state the file shown by the fragment.
649 * Added to notify to FileDisplayActivity about the need of refresh the files list.
651 * Currently called when:
652 * - a download is started;
653 * - a rename is completed;
654 * - a deletion is completed;
655 * - the 'inSync' flag is changed;
657 public void onFileStateChanged();
663 * Once the file download has finished -> update view
664 * @author Bartek Przybylski
666 private class DownloadFinishReceiver
extends BroadcastReceiver
{
668 public void onReceive(Context context
, Intent intent
) {
669 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
671 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
672 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
673 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
674 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
675 if (downloadWasFine
) {
676 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
)); // updates the local object without accessing the database again
678 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
686 * Once the file upload has finished -> update view
688 * Being notified about the finish of an upload is necessary for the next sequence:
689 * 1. Upload a big file.
690 * 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
691 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
692 * 3. Click the file in the list to see its details.
693 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
695 private class UploadFinishReceiver
extends BroadcastReceiver
{
697 public void onReceive(Context context
, Intent intent
) {
698 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
700 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
701 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
702 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
703 if (mFile
.getRemotePath().equals(uploadRemotePath
)) {
705 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
706 mFile
= fdsm
.getFileByPath(mFile
.getRemotePath());
708 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
715 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
716 @SuppressWarnings("unused")
717 private class ShareRunnable
implements Runnable
{
718 private String mPath
;
720 public ShareRunnable(String path
) {
725 AccountManager am
= AccountManager
.get(getActivity());
726 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
727 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
728 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
730 Log
.d("share", "sharing for version " + ocv
.toString());
732 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
733 String APPS_PATH
= "/apps/files_sharing/";
734 String SHARE_PATH
= "ajax/share.php";
736 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
738 final String WEBDAV_SCRIPT
= "webdav.php";
739 final String WEBDAV_FILES_LOCATION
= "/files/";
741 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
742 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
743 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
745 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
746 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
748 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
750 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
751 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
752 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
753 Log
.d("share", mPath
+"");
754 formparams
.add(new BasicNameValuePair("sources",mPath
));
755 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
756 formparams
.add(new BasicNameValuePair("permissions", "0"));
757 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
761 PropFindMethod find
= new PropFindMethod(url
+"/");
762 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
763 Log
.d("sharer", ""+ url
+"/");
765 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
766 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
769 int status2
= wc
.executeMethod(find
);
771 Log
.d("sharer", "propstatus "+status2
);
773 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
774 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
776 status2
= wc
.executeMethod(get
);
778 Log
.d("sharer", "getstatus "+status2
);
779 Log
.d("sharer", "" + get
.getResponseBodyAsString());
781 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
782 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
785 status
= wc
.executeMethod(post
);
786 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
787 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
789 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
790 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
792 String resp
= post
.getResponseBodyAsString();
793 Log
.d("share", ""+post
.getURI().toString());
794 Log
.d("share", "returned status " + status
);
795 Log
.d("share", " " +resp
);
797 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
801 JSONObject jsonObject
= new JSONObject (resp
);
802 String jsonStatus
= jsonObject
.getString("status");
803 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
805 String token
= jsonObject
.getString("data");
806 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
807 Log
.d("Actions:shareFile ok", "url: " + uri
);
809 } catch (Exception e
) {
813 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
819 public void onDismiss(EditNameDialog dialog
) {
820 if (dialog
.getResult()) {
821 String newFilename
= dialog
.getNewFilename();
822 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
823 mLastRemoteOperation
= new RenameFileOperation( mFile
,
825 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
826 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
827 mLastRemoteOperation
.execute(wc
, this, mHandler
);
828 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
829 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
834 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
835 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
837 protected Bitmap
doInBackground(String
... params
) {
838 Bitmap result
= null
;
839 if (params
.length
!= 1) return result
;
840 String storagePath
= params
[0];
843 BitmapFactory
.Options options
= new Options();
844 options
.inScaled
= true
;
845 options
.inPurgeable
= true
;
846 options
.inJustDecodeBounds
= true
;
847 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
848 options
.inPreferQualityOverSpeed
= false
;
850 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
851 options
.inMutable
= false
;
854 result
= BitmapFactory
.decodeFile(storagePath
, options
);
855 options
.inJustDecodeBounds
= false
;
857 int width
= options
.outWidth
;
858 int height
= options
.outHeight
;
860 if (width
>= 2048 || height
>= 2048) {
861 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
862 options
.inSampleSize
= scale
;
864 Display display
= getActivity().getWindowManager().getDefaultDisplay();
865 Point size
= new Point();
867 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
868 display
.getSize(size
);
869 screenwidth
= size
.x
;
871 screenwidth
= display
.getWidth();
874 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
876 if (width
> screenwidth
) {
877 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
878 options
.inSampleSize
= scale
;
881 result
= BitmapFactory
.decodeFile(storagePath
, options
);
883 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
885 } catch (OutOfMemoryError e
) {
887 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
889 } catch (NoSuchFieldError e
) {
891 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
893 } catch (Throwable t
) {
895 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
900 protected void onPostExecute(Bitmap result
) {
901 if (result
!= null
&& mPreview
!= null
) {
902 mPreview
.setImageBitmap(result
);
912 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
913 if (operation
.equals(mLastRemoteOperation
)) {
914 if (operation
instanceof RemoveFileOperation
) {
915 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
917 } else if (operation
instanceof RenameFileOperation
) {
918 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
924 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
925 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
926 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
928 if (result
.isSuccess()) {
929 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
931 if (inDisplayActivity
) {
933 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
934 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
935 transaction
.commit();
936 mContainerActivity
.onFileStateChanged();
938 getActivity().finish();
942 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
944 if (result
.isSslRecoverableException()) {
945 // TODO show the SSL warning dialog
950 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
951 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
952 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
954 if (result
.isSuccess()) {
955 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
956 mContainerActivity
.onFileStateChanged();
959 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
960 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
962 // TODO throw again the new rename dialog
964 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
966 if (result
.isSslRecoverableException()) {
967 // TODO show the SSL warning dialog