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 eu
.alefzero
.owncloud
.ui
.fragment
;
21 import java
.io
.IOException
;
22 import java
.util
.ArrayList
;
23 import java
.util
.List
;
25 import org
.apache
.commons
.httpclient
.HttpException
;
26 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
27 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
28 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
29 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
30 import org
.apache
.http
.HttpStatus
;
31 import org
.apache
.http
.NameValuePair
;
32 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
33 import org
.apache
.http
.message
.BasicNameValuePair
;
34 import org
.apache
.http
.protocol
.HTTP
;
35 import org
.apache
.jackrabbit
.webdav
.client
.methods
.DavMethodBase
;
36 import org
.apache
.jackrabbit
.webdav
.client
.methods
.DeleteMethod
;
37 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
38 import org
.json
.JSONException
;
39 import org
.json
.JSONObject
;
41 import android
.accounts
.Account
;
42 import android
.accounts
.AccountManager
;
43 import android
.annotation
.SuppressLint
;
44 import android
.app
.Activity
;
45 import android
.content
.ActivityNotFoundException
;
46 import android
.content
.BroadcastReceiver
;
47 import android
.content
.Context
;
48 import android
.content
.Intent
;
49 import android
.content
.IntentFilter
;
50 import android
.content
.res
.Resources
.NotFoundException
;
51 import android
.graphics
.Bitmap
;
52 import android
.graphics
.BitmapFactory
;
53 import android
.graphics
.BitmapFactory
.Options
;
54 import android
.graphics
.Point
;
55 import android
.net
.Uri
;
56 import android
.os
.AsyncTask
;
57 import android
.os
.Bundle
;
58 import android
.os
.Handler
;
59 import android
.support
.v4
.app
.FragmentTransaction
;
60 import android
.util
.Log
;
61 import android
.view
.Display
;
62 import android
.view
.LayoutInflater
;
63 import android
.view
.View
;
64 import android
.view
.View
.OnClickListener
;
65 import android
.view
.ViewGroup
;
66 import android
.view
.WindowManager
.LayoutParams
;
67 import android
.webkit
.MimeTypeMap
;
68 import android
.widget
.Button
;
69 import android
.widget
.CheckBox
;
70 import android
.widget
.ImageView
;
71 import android
.widget
.TextView
;
72 import android
.widget
.Toast
;
74 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
75 import com
.actionbarsherlock
.app
.SherlockFragment
;
77 import eu
.alefzero
.owncloud
.AccountUtils
;
78 import eu
.alefzero
.owncloud
.DisplayUtils
;
79 import eu
.alefzero
.owncloud
.R
;
80 import eu
.alefzero
.owncloud
.authenticator
.AccountAuthenticator
;
81 import eu
.alefzero
.owncloud
.datamodel
.FileDataStorageManager
;
82 import eu
.alefzero
.owncloud
.datamodel
.OCFile
;
83 import eu
.alefzero
.owncloud
.files
.services
.FileDownloader
;
84 import eu
.alefzero
.owncloud
.files
.services
.FileUploader
;
85 import eu
.alefzero
.owncloud
.ui
.activity
.FileDisplayActivity
;
86 import eu
.alefzero
.owncloud
.utils
.OwnCloudVersion
;
87 import eu
.alefzero
.webdav
.WebdavClient
;
88 import eu
.alefzero
.webdav
.WebdavUtils
;
91 * This Fragment is used to display the details about a file.
93 * @author Bartek Przybylski
96 public class FileDetailFragment
extends SherlockFragment
implements
97 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
99 public static final String EXTRA_FILE
= "FILE";
100 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
102 private FileDetailFragment
.ContainerActivity mContainerActivity
;
106 private OCFile mFile
;
107 private Account mAccount
;
108 private ImageView mPreview
;
110 private DownloadFinishReceiver mDownloadFinishReceiver
;
111 private UploadFinishReceiver mUploadFinishReceiver
;
113 private static final String TAG
= "FileDetailFragment";
114 public static final String FTAG
= "FileDetails";
115 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
119 * Creates an empty details fragment.
121 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
123 public FileDetailFragment() {
126 mLayout
= R
.layout
.file_details_empty
;
131 * Creates a details fragment.
133 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
135 * @param fileToDetail An {@link OCFile} to show in the fragment
136 * @param ocAccount An ownCloud account; needed to start downloads
138 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
){
139 mFile
= fileToDetail
;
140 mAccount
= ocAccount
;
141 mLayout
= R
.layout
.file_details_empty
;
143 if(fileToDetail
!= null
&& ocAccount
!= null
) {
144 mLayout
= R
.layout
.file_details_fragment
;
153 public void onAttach(Activity activity
) {
154 super.onAttach(activity
);
156 mContainerActivity
= (ContainerActivity
) activity
;
157 } catch (ClassCastException e
) {
158 throw new ClassCastException(activity
.toString() + " must implement FileListFragment.ContainerActivity");
164 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
165 Bundle savedInstanceState
) {
166 super.onCreateView(inflater
, container
, savedInstanceState
);
168 if (savedInstanceState
!= null
) {
169 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
170 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
174 view
= inflater
.inflate(mLayout
, container
, false
);
177 if (mLayout
== R
.layout
.file_details_fragment
) {
178 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
179 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
180 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
181 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
182 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
183 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
184 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
193 public void onSaveInstanceState(Bundle outState
) {
194 Log
.i(getClass().toString(), "onSaveInstanceState() start");
195 super.onSaveInstanceState(outState
);
196 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
197 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
198 Log
.i(getClass().toString(), "onSaveInstanceState() end");
203 public void onResume() {
206 mDownloadFinishReceiver
= new DownloadFinishReceiver();
207 IntentFilter filter
= new IntentFilter(
208 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
209 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
211 mUploadFinishReceiver
= new UploadFinishReceiver();
212 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
213 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
215 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
219 public void onPause() {
222 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
223 mDownloadFinishReceiver
= null
;
225 getActivity().unregisterReceiver(mUploadFinishReceiver
);
226 mUploadFinishReceiver
= null
;
228 if (mPreview
!= null
) {
234 public View
getView() {
235 return super.getView() == null ? mView
: super.getView();
241 public void onClick(View v
) {
243 case R
.id
.fdDownloadBtn
: {
244 Intent i
= new Intent(getActivity(), FileDownloader
.class);
245 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
246 i
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, mFile
.getRemotePath());
247 i
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, mFile
.getRemotePath());
248 i
.putExtra(FileDownloader
.EXTRA_FILE_SIZE
, mFile
.getFileLength());
251 setButtonsForTransferring();
253 getActivity().startService(i
);
254 mContainerActivity
.onFileStateChanged(); // this is not working; it is performed before the fileDownloadService registers it as 'in progress'
257 case R
.id
.fdKeepInSync
: {
258 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
259 mFile
.setKeepInSync(cb
.isChecked());
260 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
261 fdsm
.saveFile(mFile
);
262 if (mFile
.keepInSync()) {
263 onClick(getView().findViewById(R
.id
.fdDownloadBtn
));
265 mContainerActivity
.onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)
269 case R
.id
.fdRenameBtn
: {
270 EditNameFragment dialog
= EditNameFragment
.newInstance(mFile
.getFileName());
271 dialog
.show(getFragmentManager(), "nameeditdialog");
272 dialog
.setOnDismissListener(this);
275 case R
.id
.fdRemoveBtn
: {
276 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(R
.string
.confirmation_remove_alert
, new String
[]{mFile
.getFileName()});
277 confDialog
.setOnConfirmationListener(this);
278 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
281 case R
.id
.fdOpenBtn
: {
282 String storagePath
= mFile
.getStoragePath();
283 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
285 Intent i
= new Intent(Intent
.ACTION_VIEW
);
286 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
287 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
290 } catch (Throwable t
) {
291 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
292 boolean toastIt
= true
;
293 String mimeType
= "";
295 Intent i
= new Intent(Intent
.ACTION_VIEW
);
296 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
297 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
298 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
299 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
304 } catch (IndexOutOfBoundsException e
) {
305 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
307 } catch (ActivityNotFoundException e
) {
308 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
310 } catch (Throwable th
) {
311 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
315 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
323 Log
.e(TAG
, "Incorrect view clicked!");
326 /* else if (v.getId() == R.id.fdShareBtn) {
327 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
334 public void onConfirmation(boolean confirmation
, String callerTag
) {
335 if (confirmation
&& callerTag
.equals(FTAG_CONFIRMATION
)) {
336 Log
.e("ASD","onConfirmation");
337 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
338 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
339 new Thread(new RemoveRunnable(mFile
, mAccount
, new Handler())).start();
341 } else if (!confirmation
) Log
.d(TAG
, "REMOVAL CANCELED");
346 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
348 * @return True when the fragment was created with the empty layout.
350 public boolean isEmpty() {
351 return mLayout
== R
.layout
.file_details_empty
;
356 * Can be used to get the file that is currently being displayed.
357 * @return The file on the screen.
359 public OCFile
getDisplayedFile(){
364 * Use this method to signal this Activity that it shall update its view.
366 * @param file : An {@link OCFile}
368 public void updateFileDetails(OCFile file
, Account ocAccount
) {
370 mAccount
= ocAccount
;
376 * Updates the view with all relevant details about that file.
378 public void updateFileDetails() {
380 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
383 setFilename(mFile
.getFileName());
384 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
386 setFilesize(mFile
.getFileLength());
387 if(ocVersionSupportsTimeCreated()){
388 setTimeCreated(mFile
.getCreationTimestamp());
391 setTimeModified(mFile
.getModificationTimestamp());
393 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
394 cb
.setChecked(mFile
.keepInSync());
396 // configure UI for depending upon local state of the file
397 if (FileDownloader
.isDownloading(mAccount
, mFile
.getRemotePath()) || FileUploader
.isUploading(mAccount
, mFile
.getRemotePath())) {
398 setButtonsForTransferring();
400 } else if (mFile
.isDown()) {
402 if (mFile
.getMimetype().startsWith("image/")) {
403 BitmapLoader bl
= new BitmapLoader();
404 bl
.execute(new String
[]{mFile
.getStoragePath()});
409 // Change download button to open button
410 /*downloadButton.setText(R.string.filedetails_open);
411 downloadButton.setOnClickListener(new OnClickListener() {
413 public void onClick(View v) {
414 String storagePath = mFile.getStoragePath();
415 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
417 Intent i = new Intent(Intent.ACTION_VIEW);
418 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
419 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
422 } catch (Throwable t) {
423 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
424 boolean toastIt = true;
425 String mimeType = "";
427 Intent i = new Intent(Intent.ACTION_VIEW);
428 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
429 if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {
430 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
431 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
436 } catch (IndexOutOfBoundsException e) {
437 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
439 } catch (ActivityNotFoundException e) {
440 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
442 } catch (Throwable th) {
443 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
447 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
455 setButtonsForRemote();
462 * Updates the filename in view
463 * @param filename to set
465 private void setFilename(String filename
) {
466 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
468 tv
.setText(filename
);
472 * Updates the MIME type in view
473 * @param mimetype to set
475 private void setFiletype(String mimetype
) {
476 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
478 tv
.setText(mimetype
);
482 * Updates the file size in view
483 * @param filesize in bytes to set
485 private void setFilesize(long filesize
) {
486 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
488 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
492 * Updates the time that the file was created in view
493 * @param milliseconds Unix time to set
495 private void setTimeCreated(long milliseconds
){
496 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
497 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
499 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
500 tv
.setVisibility(View
.VISIBLE
);
501 tvLabel
.setVisibility(View
.VISIBLE
);
506 * Updates the time that the file was last modified
507 * @param milliseconds Unix time to set
509 private void setTimeModified(long milliseconds
){
510 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
512 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
517 * Enables or disables buttons for a file being downloaded
519 private void setButtonsForTransferring() {
521 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
522 //downloadButton.setText(R.string.filedetails_download_in_progress); // ugly
523 downloadButton
.setEnabled(false
); // TODO replace it with a 'cancel download' button
525 // let's protect the user from himself ;)
526 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
527 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
528 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
533 * Enables or disables buttons for a file locally available
535 private void setButtonsForDown() {
537 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
538 //downloadButton.setText(R.string.filedetails_redownload); // ugly
539 downloadButton
.setEnabled(true
);
541 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
542 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
543 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
548 * Enables or disables buttons for a file not locally available
550 private void setButtonsForRemote() {
552 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
553 //downloadButton.setText(R.string.filedetails_download); // unnecessary
554 downloadButton
.setEnabled(true
);
556 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
557 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
558 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
564 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
565 * the time that the file was created. There is a chance that this will
566 * be fixed in future versions. Use this method to check if this version of
567 * ownCloud has this fix.
568 * @return True, if ownCloud the ownCloud version is supporting creation time
570 private boolean ocVersionSupportsTimeCreated(){
571 /*if(mAccount != null){
572 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
573 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
574 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
575 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
584 * Interface to implement by any Activity that includes some instance of FileDetailFragment
586 * @author David A. Velasco
588 public interface ContainerActivity
{
591 * Callback method invoked when the detail fragment wants to notice its container
592 * activity about a relevant state the file shown by the fragment.
594 * Added to notify to FileDisplayActivity about the need of refresh the files list.
596 * Currently called when:
597 * - a download is started;
598 * - a rename is completed;
599 * - a deletion is completed;
600 * - the 'inSync' flag is changed;
602 public void onFileStateChanged();
608 * Once the file download has finished -> update view
609 * @author Bartek Przybylski
611 private class DownloadFinishReceiver
extends BroadcastReceiver
{
613 public void onReceive(Context context
, Intent intent
) {
614 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
616 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
617 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
618 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
619 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
620 if (downloadWasFine
) {
621 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
)); // updates the local object without accessing the database again
623 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
631 * Once the file upload has finished -> update view
633 * Being notified about the finish of an upload is necessary for the next sequence:
634 * 1. Upload a big file.
635 * 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
636 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
637 * 3. Click the file in the list to see its details.
638 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
640 private class UploadFinishReceiver
extends BroadcastReceiver
{
642 public void onReceive(Context context
, Intent intent
) {
643 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
645 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
646 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
647 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
648 if (mFile
.getRemotePath().equals(uploadRemotePath
)) {
650 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
651 mFile
= fdsm
.getFileByPath(mFile
.getRemotePath());
653 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
660 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
661 private class ShareRunnable
implements Runnable
{
662 private String mPath
;
664 public ShareRunnable(String path
) {
669 AccountManager am
= AccountManager
.get(getActivity());
670 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
671 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
672 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
674 Log
.d("share", "sharing for version " + ocv
.toString());
676 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
677 String APPS_PATH
= "/apps/files_sharing/";
678 String SHARE_PATH
= "ajax/share.php";
680 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
682 final String WEBDAV_SCRIPT
= "webdav.php";
683 final String WEBDAV_FILES_LOCATION
= "/files/";
685 WebdavClient wc
= new WebdavClient();
686 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
687 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
689 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
690 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
692 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
694 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
695 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
696 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
697 Log
.d("share", mPath
+"");
698 formparams
.add(new BasicNameValuePair("sources",mPath
));
699 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
700 formparams
.add(new BasicNameValuePair("permissions", "0"));
701 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
705 PropFindMethod find
= new PropFindMethod(url
+"/");
706 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
707 Log
.d("sharer", ""+ url
+"/");
708 wc
.setCredentials(account
.name
.substring(0, account
.name
.lastIndexOf('@')), am
.getPassword(account
));
710 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
711 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
714 int status2
= wc
.executeMethod(find
);
716 Log
.d("sharer", "propstatus "+status2
);
718 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
719 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
721 status2
= wc
.executeMethod(get
);
723 Log
.d("sharer", "getstatus "+status2
);
724 Log
.d("sharer", "" + get
.getResponseBodyAsString());
726 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
727 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
730 status
= wc
.executeMethod(post
);
731 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
732 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
734 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
735 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
737 String resp
= post
.getResponseBodyAsString();
738 Log
.d("share", ""+post
.getURI().toString());
739 Log
.d("share", "returned status " + status
);
740 Log
.d("share", " " +resp
);
742 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
746 JSONObject jsonObject
= new JSONObject (resp
);
747 String jsonStatus
= jsonObject
.getString("status");
748 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
750 String token
= jsonObject
.getString("data");
751 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
752 Log
.d("Actions:shareFile ok", "url: " + uri
);
754 } catch (HttpException e
) {
755 // TODO Auto-generated catch block
757 } catch (IOException e
) {
758 // TODO Auto-generated catch block
760 } catch (JSONException e
) {
761 // TODO Auto-generated catch block
763 } catch (Exception e
) {
764 // TODO Auto-generated catch block
768 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
774 public void onDismiss(EditNameFragment dialog
) {
775 if (dialog
instanceof EditNameFragment
) {
776 if (((EditNameFragment
)dialog
).getResult()) {
777 String newFilename
= ((EditNameFragment
)dialog
).getNewFilename();
778 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
779 if (!newFilename
.equals(mFile
.getFileName())) {
780 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
781 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
782 OCFile newFile
= new OCFile(fdsm
.getFileById(mFile
.getParentId()).getRemotePath() + newFilename
);
783 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
784 newFile
.setFileId(mFile
.getFileId());
785 newFile
.setFileLength(mFile
.getFileLength());
786 newFile
.setKeepInSync(mFile
.keepInSync());
787 newFile
.setLastSyncDate(mFile
.getLastSyncDate());
788 newFile
.setMimetype(mFile
.getMimetype());
789 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
790 newFile
.setParentId(mFile
.getParentId());
791 if (mFile
.isDown()) {
792 File f
= new File(mFile
.getStoragePath());
793 Log
.e(TAG
, f
.getAbsolutePath());
794 f
.renameTo(new File(f
.getParent() + File
.separator
+ newFilename
)); // TODO check if fails
795 Log
.e(TAG
, f
.getParent() + File
.separator
+ newFilename
);
796 newFile
.setStoragePath(f
.getParent() + File
.separator
+ newFilename
);
799 new Thread(new RenameRunnable(mFile
, newFile
, mAccount
, new Handler())).start();
805 Log
.e(TAG
, "Unknown dialog instance passed to onDismissDalog: " + dialog
.getClass().getCanonicalName());
810 private class RenameRunnable
implements Runnable
{
816 public RenameRunnable(OCFile oldFile
, OCFile newFile
, Account account
, Handler handler
) {
824 WebdavClient wc
= new WebdavClient(mAccount
, getSherlockActivity().getApplicationContext());
825 wc
.allowSelfsignedCertificates();
826 AccountManager am
= AccountManager
.get(getSherlockActivity());
827 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
828 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
829 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
830 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()));
832 Log
.e("ASD", Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
833 LocalMoveMethod move
= new LocalMoveMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()),
834 Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
837 int status
= wc
.executeMethod(move
);
838 if (move
.succeeded()) {
839 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
840 fdsm
.removeFile(mOld
);
843 mHandler
.post(new Runnable() {
846 updateFileDetails(mFile
, mAccount
);
847 mContainerActivity
.onFileStateChanged();
851 Log
.e("ASD", ""+move
.getQueryString());
852 Log
.d("move", "returned status " + status
);
853 } catch (HttpException e
) {
854 // TODO Auto-generated catch block
856 } catch (IOException e
) {
857 // TODO Auto-generated catch block
861 private class LocalMoveMethod
extends DavMethodBase
{
863 public LocalMoveMethod(String uri
, String dest
) {
865 addRequestHeader(new org
.apache
.commons
.httpclient
.Header("Destination", dest
));
869 public String
getName() {
874 protected boolean isSuccess(int status
) {
875 return status
== 201 || status
== 204;
881 private static class EditNameFragment
extends SherlockDialogFragment
implements OnClickListener
{
883 private String mNewFilename
;
884 private boolean mResult
;
885 private FileDetailFragment mListener
;
887 static public EditNameFragment
newInstance(String filename
) {
888 EditNameFragment f
= new EditNameFragment();
889 Bundle args
= new Bundle();
890 args
.putString("filename", filename
);
891 f
.setArguments(args
);
896 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
, Bundle savedInstanceState
) {
897 View v
= inflater
.inflate(R
.layout
.edit_box_dialog
, container
, false
);
899 String currentName
= getArguments().getString("filename");
900 if (currentName
== null
)
903 ((Button
)v
.findViewById(R
.id
.cancel
)).setOnClickListener(this);
904 ((Button
)v
.findViewById(R
.id
.ok
)).setOnClickListener(this);
905 ((TextView
)v
.findViewById(R
.id
.user_input
)).setText(currentName
);
906 ((TextView
)v
.findViewById(R
.id
.user_input
)).requestFocus();
907 getDialog().getWindow().setSoftInputMode(LayoutParams
.SOFT_INPUT_STATE_VISIBLE
);
914 public void onClick(View view
) {
915 switch (view
.getId()) {
917 mNewFilename
= ((TextView
)getView().findViewById(R
.id
.user_input
)).getText().toString();
920 case R
.id
.cancel
: { // fallthought
922 mListener
.onDismiss(this);
927 void setOnDismissListener(FileDetailFragment listener
) {
928 mListener
= listener
;
931 public String
getNewFilename() {
935 // true if user click ok
936 public boolean getResult() {
942 private class RemoveRunnable
implements Runnable
{
944 /** Arbitrary timeout for deletion */
945 public final static int DELETION_TIMEOUT
= 5000;
948 OCFile mFileToRemove
;
951 public RemoveRunnable(OCFile fileToRemove
, Account account
, Handler handler
) {
952 mFileToRemove
= fileToRemove
;
958 WebdavClient wc
= new WebdavClient(mAccount
, getSherlockActivity().getApplicationContext());
959 wc
.allowSelfsignedCertificates();
960 AccountManager am
= AccountManager
.get(getSherlockActivity());
961 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
962 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
963 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
964 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
966 DeleteMethod delete
= new DeleteMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
968 boolean success
= false
;
970 int status
= wc
.executeMethod(delete
, DELETION_TIMEOUT
);
971 if (delete
.succeeded()) {
972 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
973 fdsm
.removeFile(mFileToRemove
);
974 mHandler
.post(new Runnable() {
978 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
980 if (getActivity() instanceof FileDisplayActivity
) {
982 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
983 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
984 transaction
.commit();
985 mContainerActivity
.onFileStateChanged();
988 getActivity().finish();
991 } catch (NotFoundException e
) {
998 Log
.e("ASD", ""+ delete
.getQueryString());
999 Log
.d("delete", "returned status " + status
);
1001 } catch (HttpException e
) {
1002 e
.printStackTrace();
1004 } catch (IOException e
) {
1005 e
.printStackTrace();
1009 mHandler
.post(new Runnable() {
1013 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1016 } catch (NotFoundException e
) {
1017 e
.printStackTrace();
1027 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
1028 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1030 protected Bitmap
doInBackground(String
... params
) {
1031 Bitmap result
= null
;
1032 if (params
.length
!= 1) return result
;
1033 String storagePath
= params
[0];
1036 BitmapFactory
.Options options
= new Options();
1037 options
.inScaled
= true
;
1038 options
.inPurgeable
= true
;
1039 options
.inJustDecodeBounds
= true
;
1040 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
1041 options
.inPreferQualityOverSpeed
= false
;
1043 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
1044 options
.inMutable
= false
;
1047 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1048 options
.inJustDecodeBounds
= false
;
1050 int width
= options
.outWidth
;
1051 int height
= options
.outHeight
;
1053 if (width
>= 2048 || height
>= 2048) {
1054 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
1055 options
.inSampleSize
= scale
;
1057 Display display
= getActivity().getWindowManager().getDefaultDisplay();
1058 Point size
= new Point();
1060 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
1061 display
.getSize(size
);
1062 screenwidth
= size
.x
;
1064 screenwidth
= display
.getWidth();
1067 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
1069 if (width
> screenwidth
) {
1070 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
1071 options
.inSampleSize
= scale
;
1074 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1076 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
1078 } catch (OutOfMemoryError e
) {
1080 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
1082 } catch (NoSuchFieldError e
) {
1084 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
1086 } catch (Throwable t
) {
1088 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
1093 protected void onPostExecute(Bitmap result
) {
1094 if (result
!= null
&& mPreview
!= null
) {
1095 mPreview
.setImageBitmap(result
);